test.cc 922 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definition is linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. } // namespace tls
  68. } // namespace httplib
  69. #endif
  70. using namespace std;
  71. using namespace httplib;
  72. const char *HOST = "localhost";
  73. static int get_base_port() {
  74. const char *shard = getenv("GTEST_SHARD_INDEX");
  75. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  76. }
  77. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  78. // New standalone tests MUST use svr.bind_to_any_port() instead.
  79. const int PORT = get_base_port();
  80. const string LONG_QUERY_VALUE = string(25000, '@');
  81. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  82. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  83. const string TOO_LONG_QUERY_URL =
  84. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  85. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  86. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  87. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  88. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  89. return file.name == key;
  90. });
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return *it;
  93. #else
  94. if (it != items.end()) { return *it; }
  95. throw std::runtime_error("invalid multipart form data name error");
  96. #endif
  97. }
  98. static void read_file(const std::string &path, std::string &out) {
  99. std::ifstream fs(path, std::ios_base::binary);
  100. if (!fs) {
  101. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  102. return;
  103. #else
  104. throw std::runtime_error("File not found: " + path);
  105. #endif
  106. }
  107. fs.seekg(0, std::ios_base::end);
  108. auto size = fs.tellg();
  109. fs.seekg(0);
  110. out.resize(static_cast<size_t>(size));
  111. fs.read(&out[0], static_cast<std::streamsize>(size));
  112. }
  113. class UnixSocketTest : public ::testing::Test {
  114. protected:
  115. void TearDown() override { std::remove(pathname_.c_str()); }
  116. void client_GET(const std::string &addr) {
  117. httplib::Client cli{addr};
  118. cli.set_address_family(AF_UNIX);
  119. ASSERT_TRUE(cli.is_valid());
  120. const auto &result = cli.Get(pattern_);
  121. ASSERT_TRUE(result) << "error: " << result.error();
  122. const auto &resp = result.value();
  123. EXPECT_EQ(resp.status, StatusCode::OK_200);
  124. EXPECT_EQ(resp.body, content_);
  125. }
  126. static std::string make_sock_path() {
  127. const char *shard = getenv("GTEST_SHARD_INDEX");
  128. return shard ? std::string("./httplib-server-") + shard + ".sock"
  129. : "./httplib-server.sock";
  130. }
  131. const std::string pathname_{make_sock_path()};
  132. const std::string pattern_{"/hi"};
  133. const std::string content_{"Hello World!"};
  134. };
  135. TEST_F(UnixSocketTest, pathname) {
  136. httplib::Server svr;
  137. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  138. res.set_content(content_, "text/plain");
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. }
  152. #if defined(__linux__) || \
  153. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  154. TEST_F(UnixSocketTest, PeerPid) {
  155. httplib::Server svr;
  156. std::string remote_port_val;
  157. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. remote_port_val = std::to_string(req.remote_port);
  160. });
  161. std::thread t{[&] {
  162. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  163. }};
  164. auto se = detail::scope_exit([&] {
  165. svr.stop();
  166. t.join();
  167. ASSERT_FALSE(svr.is_running());
  168. });
  169. svr.wait_until_ready();
  170. ASSERT_TRUE(svr.is_running());
  171. client_GET(pathname_);
  172. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  173. }
  174. #endif
  175. #ifdef __linux__
  176. TEST_F(UnixSocketTest, abstract) {
  177. constexpr char svr_path[]{"\x00httplib-server.sock"};
  178. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  179. httplib::Server svr;
  180. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  181. res.set_content(content_, "text/plain");
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(abstract_addr);
  194. }
  195. #endif
  196. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  197. httplib::Server svr;
  198. std::string received_host_header;
  199. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  200. // Capture the Host header sent by the client
  201. auto host_iter = req.headers.find("Host");
  202. if (host_iter != req.headers.end()) {
  203. received_host_header = host_iter->second;
  204. }
  205. res.set_content(content_, "text/plain");
  206. });
  207. std::thread t{[&] {
  208. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  209. }};
  210. auto se = detail::scope_exit([&] {
  211. svr.stop();
  212. t.join();
  213. ASSERT_FALSE(svr.is_running());
  214. });
  215. svr.wait_until_ready();
  216. ASSERT_TRUE(svr.is_running());
  217. // Test that Host header is automatically set to "localhost" for Unix socket
  218. // connections
  219. httplib::Client cli{pathname_};
  220. cli.set_address_family(AF_UNIX);
  221. ASSERT_TRUE(cli.is_valid());
  222. const auto &result = cli.Get(pattern_);
  223. ASSERT_TRUE(result) << "error: " << result.error();
  224. const auto &resp = result.value();
  225. EXPECT_EQ(resp.status, StatusCode::OK_200);
  226. EXPECT_EQ(resp.body, content_);
  227. // Verify that Host header was automatically set to "localhost"
  228. EXPECT_EQ(received_host_header, "localhost");
  229. }
  230. #ifndef _WIN32
  231. TEST(SocketStream, wait_writable_UNIX) {
  232. int fds[2];
  233. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  234. const auto asSocketStream = [&](socket_t fd,
  235. std::function<bool(Stream &)> func) {
  236. return detail::process_client_socket(
  237. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  238. };
  239. asSocketStream(fds[0], [&](Stream &s0) {
  240. EXPECT_EQ(s0.socket(), fds[0]);
  241. EXPECT_TRUE(s0.wait_writable());
  242. EXPECT_TRUE(s0.is_peer_alive());
  243. EXPECT_EQ(0, close(fds[1]));
  244. EXPECT_FALSE(s0.is_peer_alive());
  245. return true;
  246. });
  247. EXPECT_EQ(0, close(fds[0]));
  248. }
  249. TEST(SocketStream, wait_writable_INET) {
  250. sockaddr_in addr;
  251. memset(&addr, 0, sizeof(addr));
  252. addr.sin_family = AF_INET;
  253. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  254. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  255. int disconnected_svr_sock = -1;
  256. std::thread svr{[&] {
  257. const int s = socket(AF_INET, SOCK_STREAM, 0);
  258. ASSERT_LE(0, s);
  259. // PORT + 1 is shared with the SSL redirect tests and with
  260. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  261. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  262. // because that happens on a worker thread the ASSERT does not stop the
  263. // test: it runs on and fails at the disconnected_svr_sock check instead.
  264. default_socket_options(s);
  265. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  266. ASSERT_EQ(0, listen(s, 1));
  267. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  268. ASSERT_EQ(0, close(s));
  269. }};
  270. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  271. std::thread cli{[&] {
  272. const int s = socket(AF_INET, SOCK_STREAM, 0);
  273. ASSERT_LE(0, s);
  274. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  275. ASSERT_EQ(0, close(s));
  276. }};
  277. cli.join();
  278. svr.join();
  279. ASSERT_NE(disconnected_svr_sock, -1);
  280. const auto asSocketStream = [&](socket_t fd,
  281. std::function<bool(Stream &)> func) {
  282. return detail::process_client_socket(
  283. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  284. };
  285. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  286. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  287. // wait_writable() returns true because select_write() only checks if the
  288. // send buffer has space. Peer disconnection is detected later by send().
  289. EXPECT_TRUE(ss.wait_writable());
  290. return true;
  291. });
  292. ASSERT_EQ(0, close(disconnected_svr_sock));
  293. }
  294. #endif // #ifndef _WIN32
  295. TEST(SetSocketOptTest, TcpNoDelay) {
  296. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  297. ASSERT_NE(sock, INVALID_SOCKET);
  298. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  299. int val = 0;
  300. socklen_t len = sizeof(val);
  301. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  302. reinterpret_cast<char *>(&val), &len));
  303. EXPECT_NE(val, 0);
  304. detail::close_socket(sock);
  305. }
  306. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  307. // accept() reports failures through WSAGetLastError() on Windows and through
  308. // errno everywhere else. Asking the wrong one is what made the accept loop
  309. // treat every recoverable failure as fatal on Windows.
  310. struct Classification {
  311. bool resource;
  312. bool transient;
  313. };
  314. auto classify = [](int err) {
  315. #ifdef _WIN32
  316. WSASetLastError(err);
  317. #else
  318. errno = err;
  319. #endif
  320. // Read both before asserting: an assertion may clobber the error slot.
  321. Classification c;
  322. c.resource = detail::is_accept_resource_error();
  323. c.transient = detail::is_accept_transient_error();
  324. return c;
  325. };
  326. #ifdef _WIN32
  327. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  328. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  329. WSAECONNRESET, WSAECONNABORTED};
  330. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  331. #else
  332. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  333. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  334. ECONNABORTED};
  335. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  336. #endif
  337. for (auto err : resource_errors) {
  338. const auto c = classify(err);
  339. EXPECT_TRUE(c.resource) << "error " << err;
  340. EXPECT_FALSE(c.transient) << "error " << err;
  341. }
  342. for (auto err : transient_errors) {
  343. const auto c = classify(err);
  344. EXPECT_TRUE(c.transient) << "error " << err;
  345. EXPECT_FALSE(c.resource) << "error " << err;
  346. }
  347. for (auto err : fatal_errors) {
  348. const auto c = classify(err);
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. EXPECT_FALSE(c.transient) << "error " << err;
  351. }
  352. #ifdef _WIN32
  353. WSASetLastError(0);
  354. #else
  355. errno = 0;
  356. #endif
  357. }
  358. TEST(ClientTest, MoveConstructible) {
  359. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  360. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  361. }
  362. TEST(ClientTest, MoveAssignable) {
  363. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  365. }
  366. #ifdef _WIN32
  367. TEST(StartupTest, WSAStartup) {
  368. WSADATA wsaData;
  369. int ret = WSAStartup(0x0002, &wsaData);
  370. ASSERT_EQ(0, ret);
  371. }
  372. #endif
  373. TEST(DecodePathTest, PercentCharacter) {
  374. EXPECT_EQ(
  375. decode_path_component(
  376. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  377. U8("descrip=Gastos áéíóúñÑ 6"));
  378. }
  379. TEST(DecodePathTest, PercentCharacterNUL) {
  380. string expected;
  381. expected.push_back('x');
  382. expected.push_back('\0');
  383. expected.push_back('x');
  384. EXPECT_EQ(decode_path_component("x%00x"), expected);
  385. }
  386. TEST(DecodePathTest, UnicodeEncoding) {
  387. // %u0041 = 'A' (1-byte UTF-8)
  388. EXPECT_EQ("A", decode_path_component("%u0041"));
  389. // %u00E9 = 'é' (2-byte UTF-8)
  390. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  391. // %u3042 = 'あ' (3-byte UTF-8)
  392. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  393. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  394. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  395. // %uD800 = surrogate (invalid, silently dropped)
  396. EXPECT_EQ("", decode_path_component("%uD800"));
  397. }
  398. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  399. // A sign or whitespace inside the two-character escape window must not be
  400. // accepted as a valid percent-encoding; the sequence is passed through
  401. // literally, matching decode_uri_component / decode_path_component.
  402. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  403. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  404. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  405. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  406. // Well-formed escapes still decode.
  407. EXPECT_EQ("-", decode_query_component("%2D", false));
  408. EXPECT_EQ("A", decode_query_component("%41", false));
  409. }
  410. TEST(SanitizeFilenameTest, VariousPatterns) {
  411. // Path traversal
  412. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  413. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  414. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  415. // Normal and edge cases
  416. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  417. EXPECT_EQ("filename.txt",
  418. httplib::sanitize_filename("/path/to/filename.txt"));
  419. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  420. EXPECT_EQ("", httplib::sanitize_filename(".."));
  421. EXPECT_EQ("", httplib::sanitize_filename(""));
  422. // Null bytes stripped
  423. EXPECT_EQ("safe.txt",
  424. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  425. // Whitespace-only rejected
  426. EXPECT_EQ("", httplib::sanitize_filename(" "));
  427. }
  428. // Forward declaration (see the base64_encode note below): split builds move the
  429. // definition into httplib.cc, so re-declaring it here lets the test link.
  430. namespace httplib {
  431. namespace detail {
  432. bool is_chunked_transfer_encoding(const Headers &headers);
  433. } // namespace detail
  434. } // namespace httplib
  435. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  436. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  437. auto make = [](std::initializer_list<const char *> lines) {
  438. Headers h;
  439. for (auto te : lines) {
  440. if (te) { h.emplace("Transfer-Encoding", te); }
  441. }
  442. return h;
  443. };
  444. // Sole coding, matched case-insensitively.
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  446. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  448. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  452. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  457. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  458. // were received, into one list. Headers preserves that order, so the answer
  459. // is decided by the last coding of the last line and the order the lines
  460. // arrived in is significant.
  461. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  463. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  464. // The split can fall anywhere in the list.
  465. EXPECT_TRUE(
  466. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  467. EXPECT_FALSE(
  468. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  469. // A trailing line naming no coding leaves the list ending in nothing, so it
  470. // must not inherit the chunked from the line before it.
  471. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  472. }
  473. // Forward declarations (see the base64_encode note below).
  474. namespace httplib {
  475. namespace detail {
  476. bool parse_status_line(const char *line, std::string &version, int &status,
  477. std::string &reason);
  478. std::string file_extension(const std::string &path);
  479. std::string
  480. find_content_type(const std::string &path,
  481. const std::map<std::string, std::string> &user_data,
  482. const std::string &default_content_type);
  483. bool can_compress_content_type(const std::string &content_type);
  484. bool is_prohibited_header_name(const std::string &name);
  485. } // namespace detail
  486. } // namespace httplib
  487. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  488. struct {
  489. const char *line;
  490. const char *version;
  491. int status;
  492. const char *reason;
  493. } cases[] = {
  494. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  495. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  496. // The reason phrase may be empty, or left out along with its space.
  497. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  498. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  499. };
  500. for (const auto &c : cases) {
  501. std::string version;
  502. int status = 0;
  503. std::string reason = "unset";
  504. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  505. << c.line;
  506. EXPECT_EQ(c.version, version);
  507. EXPECT_EQ(c.status, status);
  508. EXPECT_EQ(c.reason, reason);
  509. }
  510. }
  511. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  512. const char *lines[] = {
  513. "HTTP/2 200 OK\r\n",
  514. "HTTP/1.2 200 OK\r\n",
  515. "HTTP/1.1 20 OK\r\n",
  516. "HTTP/1.1 2000 OK\r\n",
  517. "HTTP/1.1 2x0 OK\r\n",
  518. "HTTP/1.1 200 OK\r\n",
  519. "HTTP/1.1 200OK\r\n",
  520. "HTTP/1.1 200 O\rK\r\n",
  521. "HTTP/1.1 200 OK",
  522. "HTTP/1.1 200 OK\r\nX",
  523. "",
  524. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  525. "HTTP/1.1 200 OK\n",
  526. #endif
  527. };
  528. for (auto line : lines) {
  529. std::string version;
  530. int status = 0;
  531. std::string reason;
  532. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  533. << line;
  534. }
  535. }
  536. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  537. // Long enough to overflow the stack when matched with std::regex.
  538. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  539. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  540. std::string version;
  541. int status = 0;
  542. std::string reason;
  543. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  544. EXPECT_EQ(200, status);
  545. EXPECT_EQ(long_reason, reason);
  546. }
  547. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  548. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  549. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  550. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  551. EXPECT_EQ("", detail::file_extension("noext"));
  552. EXPECT_EQ("", detail::file_extension("a."));
  553. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  554. EXPECT_EQ("", detail::file_extension("a.b-c"));
  555. // Long enough to overflow the stack when matched with std::regex.
  556. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  557. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  558. }
  559. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  560. detail::case_ignore::hash hash;
  561. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  562. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  563. // Long enough to overflow the stack if hashed one call per character.
  564. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  565. }
  566. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  567. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  568. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  569. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  570. // Same 26-bit hash as html, svg and js.
  571. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  572. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  573. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  574. }
  575. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  576. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  577. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  578. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  579. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  580. // Same 26-bit hash as application/json.
  581. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  582. }
  583. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  584. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  585. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  586. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  587. // Same 26-bit hash as REMOTE_ADDR.
  588. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  589. }
  590. // Forward declaration: in split builds split.py strips `inline` and moves the
  591. // definition into httplib.cc, so detail::base64_encode is not visible from the
  592. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  593. // in both header-only and split builds.
  594. namespace httplib {
  595. namespace detail {
  596. std::string base64_encode(const std::string &in);
  597. } // namespace detail
  598. } // namespace httplib
  599. TEST(Base64EncodeTest, KnownAnswers) {
  600. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  601. // where the accumulator's top bit is already set before the next shift.
  602. EXPECT_EQ("", detail::base64_encode(""));
  603. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  604. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  605. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  606. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  607. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  608. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  609. // High bytes keep the top bit set across several rounds.
  610. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  611. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  612. }
  613. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  614. string unescapedCharacters = "-_.!~*'()";
  615. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  616. }
  617. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  618. string reservedCharacters = ";,/?:@&=+$";
  619. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  620. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  621. }
  622. TEST(ClientQueryOrder, PreserveOrder) {
  623. // This test reproduces Issue #2259: client may reorder query parameters
  624. // when sending a GET request. The expected behavior is that the client
  625. // preserves the original query string order when the caller supplied it
  626. // as part of the path.
  627. Server svr;
  628. svr.Get("/", [&](const Request &req, Response &res) {
  629. // Echo back the raw target so the test can assert ordering
  630. res.set_content(req.target, "text/plain");
  631. });
  632. std::thread t{[&] { svr.listen(HOST, PORT); }};
  633. auto se = detail::scope_exit([&] {
  634. svr.stop();
  635. t.join();
  636. ASSERT_FALSE(svr.is_running());
  637. });
  638. svr.wait_until_ready();
  639. Client cli(HOST, PORT);
  640. ASSERT_TRUE(cli.is_valid());
  641. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  642. auto res = cli.Get(original);
  643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  644. // Expect the echoed target to exactly match the original path (order
  645. // preserved)
  646. EXPECT_EQ(res->body, original);
  647. }
  648. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  649. string chineseCharacters = U8("中国語");
  650. string russianCharacters = U8("дом");
  651. string brazilianCharacters = U8("óculos");
  652. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  653. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  654. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  655. "%D0%B4%D0%BE%D0%BC");
  656. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  657. }
  658. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  659. string unescapedCharacters = "-_.!~*'()";
  660. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  661. }
  662. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  663. string reservedCharacters = ";,/?:@&=+$";
  664. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  665. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  666. }
  667. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  668. string chineseCharacters = U8("中国語");
  669. string russianCharacters = U8("дом");
  670. string brazilianCharacters = U8("óculos");
  671. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  672. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  673. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  674. "%D0%B4%D0%BE%D0%BC");
  675. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  676. }
  677. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  678. // Issue #2082 use case: encoding path component with ampersand
  679. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  680. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  681. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  682. }
  683. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  684. string unescapedCharacters = "-_.!~*'()";
  685. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  686. }
  687. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  688. string reservedCharacters = ";,/?:@&=+$#";
  689. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  690. }
  691. TEST(EncodeUriTest, TestUTF8Characters) {
  692. string chineseCharacters = U8("中国語");
  693. string russianCharacters = U8("дом");
  694. string brazilianCharacters = U8("óculos");
  695. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  696. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  697. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  698. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  699. }
  700. TEST(EncodeUriTest, TestCompleteUri) {
  701. string uri =
  702. "https://example.com/path/to/resource?query=value&param=test#fragment";
  703. EXPECT_EQ(
  704. httplib::encode_uri(uri),
  705. "https://example.com/path/to/resource?query=value&param=test#fragment");
  706. }
  707. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  708. string uri =
  709. "https://example.com/path with spaces/file name.html?q=hello world";
  710. EXPECT_EQ(httplib::encode_uri(uri),
  711. "https://example.com/path%20with%20spaces/"
  712. "file%20name.html?q=hello%20world");
  713. }
  714. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  715. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  716. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  717. }
  718. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  719. string unescapedCharacters = "-_.!~*'()";
  720. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  721. }
  722. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  723. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  724. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  725. string encodedBrazilian = "%C3%B3culos";
  726. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  727. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  728. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  729. }
  730. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  731. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  732. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  733. "Piri Tommy Villiers - on & on");
  734. }
  735. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  736. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  737. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  738. }
  739. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  740. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  741. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  742. }
  743. TEST(DecodeUriTest, TestUTF8Characters) {
  744. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  745. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  746. string encodedBrazilian = "%C3%B3culos";
  747. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  748. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  749. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  750. }
  751. TEST(DecodeUriTest, TestCompleteUri) {
  752. string encodedUri = "https://example.com/path%20with%20spaces/"
  753. "file%20name.html?q=hello%20world";
  754. EXPECT_EQ(
  755. httplib::decode_uri(encodedUri),
  756. "https://example.com/path with spaces/file name.html?q=hello world");
  757. }
  758. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  759. string original =
  760. "https://example.com/path with spaces/file name.html?q=hello world";
  761. string encoded = httplib::encode_uri(original);
  762. string decoded = httplib::decode_uri(encoded);
  763. EXPECT_EQ(decoded, original);
  764. }
  765. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  766. // decode_uri is the inverse of encode_uri: an escaped reserved character
  767. // stays encoded so it is not promoted into a real delimiter, while
  768. // non-reserved escapes still decode (like JS decodeURI).
  769. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  770. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  771. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  772. "%3F%3A%40%26%3D%2B%24%2C%3B");
  773. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  774. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  775. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  776. "http://example.com/a%2Fb");
  777. // decode_uri_component still decodes the reserved character.
  778. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  779. }
  780. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  781. string original = "Piri Tommy Villiers - on & on";
  782. string encoded = httplib::encode_uri_component(original);
  783. string decoded = httplib::decode_uri_component(encoded);
  784. EXPECT_EQ(decoded, original);
  785. }
  786. TEST(TrimTests, TrimStringTests) {
  787. EXPECT_EQ("abc", detail::trim_copy("abc"));
  788. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  789. EXPECT_TRUE(detail::trim_copy("").empty());
  790. }
  791. TEST(AsciiTest, LocaleIndependentClassification) {
  792. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  793. // which consult the global C locale: std::isalnum(0xC5) can return true
  794. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  795. // helpers must classify every byte by the ASCII grammar alone.
  796. for (int i = 0; i < 256; i++) {
  797. auto c = static_cast<char>(i);
  798. auto is_digit = i >= '0' && i <= '9';
  799. auto is_upper = i >= 'A' && i <= 'Z';
  800. auto is_lower = i >= 'a' && i <= 'z';
  801. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  802. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  803. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  804. << "byte " << i;
  805. }
  806. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  807. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  808. // Non-ASCII bytes must be percent-encoded, never passed through as
  809. // alphanumeric.
  810. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  811. }
  812. TEST(FromCharsTest, Double) {
  813. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  814. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  815. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  816. auto parse = [](const std::string &s, double &v) {
  817. return detail::from_chars(s.data(), s.data() + s.size(), v);
  818. };
  819. double v = -1.0;
  820. // Representative quality values.
  821. EXPECT_EQ(parse("0", v).ec, std::errc{});
  822. EXPECT_DOUBLE_EQ(v, 0.0);
  823. EXPECT_EQ(parse("1", v).ec, std::errc{});
  824. EXPECT_DOUBLE_EQ(v, 1.0);
  825. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  826. EXPECT_DOUBLE_EQ(v, 0.8);
  827. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  828. EXPECT_DOUBLE_EQ(v, 0.001);
  829. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  830. EXPECT_DOUBLE_EQ(v, 1.0);
  831. // A missing integer or fractional part is tolerated.
  832. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  833. EXPECT_DOUBLE_EQ(v, 0.5);
  834. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  835. EXPECT_DOUBLE_EQ(v, 5.0);
  836. // Values outside [0, 1] still parse; the caller range-checks them.
  837. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  838. EXPECT_DOUBLE_EQ(v, 123.456);
  839. // Stops at the first byte that is not part of the number and reports where.
  840. std::string trailing = "0.9, text/html";
  841. auto r = parse(trailing, v);
  842. EXPECT_EQ(r.ec, std::errc{});
  843. EXPECT_DOUBLE_EQ(v, 0.9);
  844. EXPECT_EQ(*r.ptr, ',');
  845. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  846. // outright, and an 'e'/'E' simply ends the number.
  847. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  848. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  849. std::string exp_input = "1.5e3";
  850. r = parse(exp_input, v);
  851. EXPECT_EQ(r.ec, std::errc{});
  852. EXPECT_DOUBLE_EQ(v, 1.5);
  853. EXPECT_EQ(*r.ptr, 'e');
  854. // Invalid inputs.
  855. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  856. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  857. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  858. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  859. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  860. // Pathological but well-formed inputs must stay bounded (no overflow, no
  861. // out-of-bounds table access) and stay within [0, 1] for the caller.
  862. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  863. std::errc{});
  864. EXPECT_DOUBLE_EQ(v, 0.0);
  865. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  866. std::errc{});
  867. EXPECT_GE(v, 0.0);
  868. EXPECT_LE(v, 1.0);
  869. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  870. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  871. }
  872. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  873. // Simple case without quality values
  874. std::vector<std::string> result1;
  875. EXPECT_TRUE(detail::parse_accept_header(
  876. "text/html,application/json,text/plain", result1));
  877. EXPECT_EQ(result1.size(), 3U);
  878. EXPECT_EQ(result1[0], "text/html");
  879. EXPECT_EQ(result1[1], "application/json");
  880. EXPECT_EQ(result1[2], "text/plain");
  881. // With quality values
  882. std::vector<std::string> result2;
  883. EXPECT_TRUE(detail::parse_accept_header(
  884. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  885. EXPECT_EQ(result2.size(), 3U);
  886. EXPECT_EQ(result2[0], "application/json"); // highest q value
  887. EXPECT_EQ(result2[1], "text/html");
  888. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  889. }
  890. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  891. // Mixed with and without quality values
  892. std::vector<std::string> result;
  893. EXPECT_TRUE(detail::parse_accept_header(
  894. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  895. EXPECT_EQ(result.size(), 3U);
  896. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  897. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  898. EXPECT_EQ(result[2], "application/json"); // q=0.5
  899. }
  900. TEST(ParseAcceptHeaderTest, EdgeCases) {
  901. // Empty header
  902. std::vector<std::string> empty_result;
  903. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  904. EXPECT_TRUE(empty_result.empty());
  905. // Single type
  906. std::vector<std::string> single_result;
  907. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  908. EXPECT_EQ(single_result.size(), 1U);
  909. EXPECT_EQ(single_result[0], "application/json");
  910. // Wildcard types
  911. std::vector<std::string> wildcard_result;
  912. EXPECT_TRUE(detail::parse_accept_header(
  913. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  914. EXPECT_EQ(wildcard_result.size(), 3U);
  915. EXPECT_EQ(wildcard_result[0], "application/json");
  916. EXPECT_EQ(wildcard_result[1], "text/*");
  917. EXPECT_EQ(wildcard_result[2], "*/*");
  918. }
  919. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  920. // Common browser Accept header
  921. std::vector<std::string> browser_result;
  922. EXPECT_TRUE(
  923. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  924. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  925. browser_result));
  926. EXPECT_EQ(browser_result.size(), 6U);
  927. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  928. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  929. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  930. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  931. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  932. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  933. // API client header
  934. std::vector<std::string> api_result;
  935. EXPECT_TRUE(detail::parse_accept_header(
  936. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  937. api_result));
  938. EXPECT_EQ(api_result.size(), 3U);
  939. EXPECT_EQ(api_result[0], "application/json");
  940. EXPECT_EQ(api_result[1], "application/xml");
  941. EXPECT_EQ(api_result[2], "text/plain");
  942. }
  943. TEST(ParseAcceptHeaderTest, SpecialCases) {
  944. // Quality value with 3 decimal places
  945. std::vector<std::string> decimal_result;
  946. EXPECT_TRUE(detail::parse_accept_header(
  947. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  948. EXPECT_EQ(decimal_result.size(), 2U);
  949. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  950. EXPECT_EQ(decimal_result[1], "text/html");
  951. // Zero quality (should still be included but with lowest priority)
  952. std::vector<std::string> zero_q_result;
  953. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  954. zero_q_result));
  955. EXPECT_EQ(zero_q_result.size(), 2U);
  956. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  957. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  958. // No spaces around commas
  959. std::vector<std::string> no_space_result;
  960. EXPECT_TRUE(detail::parse_accept_header(
  961. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  962. no_space_result));
  963. EXPECT_EQ(no_space_result.size(), 3U);
  964. EXPECT_EQ(no_space_result[0], "text/html");
  965. EXPECT_EQ(no_space_result[1], "application/json");
  966. EXPECT_EQ(no_space_result[2], "text/plain");
  967. }
  968. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  969. // Quality values always use '.' as the decimal separator, so parsing must
  970. // not depend on the process locale. An embedding application may have
  971. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  972. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  973. std::string saved = cur ? cur : "C";
  974. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  975. "fr_FR.UTF-8"};
  976. bool switched = false;
  977. for (const auto loc : comma_locales) {
  978. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  979. std::localeconv()->decimal_point[0] == ',') {
  980. switched = true;
  981. break;
  982. }
  983. }
  984. if (!switched) {
  985. std::setlocale(LC_NUMERIC, saved.c_str());
  986. GTEST_SKIP() << "no comma-decimal locale available on this host";
  987. }
  988. // The higher-weighted type appears later in the list, so a correct parse
  989. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  990. // sensitive parse reads both weights as 0 and leaves the original order.
  991. std::vector<std::string> result;
  992. EXPECT_TRUE(detail::parse_accept_header(
  993. "application/json;q=0.1,text/html;q=0.9", result));
  994. ASSERT_EQ(result.size(), 2U);
  995. EXPECT_EQ(result[0], "text/html");
  996. EXPECT_EQ(result[1], "application/json");
  997. std::setlocale(LC_NUMERIC, saved.c_str());
  998. }
  999. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1000. std::vector<std::string> result;
  1001. // Invalid quality value (> 1.0)
  1002. EXPECT_FALSE(
  1003. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1004. // Invalid quality value (< 0.0)
  1005. EXPECT_FALSE(
  1006. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1007. // Invalid quality value (not a number)
  1008. EXPECT_FALSE(detail::parse_accept_header(
  1009. "text/html;q=invalid,application/json", result));
  1010. // A valid numeric prefix does not make the entire quality value valid.
  1011. EXPECT_FALSE(detail::parse_accept_header(
  1012. "text/html;q=0.5junk,application/json", result));
  1013. // Empty quality value
  1014. EXPECT_FALSE(
  1015. detail::parse_accept_header("text/html;q=,application/json", result));
  1016. // Invalid media type format (no slash and not wildcard)
  1017. EXPECT_FALSE(
  1018. detail::parse_accept_header("invalidtype,application/json", result));
  1019. // Valid cases should still work
  1020. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1021. EXPECT_EQ(result.size(), 1U);
  1022. EXPECT_EQ(result[0], "*/*");
  1023. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1024. EXPECT_EQ(result.size(), 1U);
  1025. EXPECT_EQ(result[0], "*");
  1026. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1027. EXPECT_EQ(result.size(), 1U);
  1028. EXPECT_EQ(result[0], "text/*");
  1029. }
  1030. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1031. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1032. // and must not be answered with 400 Bad Request.
  1033. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1034. struct {
  1035. const char *value;
  1036. std::vector<std::string> expected;
  1037. } cases[] = {
  1038. {",application/json", {"application/json"}},
  1039. {"text/html,", {"text/html"}},
  1040. {"text/html,,*/*", {"text/html", "*/*"}},
  1041. // An empty element may be spelled with whitespace in it
  1042. {"text/html, , application/json", {"text/html", "application/json"}},
  1043. // Nothing but empty elements is an empty list, which means the same
  1044. // thing as no Accept header at all
  1045. {",,,", {}},
  1046. // Quality values still apply across ignored empty elements
  1047. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1048. };
  1049. for (const auto &c : cases) {
  1050. std::vector<std::string> result;
  1051. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1052. << "value: " << c.value;
  1053. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1054. }
  1055. // An invalid entry is still rejected when empty elements surround it
  1056. std::vector<std::string> result;
  1057. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1058. }
  1059. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1060. // or ';' inside one does not end the list element or the parameter. Section
  1061. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1062. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1063. struct {
  1064. const char *value;
  1065. std::vector<std::string> expected;
  1066. } cases[] = {
  1067. {"text/html;profile=\"a,b\",application/json",
  1068. {"text/html", "application/json"}},
  1069. // A "q=" inside a quoted value is not the weight
  1070. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1071. {"text/html", "application/json"}},
  1072. // The weight after a quoted value still applies
  1073. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1074. {"application/json", "text/html"}},
  1075. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1076. {"application/json", "text/html"}},
  1077. {"text/html;profile=\"a\\\"b\",application/json",
  1078. {"text/html", "application/json"}},
  1079. // An escaped backslash does not escape the '"' after it
  1080. {"text/html;profile=\"a\\\\\",application/json",
  1081. {"text/html", "application/json"}},
  1082. };
  1083. for (const auto &c : cases) {
  1084. std::vector<std::string> result;
  1085. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1086. << "value: " << c.value;
  1087. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1088. }
  1089. }
  1090. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1091. Server svr;
  1092. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1093. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1094. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1095. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1096. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1097. res.set_content("ok", "text/plain");
  1098. });
  1099. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1100. EXPECT_TRUE(false);
  1101. res.set_content("bad request", "text/plain");
  1102. });
  1103. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1104. auto se = detail::scope_exit([&] {
  1105. svr.stop();
  1106. listen_thread.join();
  1107. ASSERT_FALSE(svr.is_running());
  1108. });
  1109. svr.wait_until_ready();
  1110. Client cli("localhost", PORT);
  1111. {
  1112. auto res = cli.Get(
  1113. "/accept_ok",
  1114. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1116. EXPECT_EQ(StatusCode::OK_200, res->status);
  1117. }
  1118. {
  1119. auto res = cli.Get("/accept_bad_request",
  1120. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1122. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1123. }
  1124. }
  1125. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1126. Server svr;
  1127. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1128. res.set_content("ok", "text/plain");
  1129. });
  1130. std::atomic<int> start_count{0};
  1131. std::atomic<bool> running_when_called{false};
  1132. svr.set_start_handler([&]() {
  1133. running_when_called = svr.is_running();
  1134. start_count++;
  1135. });
  1136. auto port = svr.bind_to_any_port(HOST);
  1137. std::thread t([&]() { svr.listen_after_bind(); });
  1138. auto se = detail::scope_exit([&] {
  1139. svr.stop();
  1140. t.join();
  1141. ASSERT_FALSE(svr.is_running());
  1142. });
  1143. svr.wait_until_ready();
  1144. // A successful request proves the accept loop is running, which the start
  1145. // handler precedes; so by now the handler must have run exactly once.
  1146. Client cli(HOST, port);
  1147. cli.set_connection_timeout(std::chrono::seconds(5));
  1148. auto res = cli.Get("/");
  1149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1150. EXPECT_EQ(StatusCode::OK_200, res->status);
  1151. EXPECT_EQ(1, start_count.load());
  1152. EXPECT_TRUE(running_when_called.load());
  1153. }
  1154. TEST(DivideTest, DivideStringTests) {
  1155. auto divide = [](const std::string &str, char d) {
  1156. std::string lhs;
  1157. std::string rhs;
  1158. detail::divide(str, d,
  1159. [&](const char *lhs_data, std::size_t lhs_size,
  1160. const char *rhs_data, std::size_t rhs_size) {
  1161. lhs.assign(lhs_data, lhs_size);
  1162. rhs.assign(rhs_data, rhs_size);
  1163. });
  1164. return std::make_pair(std::move(lhs), std::move(rhs));
  1165. };
  1166. {
  1167. const auto res = divide("", '=');
  1168. EXPECT_EQ(res.first, "");
  1169. EXPECT_EQ(res.second, "");
  1170. }
  1171. {
  1172. const auto res = divide("=", '=');
  1173. EXPECT_EQ(res.first, "");
  1174. EXPECT_EQ(res.second, "");
  1175. }
  1176. {
  1177. const auto res = divide(" ", '=');
  1178. EXPECT_EQ(res.first, " ");
  1179. EXPECT_EQ(res.second, "");
  1180. }
  1181. {
  1182. const auto res = divide("a", '=');
  1183. EXPECT_EQ(res.first, "a");
  1184. EXPECT_EQ(res.second, "");
  1185. }
  1186. {
  1187. const auto res = divide("a=", '=');
  1188. EXPECT_EQ(res.first, "a");
  1189. EXPECT_EQ(res.second, "");
  1190. }
  1191. {
  1192. const auto res = divide("=b", '=');
  1193. EXPECT_EQ(res.first, "");
  1194. EXPECT_EQ(res.second, "b");
  1195. }
  1196. {
  1197. const auto res = divide("a=b", '=');
  1198. EXPECT_EQ(res.first, "a");
  1199. EXPECT_EQ(res.second, "b");
  1200. }
  1201. {
  1202. const auto res = divide("a=b=", '=');
  1203. EXPECT_EQ(res.first, "a");
  1204. EXPECT_EQ(res.second, "b=");
  1205. }
  1206. {
  1207. const auto res = divide("a=b=c", '=');
  1208. EXPECT_EQ(res.first, "a");
  1209. EXPECT_EQ(res.second, "b=c");
  1210. }
  1211. }
  1212. TEST(SplitTest, ParseQueryString) {
  1213. string s = "key1=val1&key2=val2&key3=val3";
  1214. Params dic;
  1215. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1216. [&](const char *b, const char *e) {
  1217. string key, val;
  1218. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1219. if (key.empty()) {
  1220. key.assign(b2, e2);
  1221. } else {
  1222. val.assign(b2, e2);
  1223. }
  1224. });
  1225. dic.emplace(key, val);
  1226. });
  1227. EXPECT_EQ("val1", dic.find("key1")->second);
  1228. EXPECT_EQ("val2", dic.find("key2")->second);
  1229. EXPECT_EQ("val3", dic.find("key3")->second);
  1230. }
  1231. TEST(SplitTest, ParseInvalidQueryTests) {
  1232. {
  1233. string s = " ";
  1234. Params dict;
  1235. detail::parse_query_text(s, dict);
  1236. EXPECT_TRUE(dict.empty());
  1237. }
  1238. {
  1239. string s = " = =";
  1240. Params dict;
  1241. detail::parse_query_text(s, dict);
  1242. EXPECT_TRUE(dict.empty());
  1243. }
  1244. }
  1245. TEST(ParseQueryTest, ParseQueryString) {
  1246. {
  1247. std::string s = "key1=val1&key2=val2&key3=val3";
  1248. Params dic;
  1249. detail::parse_query_text(s, dic);
  1250. EXPECT_EQ("val1", dic.find("key1")->second);
  1251. EXPECT_EQ("val2", dic.find("key2")->second);
  1252. EXPECT_EQ("val3", dic.find("key3")->second);
  1253. }
  1254. {
  1255. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1256. Params dic;
  1257. detail::parse_query_text(s, dic);
  1258. EXPECT_EQ("", dic.find("key1")->second);
  1259. EXPECT_EQ("val1", dic.find("key2")->second);
  1260. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1261. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1262. }
  1263. }
  1264. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1265. Params dic;
  1266. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1267. dic.emplace("key1", "val1");
  1268. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1269. dic.emplace("key2", "val2");
  1270. dic.emplace("key3", "val3");
  1271. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1272. }
  1273. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1274. Params params;
  1275. params.emplace("a", "1");
  1276. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1277. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1278. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1279. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1280. // Long enough to overflow the stack when matched with std::regex.
  1281. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1282. EXPECT_EQ("/p?" + long_query + "&a=1",
  1283. append_query_params("/p?" + long_query, params));
  1284. }
  1285. // Joins every entry of a Headers or Params into "key=value " so a whole
  1286. // traversal can be compared in one assertion. Both are instantiations of the
  1287. // same insertion-ordered container, so one helper serves both.
  1288. template <typename Map> static std::string entries_to_string(const Map &m) {
  1289. std::string s;
  1290. for (const auto &entry : m) {
  1291. s += entry.first + "=" + entry.second + " ";
  1292. }
  1293. return s;
  1294. }
  1295. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1296. // Params used to be a std::multimap, which sorted by name and handed the
  1297. // caller's query back alphabetised. A client signing its query string could
  1298. // not reproduce the order it asked for.
  1299. Params dic;
  1300. dic.emplace("zulu", "1");
  1301. dic.emplace("alpha", "2");
  1302. dic.emplace("mike", "3");
  1303. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1304. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1305. }
  1306. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1307. Params dic;
  1308. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1309. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1310. }
  1311. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1312. Request req;
  1313. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1314. req.params);
  1315. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1316. EXPECT_EQ("first", req.get_param_value("tag"));
  1317. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1318. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1319. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1320. EXPECT_EQ("", req.get_param_value("tag", 3));
  1321. }
  1322. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1323. // Params shares its container with Headers, which matches field names
  1324. // case-insensitively. Parameter names must not pick that up.
  1325. Params dic;
  1326. dic.emplace("Key", "upper");
  1327. dic.emplace("key", "lower");
  1328. EXPECT_EQ(2U, dic.size());
  1329. EXPECT_EQ(1U, dic.count("Key"));
  1330. EXPECT_EQ(1U, dic.count("key"));
  1331. EXPECT_EQ("upper", dic.find("Key")->second);
  1332. EXPECT_EQ("lower", dic.find("key")->second);
  1333. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1334. }
  1335. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1336. Server svr;
  1337. std::string order;
  1338. svr.Get("/order", [&](const Request &req, Response &res) {
  1339. order = entries_to_string(req.params);
  1340. res.set_content("ok", "text/plain");
  1341. });
  1342. auto port = svr.bind_to_any_port(HOST);
  1343. thread t = thread([&] { svr.listen_after_bind(); });
  1344. auto se = detail::scope_exit([&] {
  1345. svr.stop();
  1346. t.join();
  1347. ASSERT_FALSE(svr.is_running());
  1348. });
  1349. svr.wait_until_ready();
  1350. Client cli(HOST, port);
  1351. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1352. ASSERT_TRUE(res);
  1353. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1354. }
  1355. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1356. Server svr;
  1357. std::string field_order, file_order;
  1358. svr.Post("/order", [&](const Request &req, Response &res) {
  1359. for (const auto &field : req.form.fields) {
  1360. field_order += field.first + "=" + field.second.content + " ";
  1361. }
  1362. for (const auto &file : req.form.files) {
  1363. file_order += file.first + "=" + file.second.filename + " ";
  1364. }
  1365. res.set_content("ok", "text/plain");
  1366. });
  1367. auto port = svr.bind_to_any_port(HOST);
  1368. thread t = thread([&] { svr.listen_after_bind(); });
  1369. auto se = detail::scope_exit([&] {
  1370. svr.stop();
  1371. t.join();
  1372. ASSERT_FALSE(svr.is_running());
  1373. });
  1374. svr.wait_until_ready();
  1375. UploadFormDataItems items = {
  1376. {"zulu", "1", "", ""},
  1377. {"alpha", "2", "", ""},
  1378. {"mike", "3", "", ""},
  1379. {"zebra", "z", "z.txt", "text/plain"},
  1380. {"apple", "a", "a.txt", "text/plain"},
  1381. };
  1382. Client cli(HOST, port);
  1383. auto res = cli.Post("/order", items);
  1384. ASSERT_TRUE(res);
  1385. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1386. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1387. }
  1388. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1389. Server svr;
  1390. std::vector<std::string> values;
  1391. std::string first, second, out_of_range, order;
  1392. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1393. values = req.form.get_fields("tag");
  1394. first = req.form.get_field("tag", 0);
  1395. second = req.form.get_field("tag", 1);
  1396. out_of_range = req.form.get_field("tag", 2);
  1397. for (const auto &field : req.form.fields) {
  1398. order += field.first + "=" + field.second.content + " ";
  1399. }
  1400. res.set_content("ok", "text/plain");
  1401. });
  1402. auto port = svr.bind_to_any_port(HOST);
  1403. thread t = thread([&] { svr.listen_after_bind(); });
  1404. auto se = detail::scope_exit([&] {
  1405. svr.stop();
  1406. t.join();
  1407. ASSERT_FALSE(svr.is_running());
  1408. });
  1409. svr.wait_until_ready();
  1410. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1411. // not adjacent in the container.
  1412. UploadFormDataItems items = {
  1413. {"tag", "first", "", ""},
  1414. {"other", "x", "", ""},
  1415. {"tag", "second", "", ""},
  1416. };
  1417. Client cli(HOST, port);
  1418. auto res = cli.Post("/repeated", items);
  1419. ASSERT_TRUE(res);
  1420. ASSERT_EQ(2U, values.size());
  1421. EXPECT_EQ("first", values[0]);
  1422. EXPECT_EQ("second", values[1]);
  1423. EXPECT_EQ("first", first);
  1424. EXPECT_EQ("second", second);
  1425. // std::multimap already kept entries sharing a name in insertion order, so
  1426. // everything above passes without this change too. The whole traversal is
  1427. // what tells the two apart: sorting by name would hoist "other" to the front
  1428. // and the two "tag" parts would end up adjacent.
  1429. EXPECT_EQ("tag=first other=x tag=second ", order);
  1430. // Advancing past the last entry of a name used to run off the container;
  1431. // the container's saturating increment makes it return the default instead.
  1432. EXPECT_EQ("", out_of_range);
  1433. }
  1434. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1435. // Server::read_content() keeps a FormFields::iterator alive across the
  1436. // content callbacks that fill the part it points at. The container is
  1437. // vector-backed, so a later emplace can reallocate and invalidate an older
  1438. // iterator; 64 parts grow the vector through seven reallocations, which
  1439. // checks that every part's content still lands in its own entry.
  1440. const size_t part_count = 64;
  1441. // One formula for both the parts sent and the values expected back, so the
  1442. // two cannot drift apart.
  1443. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1444. auto content_of = [](size_t i) {
  1445. return std::string(64, static_cast<char>('a' + (i % 26)));
  1446. };
  1447. Server svr;
  1448. std::vector<std::pair<std::string, std::string>> received;
  1449. svr.Post("/many", [&](const Request &req, Response &res) {
  1450. for (const auto &field : req.form.fields) {
  1451. received.emplace_back(field.first, field.second.content);
  1452. }
  1453. res.set_content("ok", "text/plain");
  1454. });
  1455. auto port = svr.bind_to_any_port(HOST);
  1456. thread t = thread([&] { svr.listen_after_bind(); });
  1457. auto se = detail::scope_exit([&] {
  1458. svr.stop();
  1459. t.join();
  1460. ASSERT_FALSE(svr.is_running());
  1461. });
  1462. svr.wait_until_ready();
  1463. UploadFormDataItems items;
  1464. for (size_t i = 0; i < part_count; i++) {
  1465. items.push_back({name_of(i), content_of(i), "", ""});
  1466. }
  1467. Client cli(HOST, port);
  1468. auto res = cli.Post("/many", items);
  1469. ASSERT_TRUE(res);
  1470. ASSERT_EQ(part_count, received.size());
  1471. for (size_t i = 0; i < part_count; i++) {
  1472. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1473. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1474. }
  1475. }
  1476. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1477. string content_type = "multipart/form-data; boundary=something";
  1478. string boundary;
  1479. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1480. EXPECT_TRUE(ret);
  1481. EXPECT_EQ(boundary, "something");
  1482. }
  1483. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1484. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1485. string boundary;
  1486. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1487. EXPECT_TRUE(ret);
  1488. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1489. }
  1490. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1491. string content_type =
  1492. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1493. string boundary;
  1494. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1495. EXPECT_TRUE(ret);
  1496. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1497. }
  1498. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1499. string content_type =
  1500. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1501. string boundary;
  1502. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1503. EXPECT_TRUE(ret);
  1504. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1505. }
  1506. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1507. const string boundary(70, 'a');
  1508. string content_type = "multipart/form-data; boundary=" + boundary;
  1509. string parsed;
  1510. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1511. EXPECT_TRUE(ret);
  1512. EXPECT_EQ(parsed, boundary);
  1513. }
  1514. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1515. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1516. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1517. string parsed;
  1518. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1519. EXPECT_FALSE(ret);
  1520. }
  1521. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1522. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1523. // is 72 characters on the wire and still valid.
  1524. const string boundary(70, 'a');
  1525. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1526. string parsed;
  1527. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1528. EXPECT_EQ(parsed, boundary);
  1529. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1530. parsed.clear();
  1531. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1532. }
  1533. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1534. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1535. // The parameter parser must not treat that '=' as the key/value separator.
  1536. string content_type =
  1537. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1538. "charset=UTF-8";
  1539. string parsed;
  1540. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1541. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1542. }
  1543. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1544. // A ';' inside the quoted-string is part of the value, not a parameter
  1545. // separator, so it must not truncate the boundary.
  1546. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1547. string parsed;
  1548. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1549. EXPECT_EQ(parsed, "a;b");
  1550. }
  1551. TEST(ParseDispositionParamsTest, QuotedValues) {
  1552. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1553. // ';' and '=' are ordinary characters inside one.
  1554. struct {
  1555. const char *value;
  1556. std::vector<std::pair<const char *, const char *>> expected;
  1557. } cases[] = {
  1558. {"name=\"file1\"; filename=\"a.txt\"",
  1559. {{"name", "file1"}, {"filename", "a.txt"}}},
  1560. // Whitespace around '=' and ';' is still trimmed
  1561. {"name=\"file2\" ;filename = \"a.html\"",
  1562. {{"name", "file2"}, {"filename", "a.html"}}},
  1563. // '=' inside the value used to leave only the text after the last one
  1564. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1565. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1566. {"name=\"x=y\"", {{"name", "x=y"}}},
  1567. // ';' inside the value used to truncate the pair and leave a bogus one
  1568. {"name=\"file3\"; filename=\"a;b.txt\"",
  1569. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1570. // An unquoted value keeps working, and so does filename*
  1571. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1572. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1573. // A parameter with no key is dropped rather than turned into one whose
  1574. // key is the value
  1575. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1576. };
  1577. for (const auto &c : cases) {
  1578. Params params;
  1579. detail::parse_disposition_params(c.value, params);
  1580. for (const auto &kv : c.expected) {
  1581. auto it = params.find(kv.first);
  1582. ASSERT_NE(it, params.end())
  1583. << "value: " << c.value << ", key: " << kv.first;
  1584. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1585. }
  1586. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1587. }
  1588. }
  1589. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1590. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1591. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1592. Server svr;
  1593. std::string field_value, file_name, file_filename;
  1594. bool has_field = false, has_file = false;
  1595. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1596. has_field = req.form.has_field("x=y");
  1597. field_value = req.form.get_field("x=y");
  1598. has_file = req.form.has_file("file1");
  1599. const auto &file = req.form.get_file("file1");
  1600. file_name = file.name;
  1601. file_filename = file.filename;
  1602. res.set_content("ok", "text/plain");
  1603. });
  1604. auto port = svr.bind_to_any_port(HOST);
  1605. thread t = thread([&] { svr.listen_after_bind(); });
  1606. auto se = detail::scope_exit([&] {
  1607. svr.stop();
  1608. t.join();
  1609. ASSERT_FALSE(svr.is_running());
  1610. });
  1611. svr.wait_until_ready();
  1612. UploadFormDataItems items = {
  1613. {"x=y", "field-value", "", ""},
  1614. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1615. };
  1616. Client cli(HOST, port);
  1617. auto res = cli.Post("/quoted", items);
  1618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1619. ASSERT_EQ(StatusCode::OK_200, res->status);
  1620. EXPECT_TRUE(has_field);
  1621. EXPECT_EQ("field-value", field_value);
  1622. EXPECT_TRUE(has_file);
  1623. EXPECT_EQ("file1", file_name);
  1624. EXPECT_EQ("a;b=report.pdf", file_filename);
  1625. }
  1626. TEST(GetHeaderValueTest, DefaultValue) {
  1627. Headers headers = {{"Dummy", "Dummy"}};
  1628. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1629. EXPECT_STREQ("text/plain", val);
  1630. }
  1631. TEST(GetHeaderValueTest, DefaultValueInt) {
  1632. Headers headers = {{"Dummy", "Dummy"}};
  1633. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1634. EXPECT_EQ(100ull, val);
  1635. }
  1636. TEST(GetHeaderValueTest, RegularValue) {
  1637. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1638. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1639. EXPECT_STREQ("text/html", val);
  1640. }
  1641. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1642. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1643. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1644. EXPECT_STREQ("text/html", val);
  1645. }
  1646. TEST(GetHeaderValueTest, SetContent) {
  1647. Response res;
  1648. res.set_content("html", "text/html");
  1649. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1650. res.set_content("text", "text/plain");
  1651. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1652. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1653. }
  1654. TEST(GetHeaderValueTest, RegularValueInt) {
  1655. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1656. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1657. EXPECT_EQ(100ull, val);
  1658. }
  1659. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1660. Headers headers = {{"Content-Length", "x"}};
  1661. auto is_invalid_value = false;
  1662. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1663. is_invalid_value);
  1664. EXPECT_EQ(0ull, val);
  1665. EXPECT_TRUE(is_invalid_value);
  1666. }
  1667. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1668. // An all-digit value that overflows size_t must be reported as invalid, not
  1669. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1670. // a large length to a small one on 32-bit builds, leaving the framing length
  1671. // wrong while is_invalid_value stayed false.
  1672. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1673. auto is_invalid_value = false;
  1674. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1675. is_invalid_value);
  1676. EXPECT_TRUE(is_invalid_value);
  1677. // A well-formed length is unaffected.
  1678. Headers ok = {{"Content-Length", "1234"}};
  1679. is_invalid_value = false;
  1680. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1681. is_invalid_value);
  1682. EXPECT_EQ(1234ull, val);
  1683. EXPECT_FALSE(is_invalid_value);
  1684. }
  1685. TEST(GetHeaderValueTest, Range) {
  1686. {
  1687. Headers headers = {make_range_header({{1, -1}})};
  1688. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1689. EXPECT_STREQ("bytes=1-", val);
  1690. }
  1691. {
  1692. Headers headers = {make_range_header({{-1, 1}})};
  1693. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1694. EXPECT_STREQ("bytes=-1", val);
  1695. }
  1696. {
  1697. Headers headers = {make_range_header({{1, 10}})};
  1698. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1699. EXPECT_STREQ("bytes=1-10", val);
  1700. }
  1701. {
  1702. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1703. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1704. EXPECT_STREQ("bytes=1-10, 100-", val);
  1705. }
  1706. {
  1707. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1708. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1709. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1710. }
  1711. {
  1712. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1713. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1714. EXPECT_STREQ("bytes=0-0, -1", val);
  1715. }
  1716. }
  1717. TEST(BearerTokenAuthTest, SchemeValidation) {
  1718. // A value shorter than "Bearer " must not throw from the fixed-length
  1719. // substr, and a non-Bearer scheme must not be reported as a token.
  1720. struct {
  1721. const char *value;
  1722. const char *expected;
  1723. } cases[] = {
  1724. {"x", ""},
  1725. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1726. {"Bearer abc123", "abc123"},
  1727. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1728. };
  1729. for (const auto &c : cases) {
  1730. Request req;
  1731. req.set_header("Authorization", c.value);
  1732. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1733. }
  1734. }
  1735. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1736. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1737. // to depend on the standard library (libstdc++ handed back duplicates in
  1738. // reverse insertion order, libc++ in insertion order).
  1739. Request req;
  1740. req.set_header("Accept-Encoding", "gzip");
  1741. req.set_header("Accept-Encoding", "deflate");
  1742. req.set_header("Accept-Encoding", "br");
  1743. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1744. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1745. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1746. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1747. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1748. }
  1749. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1750. Request req;
  1751. req.set_header("X-Test", "only");
  1752. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1753. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1754. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1755. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1756. }
  1757. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1758. Request req;
  1759. req.set_header("X-First", "1");
  1760. req.set_header("X-Test", "2");
  1761. req.params.emplace("first", "1");
  1762. req.params.emplace("test", "2");
  1763. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1764. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1765. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1766. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1767. // The second one is negative when read as a signed value
  1768. const auto max_id = (std::numeric_limits<size_t>::max)();
  1769. for (auto id : {max_id / 2, max_id}) {
  1770. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1771. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1772. EXPECT_EQ("", req.get_param_value("test", id));
  1773. EXPECT_EQ("", req.form.get_field("test", id));
  1774. EXPECT_EQ("", req.form.get_file("test", id).content);
  1775. }
  1776. }
  1777. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1778. Headers headers;
  1779. headers.emplace("Host", "example.com");
  1780. headers.emplace("Accept-Encoding", "gzip");
  1781. headers.emplace("User-Agent", "test");
  1782. headers.emplace("Accept-Encoding", "deflate");
  1783. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1784. "Accept-Encoding=deflate ",
  1785. entries_to_string(headers));
  1786. }
  1787. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1788. Headers headers = {{"Content-Type", "text/html"},
  1789. {"CONTENT-TYPE", "text/xml"}};
  1790. EXPECT_EQ(2U, headers.count("content-type"));
  1791. auto it = headers.find("content-type");
  1792. ASSERT_TRUE(it != headers.end());
  1793. EXPECT_EQ("text/html", it->second);
  1794. }
  1795. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1796. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1797. // drop only those fields and leave everything positioned between them.
  1798. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1799. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1800. auto rng = headers.equal_range("a");
  1801. headers.erase(rng.first, rng.second);
  1802. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1803. }
  1804. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1805. Headers headers = {
  1806. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1807. EXPECT_EQ(3U, headers.erase("A"));
  1808. EXPECT_EQ(0U, headers.count("A"));
  1809. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1810. }
  1811. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1812. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1813. headers.emplace_front("Host", "example.com");
  1814. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1815. entries_to_string(headers));
  1816. }
  1817. TEST(ParseHeaderValueTest, Range) {
  1818. {
  1819. Ranges ranges;
  1820. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1821. EXPECT_TRUE(ret);
  1822. EXPECT_EQ(1u, ranges.size());
  1823. EXPECT_EQ(1u, ranges[0].first);
  1824. EXPECT_EQ(-1, ranges[0].second);
  1825. }
  1826. {
  1827. Ranges ranges;
  1828. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1829. EXPECT_TRUE(ret);
  1830. EXPECT_EQ(1u, ranges.size());
  1831. EXPECT_EQ(-1, ranges[0].first);
  1832. EXPECT_EQ(1u, ranges[0].second);
  1833. }
  1834. {
  1835. Ranges ranges;
  1836. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1837. EXPECT_TRUE(ret);
  1838. EXPECT_EQ(1u, ranges.size());
  1839. EXPECT_EQ(1u, ranges[0].first);
  1840. EXPECT_EQ(10u, ranges[0].second);
  1841. }
  1842. {
  1843. Ranges ranges;
  1844. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1845. EXPECT_FALSE(ret);
  1846. }
  1847. {
  1848. Ranges ranges;
  1849. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1850. EXPECT_TRUE(ret);
  1851. EXPECT_EQ(2u, ranges.size());
  1852. EXPECT_EQ(1u, ranges[0].first);
  1853. EXPECT_EQ(10u, ranges[0].second);
  1854. EXPECT_EQ(100u, ranges[1].first);
  1855. EXPECT_EQ(-1, ranges[1].second);
  1856. }
  1857. {
  1858. Ranges ranges;
  1859. auto ret =
  1860. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1861. EXPECT_TRUE(ret);
  1862. EXPECT_EQ(3u, ranges.size());
  1863. EXPECT_EQ(1u, ranges[0].first);
  1864. EXPECT_EQ(10u, ranges[0].second);
  1865. EXPECT_EQ(100u, ranges[1].first);
  1866. EXPECT_EQ(200u, ranges[1].second);
  1867. EXPECT_EQ(300u, ranges[2].first);
  1868. EXPECT_EQ(400u, ranges[2].second);
  1869. }
  1870. {
  1871. Ranges ranges;
  1872. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1873. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1874. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1875. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1876. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1877. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1878. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1879. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1880. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1881. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1882. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1883. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1884. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1885. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1886. EXPECT_FALSE(
  1887. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1888. EXPECT_TRUE(ranges.empty());
  1889. }
  1890. {
  1891. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1892. // remainder of the representation, so it stays accepted.
  1893. Ranges ranges;
  1894. auto ret =
  1895. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1896. EXPECT_TRUE(ret);
  1897. ASSERT_EQ(1u, ranges.size());
  1898. EXPECT_EQ(0, ranges[0].first);
  1899. EXPECT_EQ(-1, ranges[0].second);
  1900. }
  1901. // RFC 9110 14.1: range unit names are case-insensitive.
  1902. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1903. Ranges ranges;
  1904. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1905. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1906. }
  1907. }
  1908. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1909. Request req;
  1910. req.set_header("Accept-Encoding", "gzip");
  1911. Response res;
  1912. res.set_header("Content-Type", "text/plain");
  1913. auto ret = detail::encoding_type(req, res);
  1914. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1915. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1916. #else
  1917. EXPECT_TRUE(ret == detail::EncodingType::None);
  1918. #endif
  1919. }
  1920. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1921. Request req;
  1922. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1923. Response res;
  1924. res.set_header("Content-Type", "text/plain");
  1925. auto ret = detail::encoding_type(req, res);
  1926. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1927. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1928. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1929. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1930. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1931. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1932. #else
  1933. EXPECT_TRUE(ret == detail::EncodingType::None);
  1934. #endif
  1935. }
  1936. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1937. Request req;
  1938. req.set_header("Accept-Encoding",
  1939. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1940. Response res;
  1941. res.set_header("Content-Type", "text/plain");
  1942. auto ret = detail::encoding_type(req, res);
  1943. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1944. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1945. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1946. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1947. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1948. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1949. #else
  1950. EXPECT_TRUE(ret == detail::EncodingType::None);
  1951. #endif
  1952. }
  1953. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1954. // All supported encodings rejected with q=0 should return None
  1955. Request req;
  1956. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1957. Response res;
  1958. res.set_header("Content-Type", "text/plain");
  1959. auto ret = detail::encoding_type(req, res);
  1960. EXPECT_TRUE(ret == detail::EncodingType::None);
  1961. }
  1962. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1963. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1964. Request req;
  1965. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1966. Response res;
  1967. res.set_header("Content-Type", "text/plain");
  1968. auto ret = detail::encoding_type(req, res);
  1969. EXPECT_TRUE(ret == detail::EncodingType::None);
  1970. }
  1971. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  1972. Request req;
  1973. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  1974. Response res;
  1975. res.set_header("Content-Type", "text/plain");
  1976. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  1977. }
  1978. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1979. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1980. Request req;
  1981. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1982. Response res;
  1983. res.set_header("Content-Type", "text/plain");
  1984. auto ret = detail::encoding_type(req, res);
  1985. EXPECT_TRUE(ret == detail::EncodingType::None);
  1986. }
  1987. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1988. // RFC 7231: Accept-Encoding values are case-insensitive
  1989. Request req;
  1990. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1991. Response res;
  1992. res.set_header("Content-Type", "text/plain");
  1993. auto ret = detail::encoding_type(req, res);
  1994. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1995. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1996. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1997. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1998. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1999. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2000. #else
  2001. EXPECT_TRUE(ret == detail::EncodingType::None);
  2002. #endif
  2003. }
  2004. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2005. // q value should determine priority, not hardcoded order
  2006. Request req;
  2007. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2008. Response res;
  2009. res.set_header("Content-Type", "text/plain");
  2010. auto ret = detail::encoding_type(req, res);
  2011. // gzip has highest q=1.0, so it should be selected even though
  2012. // br and zstd are also supported
  2013. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2014. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2015. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2016. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2017. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2018. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2019. #else
  2020. EXPECT_TRUE(ret == detail::EncodingType::None);
  2021. #endif
  2022. }
  2023. TEST(BufferStreamTest, read) {
  2024. detail::BufferStream strm1;
  2025. Stream &strm = strm1;
  2026. EXPECT_EQ(5, strm.write("hello"));
  2027. char buf[512];
  2028. EXPECT_EQ(2, strm.read(buf, 2));
  2029. EXPECT_EQ('h', buf[0]);
  2030. EXPECT_EQ('e', buf[1]);
  2031. EXPECT_EQ(2, strm.read(buf, 2));
  2032. EXPECT_EQ('l', buf[0]);
  2033. EXPECT_EQ('l', buf[1]);
  2034. EXPECT_EQ(1, strm.read(buf, 1));
  2035. EXPECT_EQ('o', buf[0]);
  2036. EXPECT_EQ(0, strm.read(buf, 1));
  2037. }
  2038. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2039. auto host = "www.httpwatch.com";
  2040. auto ip = hosted_at(host);
  2041. EXPECT_EQ("23.96.13.243", ip);
  2042. std::vector<std::string> addrs;
  2043. hosted_at(host, addrs);
  2044. EXPECT_EQ(1u, addrs.size());
  2045. }
  2046. #if 0 // It depends on each test environment...
  2047. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2048. auto host = "www.youtube.com";
  2049. std::vector<std::string> addrs;
  2050. hosted_at(host, addrs);
  2051. EXPECT_EQ(20u, addrs.size());
  2052. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2053. EXPECT_TRUE(it != addrs.end());
  2054. }
  2055. #endif
  2056. class ChunkedEncodingTest : public ::testing::Test {
  2057. protected:
  2058. ChunkedEncodingTest()
  2059. : cli_(HOST, PORT)
  2060. #ifdef CPPHTTPLIB_SSL_ENABLED
  2061. ,
  2062. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2063. #endif
  2064. {
  2065. cli_.set_connection_timeout(2);
  2066. #ifdef CPPHTTPLIB_SSL_ENABLED
  2067. cli_.enable_server_certificate_verification(false);
  2068. #endif
  2069. }
  2070. virtual void SetUp() {
  2071. read_file("./image.jpg", image_data_);
  2072. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2073. res.set_content("Hello World!", "text/plain");
  2074. });
  2075. svr_.Get(
  2076. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2077. res.set_chunked_content_provider(
  2078. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2079. size_t remaining = image_data_.size() - offset;
  2080. if (remaining == 0) {
  2081. sink.done();
  2082. } else {
  2083. constexpr size_t CHUNK_SIZE = 1024;
  2084. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2085. sink.write(&image_data_[offset], send_size);
  2086. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2087. }
  2088. return true;
  2089. });
  2090. });
  2091. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2092. svr_.wait_until_ready();
  2093. }
  2094. virtual void TearDown() {
  2095. svr_.stop();
  2096. if (!request_threads_.empty()) {
  2097. std::this_thread::sleep_for(std::chrono::seconds(1));
  2098. for (auto &t : request_threads_) {
  2099. t.join();
  2100. }
  2101. }
  2102. t_.join();
  2103. }
  2104. #ifdef CPPHTTPLIB_SSL_ENABLED
  2105. SSLClient cli_;
  2106. SSLServer svr_;
  2107. #else
  2108. Client cli_;
  2109. Server svr_;
  2110. #endif
  2111. thread t_;
  2112. std::vector<thread> request_threads_;
  2113. std::string image_data_;
  2114. };
  2115. TEST_F(ChunkedEncodingTest, NormalGet) {
  2116. auto res = cli_.Get("/chunked");
  2117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2118. std::string out;
  2119. read_file("./image.jpg", out);
  2120. EXPECT_EQ(StatusCode::OK_200, res->status);
  2121. EXPECT_EQ(out, res->body);
  2122. }
  2123. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2124. std::string body;
  2125. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2126. body.append(data, data_length);
  2127. return true;
  2128. });
  2129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2130. std::string out;
  2131. read_file("./image.jpg", out);
  2132. EXPECT_EQ(StatusCode::OK_200, res->status);
  2133. EXPECT_EQ(out, body);
  2134. }
  2135. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2136. std::string body;
  2137. auto res = cli_.Get(
  2138. "/chunked",
  2139. [&](const Response &response) {
  2140. EXPECT_EQ(StatusCode::OK_200, response.status);
  2141. return true;
  2142. },
  2143. [&](const char *data, size_t data_length) {
  2144. body.append(data, data_length);
  2145. return true;
  2146. });
  2147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2148. std::string out;
  2149. read_file("./image.jpg", out);
  2150. EXPECT_EQ(StatusCode::OK_200, res->status);
  2151. EXPECT_EQ(out, body);
  2152. }
  2153. TEST(RangeTest, FromHTTPBin_Online) {
  2154. auto host = "httpbingo.org";
  2155. auto path = std::string{"/range/32"};
  2156. #ifdef CPPHTTPLIB_SSL_ENABLED
  2157. auto port = 443;
  2158. SSLClient cli(host, port);
  2159. #else
  2160. auto port = 80;
  2161. Client cli(host, port);
  2162. #endif
  2163. cli.set_connection_timeout(5);
  2164. {
  2165. auto res = cli.Get(path);
  2166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2167. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2168. EXPECT_EQ(StatusCode::OK_200, res->status);
  2169. }
  2170. {
  2171. Headers headers = {make_range_header({{1, -1}})};
  2172. auto res = cli.Get(path, headers);
  2173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2174. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2175. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2176. }
  2177. {
  2178. Headers headers = {make_range_header({{1, 10}})};
  2179. auto res = cli.Get(path, headers);
  2180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2181. EXPECT_EQ("bcdefghijk", res->body);
  2182. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2183. }
  2184. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2185. // entire resource, while the original httpbin returned 200. Both are
  2186. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2187. {
  2188. Headers headers = {make_range_header({{0, 31}})};
  2189. auto res = cli.Get(path, headers);
  2190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2191. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2192. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2193. res->status == StatusCode::PartialContent_206);
  2194. }
  2195. {
  2196. Headers headers = {make_range_header({{0, -1}})};
  2197. auto res = cli.Get(path, headers);
  2198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2199. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2200. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2201. res->status == StatusCode::PartialContent_206);
  2202. }
  2203. // go-httpbin returns 206 with clamped range for over-range requests,
  2204. // while the original httpbin returned 416. Both behaviors are observed
  2205. // in real servers, so we only verify the request succeeds.
  2206. {
  2207. Headers headers = {make_range_header({{0, 32}})};
  2208. auto res = cli.Get(path, headers);
  2209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2210. }
  2211. }
  2212. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2213. auto host = "unresolvableaddress.local";
  2214. auto path = std::string{"/"};
  2215. #ifdef CPPHTTPLIB_SSL_ENABLED
  2216. auto port = 443;
  2217. SSLClient cli(host, port);
  2218. #else
  2219. auto port = 80;
  2220. Client cli(host, port);
  2221. #endif
  2222. cli.set_connection_timeout(1);
  2223. {
  2224. auto res = cli.Get(path);
  2225. ASSERT_FALSE(res);
  2226. }
  2227. std::this_thread::sleep_for(std::chrono::seconds(8));
  2228. }
  2229. #if defined(__linux__) && defined(__GLIBC__) && \
  2230. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2231. // Forward declaration: in split builds split.py strips `inline` and moves the
  2232. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2233. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2234. // against the symbol in both header-only and split builds.
  2235. namespace httplib {
  2236. namespace detail {
  2237. int getaddrinfo_with_timeout(const char *node, const char *service,
  2238. const struct addrinfo *hints,
  2239. struct addrinfo **res, time_t timeout_sec);
  2240. } // namespace detail
  2241. } // namespace httplib
  2242. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2243. //
  2244. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2245. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2246. // gai_suspend() call hits the connection timeout the function calls
  2247. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2248. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2249. // still alive and still references the now-destroyed stack frame.
  2250. //
  2251. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2252. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2253. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2254. // and runs them in a container.
  2255. namespace {
  2256. bool should_run_issue_2431_tests() {
  2257. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2258. return v && *v && std::string(v) != "0";
  2259. }
  2260. std::string unique_unresolvable_host(int n) {
  2261. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2262. // glibc still asks the configured nameserver — which is exactly the path
  2263. // we want to exercise. A unique label per call avoids the resolver cache.
  2264. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2265. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2266. std::to_string(n) + ".invalid";
  2267. }
  2268. } // namespace
  2269. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2270. if (!should_run_issue_2431_tests()) {
  2271. GTEST_SKIP()
  2272. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2273. }
  2274. for (int i = 0; i < 8; ++i) {
  2275. struct addrinfo hints;
  2276. memset(&hints, 0, sizeof(hints));
  2277. hints.ai_family = AF_UNSPEC;
  2278. hints.ai_socktype = SOCK_STREAM;
  2279. auto host = unique_unresolvable_host(i);
  2280. struct addrinfo *result = nullptr;
  2281. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2282. &result, /*timeout_sec=*/1);
  2283. if (rc == 0 && result) { freeaddrinfo(result); }
  2284. }
  2285. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2286. // stack region they still believe holds their gaicb.
  2287. std::this_thread::sleep_for(std::chrono::seconds(3));
  2288. }
  2289. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2290. if (!should_run_issue_2431_tests()) {
  2291. GTEST_SKIP()
  2292. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2293. }
  2294. std::atomic<bool> stop{false};
  2295. std::vector<std::thread> threads;
  2296. for (int t = 0; t < 8; ++t) {
  2297. threads.emplace_back([t, &stop] {
  2298. int i = 0;
  2299. while (!stop.load(std::memory_order_relaxed)) {
  2300. struct addrinfo hints;
  2301. memset(&hints, 0, sizeof(hints));
  2302. hints.ai_family = AF_UNSPEC;
  2303. hints.ai_socktype = SOCK_STREAM;
  2304. auto host = unique_unresolvable_host(t * 100000 + i++);
  2305. struct addrinfo *result = nullptr;
  2306. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2307. &result, /*timeout_sec=*/1);
  2308. if (rc == 0 && result) { freeaddrinfo(result); }
  2309. }
  2310. });
  2311. }
  2312. std::this_thread::sleep_for(std::chrono::seconds(8));
  2313. stop.store(true, std::memory_order_relaxed);
  2314. for (auto &th : threads) {
  2315. th.join();
  2316. }
  2317. std::this_thread::sleep_for(std::chrono::seconds(3));
  2318. }
  2319. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2320. if (!should_run_issue_2431_tests()) {
  2321. GTEST_SKIP()
  2322. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2323. }
  2324. std::atomic<bool> stop{false};
  2325. std::vector<std::thread> threads;
  2326. for (int t = 0; t < 8; ++t) {
  2327. threads.emplace_back([t, &stop] {
  2328. int i = 0;
  2329. while (!stop.load(std::memory_order_relaxed)) {
  2330. auto host = unique_unresolvable_host(t * 100000 + i++);
  2331. Client cli(host, 80);
  2332. cli.set_connection_timeout(1, 0);
  2333. cli.set_read_timeout(1, 0);
  2334. cli.set_write_timeout(1, 0);
  2335. (void)cli.Get("/");
  2336. }
  2337. });
  2338. }
  2339. std::this_thread::sleep_for(std::chrono::seconds(8));
  2340. stop.store(true, std::memory_order_relaxed);
  2341. for (auto &th : threads) {
  2342. th.join();
  2343. }
  2344. std::this_thread::sleep_for(std::chrono::seconds(3));
  2345. }
  2346. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2347. TEST(ConnectionErrorTest, InvalidHost) {
  2348. auto host = "-abcde.com";
  2349. #ifdef CPPHTTPLIB_SSL_ENABLED
  2350. auto port = 443;
  2351. SSLClient cli(host, port);
  2352. #else
  2353. auto port = 80;
  2354. Client cli(host, port);
  2355. #endif
  2356. cli.set_connection_timeout(std::chrono::seconds(2));
  2357. auto res = cli.Get("/");
  2358. ASSERT_TRUE(!res);
  2359. EXPECT_EQ(Error::Connection, res.error());
  2360. }
  2361. TEST(ConnectionErrorTest, InvalidHost2) {
  2362. auto host = "httpcan.org/";
  2363. #ifdef CPPHTTPLIB_SSL_ENABLED
  2364. SSLClient cli(host);
  2365. #else
  2366. Client cli(host);
  2367. #endif
  2368. cli.set_connection_timeout(std::chrono::seconds(2));
  2369. auto res = cli.Get("/");
  2370. ASSERT_TRUE(!res);
  2371. EXPECT_EQ(Error::Connection, res.error());
  2372. }
  2373. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2374. auto host = "httpcan.org/";
  2375. #ifdef CPPHTTPLIB_SSL_ENABLED
  2376. SSLClient cli(host);
  2377. #else
  2378. Client cli(host);
  2379. #endif
  2380. cli.set_connection_timeout(std::chrono::seconds(2));
  2381. auto res = cli.Get("/");
  2382. ASSERT_TRUE(!res);
  2383. stringstream s;
  2384. s << "error code: " << res.error();
  2385. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2386. }
  2387. TEST(ConnectionErrorTest, InvalidPort) {
  2388. auto host = "localhost";
  2389. auto port = 44380;
  2390. #ifdef CPPHTTPLIB_SSL_ENABLED
  2391. SSLClient cli(host, port);
  2392. #else
  2393. Client cli(host, port);
  2394. #endif
  2395. cli.set_connection_timeout(std::chrono::seconds(2));
  2396. auto res = cli.Get("/");
  2397. ASSERT_TRUE(!res);
  2398. EXPECT_TRUE(Error::Connection == res.error() ||
  2399. Error::ConnectionTimeout == res.error());
  2400. }
  2401. TEST(ConnectionErrorTest, Timeout_Online) {
  2402. auto host = "google.com";
  2403. #ifdef CPPHTTPLIB_SSL_ENABLED
  2404. auto port = 44380;
  2405. SSLClient cli(host, port);
  2406. #else
  2407. auto port = 8080;
  2408. Client cli(host, port);
  2409. #endif
  2410. cli.set_connection_timeout(std::chrono::seconds(2));
  2411. // only probe one address type so that the error reason
  2412. // correlates to the timed-out IPv4, not the unsupported
  2413. // IPv6 connection attempt
  2414. cli.set_address_family(AF_INET);
  2415. auto res = cli.Get("/");
  2416. ASSERT_TRUE(!res);
  2417. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2418. }
  2419. TEST(CancelTest, NoCancel_Online) {
  2420. auto host = "httpbingo.org";
  2421. auto path = std::string{"/range/32"};
  2422. #ifdef CPPHTTPLIB_SSL_ENABLED
  2423. auto port = 443;
  2424. SSLClient cli(host, port);
  2425. #else
  2426. auto port = 80;
  2427. Client cli(host, port);
  2428. #endif
  2429. cli.set_connection_timeout(std::chrono::seconds(5));
  2430. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2432. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2433. EXPECT_EQ(StatusCode::OK_200, res->status);
  2434. }
  2435. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2436. // Use /bytes with a large payload so that the DownloadProgress callback
  2437. // (which only fires for Content-Length responses) is invoked before the
  2438. // entire body is received, giving cancellation a chance to fire.
  2439. auto host = "httpbingo.org";
  2440. auto path = std::string{"/bytes/524288"};
  2441. #ifdef CPPHTTPLIB_SSL_ENABLED
  2442. auto port = 443;
  2443. SSLClient cli(host, port);
  2444. #else
  2445. auto port = 80;
  2446. Client cli(host, port);
  2447. #endif
  2448. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2449. cli.set_connection_timeout(std::chrono::seconds(5));
  2450. ASSERT_TRUE(!res);
  2451. EXPECT_EQ(Error::Canceled, res.error());
  2452. }
  2453. TEST(CancelTest, WithCancelLargePayload_Online) {
  2454. auto host = "httpbingo.org";
  2455. auto path = std::string{"/bytes/524288"};
  2456. #ifdef CPPHTTPLIB_SSL_ENABLED
  2457. auto port = 443;
  2458. SSLClient cli(host, port);
  2459. #else
  2460. auto port = 80;
  2461. Client cli(host, port);
  2462. #endif
  2463. cli.set_connection_timeout(std::chrono::seconds(5));
  2464. uint32_t count = 0;
  2465. auto res =
  2466. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2467. ASSERT_TRUE(!res);
  2468. EXPECT_EQ(Error::Canceled, res.error());
  2469. }
  2470. TEST(CancelTest, NoCancelPost) {
  2471. Server svr;
  2472. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2473. res.set_content("Hello World!", "text/plain");
  2474. });
  2475. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2476. auto se = detail::scope_exit([&] {
  2477. svr.stop();
  2478. thread.join();
  2479. ASSERT_FALSE(svr.is_running());
  2480. });
  2481. svr.wait_until_ready();
  2482. Client cli(HOST, PORT);
  2483. cli.set_connection_timeout(std::chrono::seconds(5));
  2484. auto res =
  2485. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2486. "application/json", [](uint64_t, uint64_t) { return true; });
  2487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2488. EXPECT_EQ("Hello World!", res->body);
  2489. EXPECT_EQ(StatusCode::OK_200, res->status);
  2490. }
  2491. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2492. Server svr;
  2493. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2494. res.set_content("Hello World!", "text/plain");
  2495. });
  2496. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2497. auto se = detail::scope_exit([&] {
  2498. svr.stop();
  2499. thread.join();
  2500. ASSERT_FALSE(svr.is_running());
  2501. });
  2502. svr.wait_until_ready();
  2503. Client cli(HOST, PORT);
  2504. cli.set_connection_timeout(std::chrono::seconds(5));
  2505. auto res =
  2506. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2507. "application/json", [](uint64_t, uint64_t) { return false; });
  2508. ASSERT_TRUE(!res);
  2509. EXPECT_EQ(Error::Canceled, res.error());
  2510. }
  2511. TEST(CancelTest, WithCancelLargePayloadPost) {
  2512. Server svr;
  2513. svr.set_payload_max_length(200 * 1024 * 1024);
  2514. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2515. res.set_content(LARGE_DATA, "text/plain");
  2516. });
  2517. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2518. auto se = detail::scope_exit([&] {
  2519. svr.stop();
  2520. thread.join();
  2521. ASSERT_FALSE(svr.is_running());
  2522. });
  2523. svr.wait_until_ready();
  2524. Client cli(HOST, PORT);
  2525. cli.set_payload_max_length(200 * 1024 * 1024);
  2526. cli.set_connection_timeout(std::chrono::seconds(5));
  2527. auto res =
  2528. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2529. "application/json", [](uint64_t, uint64_t) { return false; });
  2530. ASSERT_TRUE(!res);
  2531. EXPECT_EQ(Error::Canceled, res.error());
  2532. }
  2533. TEST(CancelTest, NoCancelPut) {
  2534. Server svr;
  2535. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2536. res.set_content("Hello World!", "text/plain");
  2537. });
  2538. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2539. auto se = detail::scope_exit([&] {
  2540. svr.stop();
  2541. thread.join();
  2542. ASSERT_FALSE(svr.is_running());
  2543. });
  2544. svr.wait_until_ready();
  2545. Client cli(HOST, PORT);
  2546. cli.set_connection_timeout(std::chrono::seconds(5));
  2547. auto res =
  2548. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2549. "application/json", [](uint64_t, uint64_t) { return true; });
  2550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2551. EXPECT_EQ("Hello World!", res->body);
  2552. EXPECT_EQ(StatusCode::OK_200, res->status);
  2553. }
  2554. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2555. Server svr;
  2556. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2557. res.set_content("Hello World!", "text/plain");
  2558. });
  2559. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2560. auto se = detail::scope_exit([&] {
  2561. svr.stop();
  2562. thread.join();
  2563. ASSERT_FALSE(svr.is_running());
  2564. });
  2565. svr.wait_until_ready();
  2566. Client cli(HOST, PORT);
  2567. cli.set_connection_timeout(std::chrono::seconds(5));
  2568. auto res =
  2569. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2570. "application/json", [](uint64_t, uint64_t) { return false; });
  2571. ASSERT_TRUE(!res);
  2572. EXPECT_EQ(Error::Canceled, res.error());
  2573. }
  2574. TEST(CancelTest, WithCancelLargePayloadPut) {
  2575. Server svr;
  2576. svr.set_payload_max_length(200 * 1024 * 1024);
  2577. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2578. res.set_content(LARGE_DATA, "text/plain");
  2579. });
  2580. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2581. auto se = detail::scope_exit([&] {
  2582. svr.stop();
  2583. thread.join();
  2584. ASSERT_FALSE(svr.is_running());
  2585. });
  2586. svr.wait_until_ready();
  2587. Client cli(HOST, PORT);
  2588. cli.set_payload_max_length(200 * 1024 * 1024);
  2589. cli.set_connection_timeout(std::chrono::seconds(5));
  2590. auto res =
  2591. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2592. "application/json", [](uint64_t, uint64_t) { return false; });
  2593. ASSERT_TRUE(!res);
  2594. EXPECT_EQ(Error::Canceled, res.error());
  2595. }
  2596. TEST(CancelTest, NoCancelPatch) {
  2597. Server svr;
  2598. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2599. res.set_content("Hello World!", "text/plain");
  2600. });
  2601. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2602. auto se = detail::scope_exit([&] {
  2603. svr.stop();
  2604. thread.join();
  2605. ASSERT_FALSE(svr.is_running());
  2606. });
  2607. svr.wait_until_ready();
  2608. Client cli(HOST, PORT);
  2609. cli.set_connection_timeout(std::chrono::seconds(5));
  2610. auto res =
  2611. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2612. "application/json", [](uint64_t, uint64_t) { return true; });
  2613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2614. EXPECT_EQ("Hello World!", res->body);
  2615. EXPECT_EQ(StatusCode::OK_200, res->status);
  2616. }
  2617. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2618. Server svr;
  2619. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2620. res.set_content("Hello World!", "text/plain");
  2621. });
  2622. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2623. auto se = detail::scope_exit([&] {
  2624. svr.stop();
  2625. thread.join();
  2626. ASSERT_FALSE(svr.is_running());
  2627. });
  2628. svr.wait_until_ready();
  2629. Client cli(HOST, PORT);
  2630. cli.set_connection_timeout(std::chrono::seconds(5));
  2631. auto res =
  2632. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2633. "application/json", [](uint64_t, uint64_t) { return false; });
  2634. ASSERT_TRUE(!res);
  2635. EXPECT_EQ(Error::Canceled, res.error());
  2636. }
  2637. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2638. Server svr;
  2639. svr.set_payload_max_length(200 * 1024 * 1024);
  2640. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2641. res.set_content(LARGE_DATA, "text/plain");
  2642. });
  2643. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2644. auto se = detail::scope_exit([&] {
  2645. svr.stop();
  2646. thread.join();
  2647. ASSERT_FALSE(svr.is_running());
  2648. });
  2649. svr.wait_until_ready();
  2650. Client cli(HOST, PORT);
  2651. cli.set_payload_max_length(200 * 1024 * 1024);
  2652. cli.set_connection_timeout(std::chrono::seconds(5));
  2653. auto res =
  2654. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2655. "application/json", [](uint64_t, uint64_t) { return false; });
  2656. ASSERT_TRUE(!res);
  2657. EXPECT_EQ(Error::Canceled, res.error());
  2658. }
  2659. TEST(CancelTest, NoCancelDelete) {
  2660. Server svr;
  2661. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2662. res.set_content("Hello World!", "text/plain");
  2663. });
  2664. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2665. auto se = detail::scope_exit([&] {
  2666. svr.stop();
  2667. thread.join();
  2668. ASSERT_FALSE(svr.is_running());
  2669. });
  2670. svr.wait_until_ready();
  2671. Client cli(HOST, PORT);
  2672. cli.set_connection_timeout(std::chrono::seconds(5));
  2673. auto res =
  2674. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2675. "application/json", [](uint64_t, uint64_t) { return true; });
  2676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2677. EXPECT_EQ("Hello World!", res->body);
  2678. EXPECT_EQ(StatusCode::OK_200, res->status);
  2679. }
  2680. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2681. Server svr;
  2682. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2683. res.set_content("Hello World!", "text/plain");
  2684. });
  2685. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2686. auto se = detail::scope_exit([&] {
  2687. svr.stop();
  2688. thread.join();
  2689. ASSERT_FALSE(svr.is_running());
  2690. });
  2691. svr.wait_until_ready();
  2692. Client cli(HOST, PORT);
  2693. cli.set_connection_timeout(std::chrono::seconds(5));
  2694. auto res =
  2695. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2696. "application/json", [](uint64_t, uint64_t) { return false; });
  2697. ASSERT_TRUE(!res);
  2698. EXPECT_EQ(Error::Canceled, res.error());
  2699. }
  2700. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2701. Server svr;
  2702. svr.set_payload_max_length(200 * 1024 * 1024);
  2703. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2704. res.set_content(LARGE_DATA, "text/plain");
  2705. });
  2706. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2707. auto se = detail::scope_exit([&] {
  2708. svr.stop();
  2709. thread.join();
  2710. ASSERT_FALSE(svr.is_running());
  2711. });
  2712. svr.wait_until_ready();
  2713. Client cli(HOST, PORT);
  2714. cli.set_payload_max_length(200 * 1024 * 1024);
  2715. cli.set_connection_timeout(std::chrono::seconds(5));
  2716. auto res =
  2717. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2718. "application/json", [](uint64_t, uint64_t) { return false; });
  2719. ASSERT_TRUE(!res);
  2720. EXPECT_EQ(Error::Canceled, res.error());
  2721. }
  2722. static std::string remove_whitespace(const std::string &input) {
  2723. std::string output;
  2724. output.reserve(input.size());
  2725. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2726. [](unsigned char c) { return !std::isspace(c); });
  2727. return output;
  2728. }
  2729. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2730. auto host = "httpbingo.org";
  2731. auto path = std::string{"/basic-auth/hello/world"};
  2732. #ifdef CPPHTTPLIB_SSL_ENABLED
  2733. auto port = 443;
  2734. SSLClient cli(host, port);
  2735. #else
  2736. auto port = 80;
  2737. Client cli(host, port);
  2738. #endif
  2739. {
  2740. auto res = cli.Get(path);
  2741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2742. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2743. }
  2744. {
  2745. auto res = cli.Get(
  2746. path, Headers{make_basic_authentication_header("hello", "world")});
  2747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2748. auto body = remove_whitespace(res->body);
  2749. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2750. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2751. EXPECT_EQ(StatusCode::OK_200, res->status);
  2752. }
  2753. {
  2754. cli.set_basic_auth("hello", "world");
  2755. auto res = cli.Get(path);
  2756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2757. auto body = remove_whitespace(res->body);
  2758. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2759. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2760. EXPECT_EQ(StatusCode::OK_200, res->status);
  2761. }
  2762. {
  2763. cli.set_basic_auth("hello", "bad");
  2764. auto res = cli.Get(path);
  2765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2766. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2767. }
  2768. {
  2769. cli.set_basic_auth("bad", "world");
  2770. auto res = cli.Get(path);
  2771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2772. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2773. }
  2774. }
  2775. #ifdef CPPHTTPLIB_SSL_ENABLED
  2776. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2777. auto host = "httpbingo.org";
  2778. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2779. auto paths = std::vector<std::string>{
  2780. "/digest-auth/auth/hello/world/MD5",
  2781. "/digest-auth/auth/hello/world/SHA-256",
  2782. };
  2783. auto port = 443;
  2784. SSLClient cli(host, port);
  2785. {
  2786. auto res = cli.Get(unauth_path);
  2787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2788. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2789. }
  2790. {
  2791. cli.set_digest_auth("hello", "world");
  2792. for (const auto &path : paths) {
  2793. auto res = cli.Get(path.c_str());
  2794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2795. auto body = remove_whitespace(res->body);
  2796. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2797. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2798. EXPECT_EQ(StatusCode::OK_200, res->status);
  2799. }
  2800. cli.set_digest_auth("hello", "bad");
  2801. for (const auto &path : paths) {
  2802. auto res = cli.Get(path.c_str());
  2803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2804. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2805. }
  2806. }
  2807. }
  2808. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2809. // comma-separated list of challenges, and each challenge may itself carry a
  2810. // comma-separated auth-param list, so a server can legally offer Basic
  2811. // before Digest, either as two field lines or packed into one. Runs one 401
  2812. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2813. // value() joins them in receipt order) and checks that the retry carries a
  2814. // well-formed Digest Authorization header naming expected_realm.
  2815. static void
  2816. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2817. const std::string &expected_realm) {
  2818. std::atomic<int> hits{0};
  2819. Server svr;
  2820. svr.Get("/x", [&](const Request &req, Response &res) {
  2821. if (++hits == 1) {
  2822. res.status = StatusCode::Unauthorized_401;
  2823. for (const auto &challenge : challenges) {
  2824. res.set_header("WWW-Authenticate", challenge);
  2825. }
  2826. } else {
  2827. auto authorization = req.get_header_value("Authorization");
  2828. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2829. EXPECT_NE(std::string::npos,
  2830. authorization.find("realm=\"" + expected_realm + "\""));
  2831. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2832. res.set_content("ok", "text/plain");
  2833. }
  2834. });
  2835. auto port = svr.bind_to_any_port(HOST);
  2836. std::thread t([&]() { svr.listen_after_bind(); });
  2837. auto se = detail::scope_exit([&] {
  2838. svr.stop();
  2839. t.join();
  2840. });
  2841. svr.wait_until_ready();
  2842. Client cli(HOST, port);
  2843. cli.set_digest_auth("hello", "world");
  2844. auto res = cli.Get("/x");
  2845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2846. EXPECT_EQ(2, hits.load());
  2847. }
  2848. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2849. static const char *kDigestChallenge =
  2850. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2851. "algorithm=MD5";
  2852. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2853. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2854. "testrealm");
  2855. }
  2856. // Same challenge list with the schemes in the opposite order, to make sure
  2857. // the fix above didn't just special-case "Basic first".
  2858. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2859. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2860. "testrealm");
  2861. }
  2862. // A comma inside a quoted auth-param value must not be mistaken for the
  2863. // separator between two challenges (or two auth-params).
  2864. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2865. run_digest_challenge_list_test(
  2866. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2867. "algorithm=MD5"},
  2868. "test,realm");
  2869. }
  2870. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2871. // make_digest_authentication_header() dereferences both unconditionally, so
  2872. // a server sending a challenge missing either one must not be treated as
  2873. // usable -- doing so used to crash the client with std::out_of_range.
  2874. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2875. Server svr;
  2876. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2877. res.status = StatusCode::Unauthorized_401;
  2878. res.set_header("WWW-Authenticate", challenge);
  2879. });
  2880. auto port = svr.bind_to_any_port(HOST);
  2881. std::thread t([&]() { svr.listen_after_bind(); });
  2882. auto se = detail::scope_exit([&] {
  2883. svr.stop();
  2884. t.join();
  2885. });
  2886. svr.wait_until_ready();
  2887. Client cli(HOST, port);
  2888. cli.set_digest_auth("hello", "world");
  2889. auto res = cli.Get("/x");
  2890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2891. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2892. }
  2893. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2894. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2895. }
  2896. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2897. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2898. }
  2899. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2900. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2901. }
  2902. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2903. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2904. // when storing the values, so the header builder has to re-escape them (and
  2905. // keep algorithm a bare token); otherwise the value breaks out of its
  2906. // quoted-string and injects extra auth-params into the client's Authorization.
  2907. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2908. std::atomic<int> hits{0};
  2909. std::string authorization;
  2910. Server svr;
  2911. svr.Get("/x", [&](const Request &req, Response &res) {
  2912. if (++hits == 1) {
  2913. res.status = StatusCode::Unauthorized_401;
  2914. // On the wire the quotes embedded in the values are backslash-escaped.
  2915. res.set_header("WWW-Authenticate",
  2916. "Digest realm=\"testrealm\", "
  2917. "nonce=\"n\\\"; injected=\\\"x\", "
  2918. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2919. } else {
  2920. authorization = req.get_header_value("Authorization");
  2921. res.set_content("ok", "text/plain");
  2922. }
  2923. });
  2924. auto port = svr.bind_to_any_port(HOST);
  2925. std::thread t([&]() { svr.listen_after_bind(); });
  2926. auto se = detail::scope_exit([&] {
  2927. svr.stop();
  2928. t.join();
  2929. });
  2930. svr.wait_until_ready();
  2931. Client cli(HOST, port);
  2932. cli.set_digest_auth("hello", "world");
  2933. auto res = cli.Get("/x");
  2934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2935. EXPECT_EQ(2, hits.load());
  2936. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2937. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  2938. // inside its quoted-string rather than starting an "injected" auth-param.
  2939. EXPECT_NE(std::string::npos,
  2940. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  2941. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  2942. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  2943. }
  2944. #endif
  2945. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2946. auto host = "google.com";
  2947. auto another_host = "example.com";
  2948. auto wrong_ip = "0.0.0.0";
  2949. #ifdef CPPHTTPLIB_SSL_ENABLED
  2950. SSLClient cli(host);
  2951. #else
  2952. Client cli(host);
  2953. #endif
  2954. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2955. auto res = cli.Get("/");
  2956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2957. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2958. }
  2959. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2960. auto host = "google.com";
  2961. auto wrong_ip = "0.0.0.0";
  2962. #ifdef CPPHTTPLIB_SSL_ENABLED
  2963. SSLClient cli(host);
  2964. #else
  2965. Client cli(host);
  2966. #endif
  2967. cli.set_hostname_addr_map({{host, wrong_ip}});
  2968. auto res = cli.Get("/");
  2969. ASSERT_TRUE(!res);
  2970. EXPECT_EQ(Error::Connection, res.error());
  2971. }
  2972. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2973. // A mapped value that is not an IP literal must be resolved. "localhost"
  2974. // resolves from the hosts file, so this test needs no external DNS.
  2975. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2976. auto host = "target.invalid";
  2977. Server svr;
  2978. std::string received_host;
  2979. svr.Get("/hi", [&](const Request &req, Response &res) {
  2980. received_host = req.get_header_value("Host");
  2981. res.set_content("Hello World!", "text/plain");
  2982. });
  2983. auto port = svr.bind_to_any_port(HOST);
  2984. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2985. auto se = detail::scope_exit([&] {
  2986. svr.stop();
  2987. thread.join();
  2988. ASSERT_FALSE(svr.is_running());
  2989. });
  2990. svr.wait_until_ready();
  2991. Client cli(host, port);
  2992. cli.set_hostname_addr_map({{host, HOST}});
  2993. auto res = cli.Get("/hi");
  2994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2995. EXPECT_EQ(StatusCode::OK_200, res->status);
  2996. // The mapping only redirects the connection; the identity stays host_.
  2997. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2998. }
  2999. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3000. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3001. auto host = "target.invalid";
  3002. Server svr;
  3003. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3004. res.set_content("Hello World!", "text/plain");
  3005. });
  3006. auto port = svr.bind_to_any_port("127.0.0.1");
  3007. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3008. auto se = detail::scope_exit([&] {
  3009. svr.stop();
  3010. thread.join();
  3011. ASSERT_FALSE(svr.is_running());
  3012. });
  3013. svr.wait_until_ready();
  3014. Client cli(host, port);
  3015. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3016. auto res = cli.Get("/hi");
  3017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3018. EXPECT_EQ(StatusCode::OK_200, res->status);
  3019. }
  3020. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3021. // An empty mapped value must leave host_ as the connection target. Without
  3022. // that guard the empty value would become the host argument, getaddrinfo
  3023. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3024. // loopback - silently connecting somewhere the caller never asked for.
  3025. // The server listens on loopback, so such a fallback would succeed and is
  3026. // therefore observable as a failure of this test.
  3027. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3028. Server svr;
  3029. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3030. res.set_content("Hello World!", "text/plain");
  3031. });
  3032. auto port = svr.bind_to_any_port(HOST);
  3033. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3034. auto se = detail::scope_exit([&] {
  3035. svr.stop();
  3036. thread.join();
  3037. ASSERT_FALSE(svr.is_running());
  3038. });
  3039. svr.wait_until_ready();
  3040. Client cli(blackhole, port);
  3041. cli.set_hostname_addr_map({{blackhole, ""}});
  3042. cli.set_connection_timeout(1);
  3043. auto res = cli.Get("/hi");
  3044. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3045. }
  3046. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3047. auto host = "httpbingo.org";
  3048. auto path = std::string{"/absolute-redirect/3"};
  3049. #ifdef CPPHTTPLIB_SSL_ENABLED
  3050. SSLClient cli(host);
  3051. #else
  3052. Client cli(host);
  3053. #endif
  3054. cli.set_follow_location(true);
  3055. auto res = cli.Get(path);
  3056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3057. EXPECT_EQ(StatusCode::OK_200, res->status);
  3058. }
  3059. TEST(RedirectTest, Redirect_Online) {
  3060. auto host = "httpbingo.org";
  3061. auto path = std::string{"/redirect/3"};
  3062. #ifdef CPPHTTPLIB_SSL_ENABLED
  3063. SSLClient cli(host);
  3064. #else
  3065. Client cli(host);
  3066. #endif
  3067. cli.set_follow_location(true);
  3068. auto res = cli.Get(path);
  3069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3070. EXPECT_EQ(StatusCode::OK_200, res->status);
  3071. }
  3072. TEST(RelativeRedirectTest, Redirect_Online) {
  3073. auto host = "httpbingo.org";
  3074. auto path = std::string{"/relative-redirect/3"};
  3075. #ifdef CPPHTTPLIB_SSL_ENABLED
  3076. SSLClient cli(host);
  3077. #else
  3078. Client cli(host);
  3079. #endif
  3080. cli.set_follow_location(true);
  3081. auto res = cli.Get(path);
  3082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3083. EXPECT_EQ(StatusCode::OK_200, res->status);
  3084. }
  3085. TEST(TooManyRedirectTest, Redirect_Online) {
  3086. auto host = "httpbingo.org";
  3087. auto path = std::string{"/redirect/21"};
  3088. #ifdef CPPHTTPLIB_SSL_ENABLED
  3089. SSLClient cli(host);
  3090. #else
  3091. Client cli(host);
  3092. #endif
  3093. cli.set_follow_location(true);
  3094. auto res = cli.Get(path);
  3095. ASSERT_TRUE(!res);
  3096. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3097. }
  3098. #ifdef CPPHTTPLIB_SSL_ENABLED
  3099. TEST(YahooRedirectTest, Redirect_Online) {
  3100. Client cli("yahoo.com");
  3101. auto res = cli.Get("/");
  3102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3103. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3104. cli.set_follow_location(true);
  3105. res = cli.Get("/");
  3106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3107. EXPECT_EQ(StatusCode::OK_200, res->status);
  3108. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3109. }
  3110. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3111. #define REDIR_HOST "httpbingo.org"
  3112. #define REDIR_PATH "/redirect-to"
  3113. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3114. SSLClient cli(REDIR_HOST);
  3115. cli.set_follow_location(true);
  3116. auto res =
  3117. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3119. EXPECT_EQ(StatusCode::OK_200, res->status);
  3120. }
  3121. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3122. SSLClient cli(REDIR_HOST);
  3123. cli.set_follow_location(true);
  3124. Params params;
  3125. params.emplace("url", "http://example.com");
  3126. params.emplace("status_code", "302");
  3127. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3129. EXPECT_EQ(StatusCode::OK_200, res->status);
  3130. }
  3131. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3132. SSLClient cli(REDIR_HOST);
  3133. cli.set_follow_location(true);
  3134. Params params;
  3135. params.emplace("url", "http://example.com");
  3136. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3138. EXPECT_EQ(StatusCode::OK_200, res->status);
  3139. }
  3140. TEST(UrlWithSpace, Redirect_Online) {
  3141. SSLClient cli("edge.forgecdn.net");
  3142. cli.set_follow_location(true);
  3143. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3145. EXPECT_EQ(StatusCode::OK_200, res->status);
  3146. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3147. }
  3148. #endif
  3149. #if !defined(_WIN32) && !defined(_WIN64)
  3150. TEST(ReceiveSignals, Signal) {
  3151. auto setupSignalHandlers = []() {
  3152. struct sigaction act;
  3153. sigemptyset(&act.sa_mask);
  3154. act.sa_flags = SA_SIGINFO;
  3155. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3156. switch (sig) {
  3157. case SIGINT:
  3158. default: break;
  3159. }
  3160. };
  3161. ::sigaction(SIGINT, &act, nullptr);
  3162. };
  3163. Server svr;
  3164. int port = 0;
  3165. auto thread = std::thread([&]() {
  3166. setupSignalHandlers();
  3167. port = svr.bind_to_any_port(HOST);
  3168. svr.listen_after_bind();
  3169. });
  3170. auto se = detail::scope_exit([&] {
  3171. svr.stop();
  3172. thread.join();
  3173. ASSERT_FALSE(svr.is_running());
  3174. });
  3175. svr.wait_until_ready();
  3176. ASSERT_TRUE(svr.is_running());
  3177. pthread_kill(thread.native_handle(), SIGINT);
  3178. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3179. ASSERT_TRUE(svr.is_running());
  3180. }
  3181. #endif
  3182. TEST(RedirectToDifferentPort, Redirect) {
  3183. Server svr1;
  3184. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3185. res.set_content("Hello World!", "text/plain");
  3186. });
  3187. int svr1_port = 0;
  3188. auto thread1 = std::thread([&]() {
  3189. svr1_port = svr1.bind_to_any_port(HOST);
  3190. svr1.listen_after_bind();
  3191. });
  3192. Server svr2;
  3193. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3194. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3195. });
  3196. int svr2_port = 0;
  3197. auto thread2 = std::thread([&]() {
  3198. svr2_port = svr2.bind_to_any_port(HOST);
  3199. svr2.listen_after_bind();
  3200. });
  3201. auto se = detail::scope_exit([&] {
  3202. svr2.stop();
  3203. thread2.join();
  3204. svr1.stop();
  3205. thread1.join();
  3206. ASSERT_FALSE(svr2.is_running());
  3207. ASSERT_FALSE(svr1.is_running());
  3208. });
  3209. svr1.wait_until_ready();
  3210. svr2.wait_until_ready();
  3211. Client cli("localhost", svr2_port);
  3212. cli.set_follow_location(true);
  3213. auto res = cli.Get("/2");
  3214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3215. EXPECT_EQ(StatusCode::OK_200, res->status);
  3216. EXPECT_EQ("Hello World!", res->body);
  3217. }
  3218. // GET /redir on one server redirects to /target on another port, so the
  3219. // client follows it with a new client.
  3220. static Result
  3221. GetThroughRedirectToDifferentPort(Server::Handler target,
  3222. const std::function<void(Client &)> &setup,
  3223. const Headers &headers = Headers()) {
  3224. Server target_svr;
  3225. target_svr.Get("/target", target);
  3226. int target_port = 0;
  3227. auto target_thread = std::thread([&]() {
  3228. target_port = target_svr.bind_to_any_port(HOST);
  3229. target_svr.listen_after_bind();
  3230. });
  3231. Server origin_svr;
  3232. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3233. res.set_redirect(
  3234. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3235. });
  3236. int origin_port = 0;
  3237. auto origin_thread = std::thread([&]() {
  3238. origin_port = origin_svr.bind_to_any_port(HOST);
  3239. origin_svr.listen_after_bind();
  3240. });
  3241. auto se = detail::scope_exit([&] {
  3242. origin_svr.stop();
  3243. origin_thread.join();
  3244. target_svr.stop();
  3245. target_thread.join();
  3246. });
  3247. target_svr.wait_until_ready();
  3248. origin_svr.wait_until_ready();
  3249. Client cli("localhost", origin_port);
  3250. cli.set_follow_location(true);
  3251. setup(cli);
  3252. return cli.Get("/redir", headers);
  3253. }
  3254. static void
  3255. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3256. std::string captured_authorization;
  3257. auto result = GetThroughRedirectToDifferentPort(
  3258. [&](const Request &req, Response &res) {
  3259. captured_authorization = req.get_header_value("Authorization");
  3260. res.set_content("OK", "text/plain");
  3261. },
  3262. set_auth);
  3263. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3264. EXPECT_EQ(StatusCode::OK_200, result->status);
  3265. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3266. EXPECT_TRUE(captured_authorization.empty());
  3267. }
  3268. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3269. TestDoNotForwardCredentialsOnRedirect(
  3270. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3271. }
  3272. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3273. TestDoNotForwardCredentialsOnRedirect(
  3274. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3275. }
  3276. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3277. std::string captured_cookie;
  3278. auto result = GetThroughRedirectToDifferentPort(
  3279. [&](const Request &req, Response &res) {
  3280. captured_cookie = req.get_header_value("Cookie");
  3281. res.set_content("OK", "text/plain");
  3282. },
  3283. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3284. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3285. EXPECT_EQ(StatusCode::OK_200, result->status);
  3286. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3287. EXPECT_TRUE(captured_cookie.empty());
  3288. }
  3289. TEST(RedirectToSamePort, ForwardCookie) {
  3290. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3291. // header so that ordinary session flows keep working.
  3292. Server svr;
  3293. std::string captured_cookie;
  3294. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3295. res.set_redirect("/target", 302);
  3296. });
  3297. svr.Get("/target", [&](const Request &req, Response &res) {
  3298. captured_cookie = req.get_header_value("Cookie");
  3299. res.set_content("OK", "text/plain");
  3300. });
  3301. auto port = svr.bind_to_any_port(HOST);
  3302. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3303. auto se = detail::scope_exit([&] {
  3304. svr.stop();
  3305. thread.join();
  3306. ASSERT_FALSE(svr.is_running());
  3307. });
  3308. svr.wait_until_ready();
  3309. Client cli(HOST, port);
  3310. cli.set_follow_location(true);
  3311. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3312. auto res = cli.Get("/redir", headers);
  3313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3314. EXPECT_EQ(StatusCode::OK_200, res->status);
  3315. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3316. }
  3317. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3318. std::string authorization;
  3319. std::string trace_id;
  3320. auto result = GetThroughRedirectToDifferentPort(
  3321. [&](const Request &req, Response &res) {
  3322. authorization = req.get_header_value("Authorization");
  3323. trace_id = req.get_header_value("X-Trace-Id");
  3324. res.set_content("OK", "text/plain");
  3325. },
  3326. [](Client &cli) {
  3327. cli.set_default_headers(
  3328. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3329. });
  3330. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3331. EXPECT_EQ(StatusCode::OK_200, result->status);
  3332. // Like a header given with the request, a default one goes along unless it
  3333. // carries credentials (RFC 9110 15.4).
  3334. EXPECT_TRUE(authorization.empty());
  3335. EXPECT_EQ("42", trace_id);
  3336. }
  3337. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3338. auto result = GetThroughRedirectToDifferentPort(
  3339. [](const Request &, Response &res) {
  3340. res.set_content(std::string(2048, 'x'), "text/plain");
  3341. },
  3342. [](Client &cli) { cli.set_payload_max_length(1024); });
  3343. EXPECT_FALSE(result);
  3344. }
  3345. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3346. auto result = GetThroughRedirectToDifferentPort(
  3347. [](const Request &req, Response &res) {
  3348. // Answer after a second, or once the client gives up.
  3349. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3350. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3351. }
  3352. res.set_content("late", "text/plain");
  3353. },
  3354. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3355. ASSERT_FALSE(result);
  3356. EXPECT_EQ(Error::Read, result.error());
  3357. }
  3358. #ifdef CPPHTTPLIB_SSL_ENABLED
  3359. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3360. auto result = GetThroughRedirectToDifferentPort(
  3361. [](const Request &, Response &res) {
  3362. res.status = StatusCode::Unauthorized_401;
  3363. res.set_header("WWW-Authenticate",
  3364. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3365. },
  3366. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3367. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3368. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3369. }
  3370. #endif
  3371. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3372. Server svr;
  3373. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3374. // Port number that overflows int — should not crash
  3375. res.set_redirect("http://localhost:99999999999999999999/target");
  3376. });
  3377. auto port = svr.bind_to_any_port(HOST);
  3378. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3379. auto se = detail::scope_exit([&] {
  3380. svr.stop();
  3381. thread.join();
  3382. ASSERT_FALSE(svr.is_running());
  3383. });
  3384. svr.wait_until_ready();
  3385. Client cli(HOST, port);
  3386. cli.set_follow_location(true);
  3387. auto res = cli.Get("/redir");
  3388. // Should fail gracefully, not crash (no valid response due to bad port)
  3389. EXPECT_FALSE(res);
  3390. }
  3391. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3392. Server svr;
  3393. auto port = svr.bind_to_any_port(HOST);
  3394. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3395. // The server's own port followed by junk must not be followed
  3396. res.set_redirect("http://" + std::string(HOST) + ":" +
  3397. std::to_string(port) + "junk/target");
  3398. });
  3399. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3400. res.set_content("target", "text/plain");
  3401. });
  3402. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3403. auto se = detail::scope_exit([&] {
  3404. svr.stop();
  3405. thread.join();
  3406. ASSERT_FALSE(svr.is_running());
  3407. });
  3408. svr.wait_until_ready();
  3409. Client cli(HOST, port);
  3410. cli.set_follow_location(true);
  3411. auto res = cli.Get("/redir");
  3412. EXPECT_FALSE(res);
  3413. }
  3414. TEST(RedirectFromPageWithContent, Redirect) {
  3415. Server svr;
  3416. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3417. res.set_content("___", "text/plain");
  3418. res.set_redirect("/2");
  3419. });
  3420. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3421. res.set_content("Hello World!", "text/plain");
  3422. });
  3423. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3424. auto se = detail::scope_exit([&] {
  3425. svr.stop();
  3426. th.join();
  3427. ASSERT_FALSE(svr.is_running());
  3428. });
  3429. svr.wait_until_ready();
  3430. {
  3431. Client cli("localhost", PORT);
  3432. cli.set_follow_location(true);
  3433. std::string body;
  3434. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3435. body.append(data, data_length);
  3436. return true;
  3437. });
  3438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3439. EXPECT_EQ(StatusCode::OK_200, res->status);
  3440. EXPECT_EQ("Hello World!", body);
  3441. }
  3442. {
  3443. Client cli("localhost", PORT);
  3444. std::string body;
  3445. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3446. body.append(data, data_length);
  3447. return true;
  3448. });
  3449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3450. EXPECT_EQ(StatusCode::Found_302, res->status);
  3451. EXPECT_EQ("___", body);
  3452. }
  3453. }
  3454. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3455. Server svr;
  3456. auto port_str = std::to_string(PORT);
  3457. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3458. auto expected_host = "[::1]:" + port_str;
  3459. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3460. res.set_content("___", "text/plain");
  3461. // res.set_redirect("/2");
  3462. res.set_redirect(redirect_url);
  3463. });
  3464. svr.Get("/2", [&](const Request &req, Response &res) {
  3465. auto host_header = req.headers.find("Host");
  3466. ASSERT_TRUE(host_header != req.headers.end());
  3467. EXPECT_EQ(expected_host, host_header->second);
  3468. res.set_content("Hello World!", "text/plain");
  3469. });
  3470. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3471. auto se = detail::scope_exit([&] {
  3472. svr.stop();
  3473. th.join();
  3474. ASSERT_FALSE(svr.is_running());
  3475. });
  3476. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3477. // actually starts anything, so the condition !svr.is_running() will
  3478. // always remain true, and the loop never stops.
  3479. // This basically counts how many milliseconds have passed since the
  3480. // call to svr.listen(), and if after 5 seconds nothing started yet
  3481. // aborts the test.
  3482. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3483. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3484. ASSERT_LT(milliseconds, 5000U);
  3485. }
  3486. {
  3487. Client cli("::1", PORT);
  3488. cli.set_follow_location(true);
  3489. std::string body;
  3490. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3491. body.append(data, data_length);
  3492. return true;
  3493. });
  3494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3495. EXPECT_EQ(StatusCode::OK_200, res->status);
  3496. EXPECT_EQ("Hello World!", body);
  3497. }
  3498. {
  3499. Client cli("::1", PORT);
  3500. std::string body;
  3501. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3502. body.append(data, data_length);
  3503. return true;
  3504. });
  3505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3506. EXPECT_EQ(StatusCode::Found_302, res->status);
  3507. EXPECT_EQ("___", body);
  3508. }
  3509. }
  3510. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3511. Server svr;
  3512. svr.Get("/foo", [](const Request &req, Response &res) {
  3513. auto a = req.params.find("a");
  3514. if (a != req.params.end()) {
  3515. res.set_content((*a).second, "text/plain");
  3516. res.status = StatusCode::OK_200;
  3517. } else {
  3518. res.status = StatusCode::BadRequest_400;
  3519. }
  3520. });
  3521. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3522. auto se = detail::scope_exit([&] {
  3523. svr.stop();
  3524. thread.join();
  3525. ASSERT_FALSE(svr.is_running());
  3526. });
  3527. svr.wait_until_ready();
  3528. {
  3529. Client cli(HOST, PORT);
  3530. cli.set_path_encode(false);
  3531. auto res = cli.Get("/foo?a=explicitly+encoded");
  3532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3533. EXPECT_EQ(StatusCode::OK_200, res->status);
  3534. // This expects it back with a space, as the `+` won't have been
  3535. // url-encoded, and server-side the params get decoded turning `+`
  3536. // into spaces.
  3537. EXPECT_EQ("explicitly encoded", res->body);
  3538. }
  3539. }
  3540. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3541. // When path encoding is disabled the client must transmit the supplied
  3542. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3543. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3544. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3545. // than a space (0x20). Assert on the raw wire target to catch this.
  3546. Server svr;
  3547. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3548. svr.Get("/foo", [&](const Request &req, Response &res) {
  3549. EXPECT_EQ(expected_target, req.target);
  3550. res.status = StatusCode::OK_200;
  3551. });
  3552. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3553. auto se = detail::scope_exit([&] {
  3554. svr.stop();
  3555. thread.join();
  3556. ASSERT_FALSE(svr.is_running());
  3557. });
  3558. svr.wait_until_ready();
  3559. {
  3560. Client cli(HOST, PORT);
  3561. cli.set_path_encode(false);
  3562. auto res = cli.Get(expected_target.c_str());
  3563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3564. EXPECT_EQ(StatusCode::OK_200, res->status);
  3565. }
  3566. }
  3567. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3568. // `open_stream()` used to skip the path encoding that the buffered send
  3569. // path applies, so the same `path` produced different bytes in the request
  3570. // line depending on which API was used. Assert the two agree.
  3571. Server svr;
  3572. std::string target;
  3573. svr.Get(".*", [&](const Request &req, Response &res) {
  3574. target = req.target;
  3575. res.status = StatusCode::OK_200;
  3576. });
  3577. auto port = svr.bind_to_any_port(HOST);
  3578. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3579. auto se = detail::scope_exit([&] {
  3580. svr.stop();
  3581. thread.join();
  3582. ASSERT_FALSE(svr.is_running());
  3583. });
  3584. svr.wait_until_ready();
  3585. struct {
  3586. const char *path;
  3587. const char *expected;
  3588. } cases[] = {
  3589. {"/a b?x=1", "/a%20b?x=1"},
  3590. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3591. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3592. };
  3593. for (const auto &c : cases) {
  3594. Client cli(HOST, port);
  3595. target.clear();
  3596. auto res = cli.Get(c.path);
  3597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3598. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3599. auto buffered_target = target;
  3600. target.clear();
  3601. auto handle = cli.open_stream("GET", c.path);
  3602. EXPECT_TRUE(handle.is_valid())
  3603. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3604. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3605. }
  3606. }
  3607. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3608. // The `set_path_encode(false)` contract — transmit the supplied target
  3609. // verbatim — must hold for the streaming API too.
  3610. Server svr;
  3611. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3612. std::string target;
  3613. svr.Get("/foo", [&](const Request &req, Response &res) {
  3614. target = req.target;
  3615. res.status = StatusCode::OK_200;
  3616. });
  3617. auto port = svr.bind_to_any_port(HOST);
  3618. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3619. auto se = detail::scope_exit([&] {
  3620. svr.stop();
  3621. thread.join();
  3622. ASSERT_FALSE(svr.is_running());
  3623. });
  3624. svr.wait_until_ready();
  3625. {
  3626. Client cli(HOST, port);
  3627. cli.set_path_encode(false);
  3628. auto handle = cli.open_stream("GET", expected_target);
  3629. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3630. EXPECT_EQ(expected_target, target);
  3631. }
  3632. }
  3633. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3634. // With path encoding enabled a CR/LF in the target is percent-encoded
  3635. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3636. // write_request_line still backstops `set_path_encode(false)`, which is
  3637. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3638. Server svr;
  3639. // Captured before routing: the decoded path contains a newline, which a
  3640. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3641. std::string target;
  3642. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3643. target = req.target;
  3644. res.status = StatusCode::OK_200;
  3645. return Server::HandlerResponse::Handled;
  3646. });
  3647. auto port = svr.bind_to_any_port(HOST);
  3648. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3649. auto se = detail::scope_exit([&] {
  3650. svr.stop();
  3651. thread.join();
  3652. ASSERT_FALSE(svr.is_running());
  3653. });
  3654. svr.wait_until_ready();
  3655. {
  3656. Client cli(HOST, port);
  3657. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3658. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3659. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3660. }
  3661. }
  3662. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3663. // Every control character is percent-encoded, not just CR/LF, so the target
  3664. // passes the request-target check in write_request_line.
  3665. Server svr;
  3666. std::string target;
  3667. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3668. target = req.target;
  3669. res.status = StatusCode::OK_200;
  3670. return Server::HandlerResponse::Handled;
  3671. });
  3672. auto port = svr.bind_to_any_port(HOST);
  3673. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3674. auto se = detail::scope_exit([&] {
  3675. svr.stop();
  3676. thread.join();
  3677. ASSERT_FALSE(svr.is_running());
  3678. });
  3679. svr.wait_until_ready();
  3680. {
  3681. Client cli(HOST, port);
  3682. auto res = cli.Get("/a\tb\x1b\x7f");
  3683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3684. EXPECT_EQ("/a%09b%1B%7F", target);
  3685. }
  3686. }
  3687. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3688. // Nothing may reach the wire: a raw CR/LF target would split the request
  3689. // line and inject headers.
  3690. Server svr;
  3691. // Pre-routing so that "not called" means nothing reached the server at all,
  3692. // rather than merely failing to match a handler pattern.
  3693. auto handler_called = false;
  3694. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3695. handler_called = true;
  3696. res.status = StatusCode::OK_200;
  3697. return Server::HandlerResponse::Handled;
  3698. });
  3699. auto port = svr.bind_to_any_port(HOST);
  3700. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3701. auto se = detail::scope_exit([&] {
  3702. svr.stop();
  3703. thread.join();
  3704. ASSERT_FALSE(svr.is_running());
  3705. });
  3706. svr.wait_until_ready();
  3707. {
  3708. Client cli(HOST, port);
  3709. cli.set_path_encode(false);
  3710. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3711. EXPECT_FALSE(handle.is_valid());
  3712. EXPECT_EQ(Error::Write, handle.error);
  3713. EXPECT_FALSE(handler_called);
  3714. }
  3715. }
  3716. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3717. // Which of the two branches runs is decided by whether the query component
  3718. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3719. // an empty query and must still fall back to building one from
  3720. // `req.params`, while a non-empty query must win over `req.params`.
  3721. Server svr;
  3722. std::string target;
  3723. svr.Get("/foo", [&](const Request &req, Response &res) {
  3724. target = req.target;
  3725. res.status = StatusCode::OK_200;
  3726. });
  3727. auto port = svr.bind_to_any_port(HOST);
  3728. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3729. auto se = detail::scope_exit([&] {
  3730. svr.stop();
  3731. thread.join();
  3732. ASSERT_FALSE(svr.is_running());
  3733. });
  3734. svr.wait_until_ready();
  3735. {
  3736. // Trailing `?` -> empty query component -> `req.params` is used.
  3737. Client cli(HOST, port);
  3738. Request req;
  3739. req.method = "GET";
  3740. req.path = "/foo?";
  3741. req.params.emplace("a", "1");
  3742. target.clear();
  3743. auto res = cli.send(req);
  3744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3745. EXPECT_EQ("/foo?a=1", target);
  3746. }
  3747. {
  3748. // Non-empty query in `req.path` -> `req.params` is not appended.
  3749. Client cli(HOST, port);
  3750. Request req;
  3751. req.method = "GET";
  3752. req.path = "/foo?b=2";
  3753. req.params.emplace("a", "1");
  3754. target.clear();
  3755. auto res = cli.send(req);
  3756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3757. EXPECT_EQ("/foo?b=2", target);
  3758. }
  3759. }
  3760. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3761. Server svr;
  3762. svr.Get("/", [](const Request &req, Response &) {
  3763. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3764. });
  3765. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3766. auto se = detail::scope_exit([&] {
  3767. svr.stop();
  3768. thread.join();
  3769. ASSERT_FALSE(svr.is_running());
  3770. });
  3771. svr.wait_until_ready();
  3772. {
  3773. Client cli(HOST, PORT);
  3774. cli.set_path_encode(false);
  3775. auto res = cli.Get("/?something=%0A");
  3776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3777. EXPECT_EQ(StatusCode::OK_200, res->status);
  3778. }
  3779. }
  3780. TEST(BindServerTest, BindDualStack) {
  3781. Server svr;
  3782. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3783. res.set_content("Hello World!", "text/plain");
  3784. });
  3785. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3786. auto se = detail::scope_exit([&] {
  3787. svr.stop();
  3788. thread.join();
  3789. ASSERT_FALSE(svr.is_running());
  3790. });
  3791. svr.wait_until_ready();
  3792. {
  3793. Client cli("127.0.0.1", PORT);
  3794. auto res = cli.Get("/1");
  3795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3796. EXPECT_EQ(StatusCode::OK_200, res->status);
  3797. EXPECT_EQ("Hello World!", res->body);
  3798. }
  3799. {
  3800. Client cli("::1", PORT);
  3801. auto res = cli.Get("/1");
  3802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3803. EXPECT_EQ(StatusCode::OK_200, res->status);
  3804. EXPECT_EQ("Hello World!", res->body);
  3805. }
  3806. }
  3807. TEST(BindServerTest, BindAndListenSeparately) {
  3808. Server svr;
  3809. int port = svr.bind_to_any_port("0.0.0.0");
  3810. ASSERT_TRUE(svr.is_valid());
  3811. ASSERT_TRUE(port > 0);
  3812. svr.stop();
  3813. }
  3814. // Reports whether anything is still listening on a loopback port. A plain
  3815. // connect() is used instead of a Client request because a socket left bound by
  3816. // mistake accepts the connection into its backlog and never answers, which
  3817. // would hang the test instead of failing it.
  3818. static bool is_loopback_port_accepting(int port) {
  3819. sockaddr_in addr{};
  3820. addr.sin_family = AF_INET;
  3821. addr.sin_port = htons(static_cast<uint16_t>(port));
  3822. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3823. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3824. EXPECT_NE(sock, INVALID_SOCKET);
  3825. if (sock == INVALID_SOCKET) { return false; }
  3826. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3827. static_cast<socklen_t>(sizeof(addr)));
  3828. detail::close_socket(sock);
  3829. return ret == 0;
  3830. }
  3831. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3832. Server svr;
  3833. auto port = svr.bind_to_any_port("127.0.0.1");
  3834. ASSERT_TRUE(port > 0);
  3835. svr.stop();
  3836. // bind_to_any_port() already called listen(2), so until stop() closed the
  3837. // descriptor the port kept accepting connections into the backlog. ASSERT
  3838. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3839. // below blocks forever in the accept loop.
  3840. ASSERT_FALSE(is_loopback_port_accepting(port));
  3841. // Nothing is left to accept on, so listen_after_bind() must report failure
  3842. // instead of returning success without ever serving.
  3843. EXPECT_FALSE(svr.listen_after_bind());
  3844. // The failed listen marks the server decommissioned, so a waiter returns
  3845. // instead of spinning forever.
  3846. svr.wait_until_ready();
  3847. }
  3848. #ifdef CPPHTTPLIB_SSL_ENABLED
  3849. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3850. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3851. CLIENT_CA_CERT_DIR);
  3852. int port = svr.bind_to_any_port("0.0.0.0");
  3853. ASSERT_TRUE(svr.is_valid());
  3854. ASSERT_TRUE(port > 0);
  3855. svr.stop();
  3856. }
  3857. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3858. // or a rejected CustomRoute() registration would not stop the server binding.
  3859. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3860. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3861. CLIENT_CA_CERT_DIR);
  3862. ASSERT_TRUE(svr.is_valid());
  3863. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3864. EXPECT_FALSE(svr.is_valid());
  3865. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3866. }
  3867. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3868. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3869. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3870. int port = svr.bind_to_any_port("0.0.0.0");
  3871. ASSERT_TRUE(svr.is_valid());
  3872. ASSERT_TRUE(port > 0);
  3873. svr.stop();
  3874. }
  3875. TEST(BindServerTest, UpdateCertsPem) {
  3876. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3877. int port = svr.bind_to_any_port("0.0.0.0");
  3878. ASSERT_TRUE(svr.is_valid());
  3879. ASSERT_TRUE(port > 0);
  3880. // Read PEM files
  3881. std::string cert_pem, key_pem, ca_pem;
  3882. read_file(SERVER_CERT_FILE, cert_pem);
  3883. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3884. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3885. // Update server certificates using PEM API
  3886. ASSERT_TRUE(
  3887. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3888. ASSERT_TRUE(svr.is_valid());
  3889. svr.stop();
  3890. }
  3891. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3892. // Start server with client CA (enables client auth)
  3893. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3894. ASSERT_TRUE(svr.is_valid());
  3895. bool handler_called = false;
  3896. svr.Get("/test", [&](const Request &req, Response &res) {
  3897. handler_called = true;
  3898. // Verify client certificate is present
  3899. auto cert = req.peer_cert();
  3900. EXPECT_TRUE(static_cast<bool>(cert));
  3901. res.set_content("ok", "text/plain");
  3902. });
  3903. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3904. auto se = detail::scope_exit([&] {
  3905. svr.stop();
  3906. t.join();
  3907. ASSERT_FALSE(svr.is_running());
  3908. });
  3909. svr.wait_until_ready();
  3910. // Read PEM files
  3911. std::string cert_pem, key_pem, ca_pem;
  3912. read_file(SERVER_CERT_FILE, cert_pem);
  3913. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3914. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3915. // Update server certificates and client CA using PEM API while server running
  3916. ASSERT_TRUE(
  3917. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3918. // Connect with client certificate
  3919. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3920. cli.enable_server_certificate_verification(false);
  3921. cli.set_connection_timeout(30);
  3922. auto res = cli.Get("/test");
  3923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3924. ASSERT_EQ(StatusCode::OK_200, res->status);
  3925. ASSERT_TRUE(handler_called);
  3926. EXPECT_EQ("ok", res->body);
  3927. }
  3928. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  3929. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3930. ASSERT_TRUE(svr.is_valid());
  3931. svr.Get("/test", [](const Request &, Response &res) {
  3932. res.set_content("ok", "text/plain");
  3933. });
  3934. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3935. auto se = detail::scope_exit([&] {
  3936. svr.stop();
  3937. t.join();
  3938. ASSERT_FALSE(svr.is_running());
  3939. });
  3940. svr.wait_until_ready();
  3941. // A connection that sends no ClientHello keeps its handshake in progress,
  3942. // once the server has had a moment to start it.
  3943. auto error = Error::Success;
  3944. auto sock = detail::create_client_socket(
  3945. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  3946. /*connection_timeout_sec=*/5, 0,
  3947. /*read_timeout_sec=*/5, 0,
  3948. /*write_timeout_sec=*/5, 0, std::string(), error);
  3949. ASSERT_NE(INVALID_SOCKET, sock);
  3950. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3951. std::string cert_pem, key_pem;
  3952. read_file(SERVER_CERT_FILE, cert_pem);
  3953. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3954. auto update = std::async(std::launch::async, [&]() {
  3955. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  3956. });
  3957. EXPECT_EQ(std::future_status::timeout,
  3958. update.wait_for(std::chrono::milliseconds(200)));
  3959. detail::close_socket(sock);
  3960. EXPECT_TRUE(update.get());
  3961. SSLClient cli(HOST, PORT);
  3962. cli.enable_server_certificate_verification(false);
  3963. auto res = cli.Get("/test");
  3964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3965. EXPECT_EQ(StatusCode::OK_200, res->status);
  3966. }
  3967. #endif
  3968. TEST(ErrorHandlerTest, ContentLength) {
  3969. Server svr;
  3970. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3971. res.status = StatusCode::OK_200;
  3972. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3973. "text/html"); // <= Content-Length still 13
  3974. });
  3975. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3976. res.set_content("Hello World!\n", "text/plain");
  3977. res.status = 524;
  3978. });
  3979. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3980. auto se = detail::scope_exit([&] {
  3981. svr.stop();
  3982. thread.join();
  3983. ASSERT_FALSE(svr.is_running());
  3984. });
  3985. svr.wait_until_ready();
  3986. {
  3987. Client cli(HOST, PORT);
  3988. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3990. EXPECT_EQ(StatusCode::OK_200, res->status);
  3991. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3992. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3993. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3994. }
  3995. }
  3996. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3997. TEST(ExceptionTest, WithoutExceptionHandler) {
  3998. Server svr;
  3999. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4000. throw std::runtime_error("exception...");
  4001. });
  4002. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4003. throw std::runtime_error("exception\r\n...");
  4004. });
  4005. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4006. auto se = detail::scope_exit([&] {
  4007. svr.stop();
  4008. listen_thread.join();
  4009. ASSERT_FALSE(svr.is_running());
  4010. });
  4011. svr.wait_until_ready();
  4012. Client cli("localhost", PORT);
  4013. {
  4014. auto res = cli.Get("/exception");
  4015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4016. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4017. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4018. }
  4019. {
  4020. auto res = cli.Get("/unknown");
  4021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4022. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4023. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4024. }
  4025. }
  4026. TEST(ExceptionTest, WithExceptionHandler) {
  4027. Server svr;
  4028. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4029. std::exception_ptr ep) {
  4030. EXPECT_FALSE(ep == nullptr);
  4031. try {
  4032. std::rethrow_exception(ep);
  4033. } catch (std::exception &e) {
  4034. EXPECT_EQ("abc", std::string(e.what()));
  4035. } catch (...) {}
  4036. res.status = StatusCode::InternalServerError_500;
  4037. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4038. "text/html"); // <= Content-Length still 13 at this point
  4039. });
  4040. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4041. res.set_content("Hello World!\n", "text/plain");
  4042. throw std::runtime_error("abc");
  4043. });
  4044. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4045. auto se = detail::scope_exit([&] {
  4046. svr.stop();
  4047. thread.join();
  4048. ASSERT_FALSE(svr.is_running());
  4049. });
  4050. svr.wait_until_ready();
  4051. for (size_t i = 0; i < 10; i++) {
  4052. Client cli(HOST, PORT);
  4053. for (size_t j = 0; j < 100; j++) {
  4054. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4056. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4057. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4058. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4059. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4060. }
  4061. cli.set_keep_alive(true);
  4062. for (size_t j = 0; j < 100; j++) {
  4063. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4065. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4066. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4067. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4068. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4069. }
  4070. }
  4071. }
  4072. TEST(ExceptionTest, AndErrorHandler) {
  4073. Server svr;
  4074. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4075. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4076. });
  4077. svr.set_exception_handler(
  4078. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4079. EXPECT_FALSE(ep == nullptr);
  4080. try {
  4081. std::rethrow_exception(ep);
  4082. } catch (std::exception &e) {
  4083. res.set_content(e.what(), "text/html");
  4084. } catch (...) {}
  4085. res.status = StatusCode::InternalServerError_500;
  4086. });
  4087. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4088. throw std::runtime_error("EXCEPTION");
  4089. });
  4090. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4091. res.set_content("ERROR", "text/html");
  4092. res.status = StatusCode::InternalServerError_500;
  4093. });
  4094. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4095. auto se = detail::scope_exit([&] {
  4096. svr.stop();
  4097. thread.join();
  4098. ASSERT_FALSE(svr.is_running());
  4099. });
  4100. svr.wait_until_ready();
  4101. Client cli(HOST, PORT);
  4102. {
  4103. auto res = cli.Get("/exception");
  4104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4105. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4106. EXPECT_EQ("EXCEPTION", res->body);
  4107. }
  4108. {
  4109. auto res = cli.Get("/error");
  4110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4111. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4112. EXPECT_EQ("ERROR", res->body);
  4113. }
  4114. {
  4115. auto res = cli.Get("/invalid");
  4116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4117. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4118. EXPECT_EQ("NOT_FOUND", res->body);
  4119. }
  4120. }
  4121. #endif
  4122. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4123. // process_request() wraps only routing() in a try/catch, so an exception from
  4124. // any other user callback used to unwind into the task queue - which does not
  4125. // catch - and terminate the process. Each test below runs the server on a
  4126. // single worker thread: a guard that catches the exception but still loses the
  4127. // thread would otherwise be hidden by a spare worker serving the follow-up
  4128. // request. Note that a regression here aborts the whole test binary rather
  4129. // than failing one test.
  4130. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4131. Server svr;
  4132. svr.new_task_queue = [] { return new ThreadPool(1); };
  4133. std::atomic<int> reported{0};
  4134. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4135. if (err == Error::UserCallbackException) { reported++; }
  4136. });
  4137. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4138. res.set_content_provider(
  4139. 1024, "text/plain",
  4140. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4141. sink.write("hello", 5);
  4142. throw std::runtime_error("from the content provider");
  4143. });
  4144. });
  4145. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4146. res.set_content("ok", "text/plain");
  4147. });
  4148. auto port = svr.bind_to_any_port(HOST);
  4149. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4150. auto se = detail::scope_exit([&] {
  4151. svr.stop();
  4152. listen_thread.join();
  4153. ASSERT_FALSE(svr.is_running());
  4154. });
  4155. svr.wait_until_ready();
  4156. {
  4157. Client cli(HOST, port);
  4158. cli.set_read_timeout(5, 0);
  4159. EXPECT_FALSE(cli.Get("/throw"));
  4160. }
  4161. EXPECT_TRUE(svr.is_running());
  4162. EXPECT_EQ(1, reported.load());
  4163. // A request on a fresh connection is still served.
  4164. {
  4165. Client cli(HOST, port);
  4166. auto res = cli.Get("/ok");
  4167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4168. EXPECT_EQ(StatusCode::OK_200, res->status);
  4169. EXPECT_EQ("ok", res->body);
  4170. }
  4171. }
  4172. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4173. Server svr;
  4174. svr.new_task_queue = [] { return new ThreadPool(1); };
  4175. std::atomic<bool> should_throw{true};
  4176. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4177. res.set_content("hi", "text/plain");
  4178. });
  4179. svr.set_post_routing_handler(
  4180. [&](const Request & /*req*/, Response & /*res*/) {
  4181. if (should_throw) {
  4182. throw std::runtime_error("from the post-routing handler");
  4183. }
  4184. });
  4185. auto port = svr.bind_to_any_port(HOST);
  4186. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4187. auto se = detail::scope_exit([&] {
  4188. svr.stop();
  4189. listen_thread.join();
  4190. ASSERT_FALSE(svr.is_running());
  4191. });
  4192. svr.wait_until_ready();
  4193. {
  4194. Client cli(HOST, port);
  4195. cli.set_read_timeout(5, 0);
  4196. EXPECT_FALSE(cli.Get("/hi"));
  4197. }
  4198. EXPECT_TRUE(svr.is_running());
  4199. should_throw = false;
  4200. {
  4201. Client cli(HOST, port);
  4202. auto res = cli.Get("/hi");
  4203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4204. EXPECT_EQ(StatusCode::OK_200, res->status);
  4205. EXPECT_EQ("hi", res->body);
  4206. }
  4207. }
  4208. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4209. // The guard reports the caught exception through the error logger, which is
  4210. // a user callback too. A logger that throws has to be contained as well, or
  4211. // the process would terminate from inside the catch.
  4212. Server svr;
  4213. svr.new_task_queue = [] { return new ThreadPool(1); };
  4214. std::atomic<int> reported{0};
  4215. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4216. if (err == Error::UserCallbackException) {
  4217. reported++;
  4218. throw std::runtime_error("from the error logger");
  4219. }
  4220. });
  4221. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4222. res.set_content_provider(
  4223. 1024, "text/plain",
  4224. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4225. sink.write("hello", 5);
  4226. throw std::runtime_error("from the content provider");
  4227. });
  4228. });
  4229. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4230. res.set_content("ok", "text/plain");
  4231. });
  4232. auto port = svr.bind_to_any_port(HOST);
  4233. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4234. auto se = detail::scope_exit([&] {
  4235. svr.stop();
  4236. listen_thread.join();
  4237. ASSERT_FALSE(svr.is_running());
  4238. });
  4239. svr.wait_until_ready();
  4240. {
  4241. Client cli(HOST, port);
  4242. cli.set_read_timeout(5, 0);
  4243. EXPECT_FALSE(cli.Get("/throw"));
  4244. }
  4245. EXPECT_TRUE(svr.is_running());
  4246. EXPECT_EQ(1, reported.load());
  4247. {
  4248. Client cli(HOST, port);
  4249. auto res = cli.Get("/ok");
  4250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4251. EXPECT_EQ(StatusCode::OK_200, res->status);
  4252. EXPECT_EQ("ok", res->body);
  4253. }
  4254. }
  4255. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4256. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4257. // so the exception unwinds through the ws::WebSocket object on its way to
  4258. // the guard. None of the HTTP cases above cross that.
  4259. Server svr;
  4260. svr.new_task_queue = [] { return new ThreadPool(1); };
  4261. std::atomic<int> reported{0};
  4262. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4263. if (err == Error::UserCallbackException) { reported++; }
  4264. });
  4265. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4266. throw std::runtime_error("from the WebSocket handler");
  4267. });
  4268. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4269. res.set_content("ok", "text/plain");
  4270. });
  4271. auto port = svr.bind_to_any_port(HOST);
  4272. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4273. auto se = detail::scope_exit([&] {
  4274. svr.stop();
  4275. listen_thread.join();
  4276. ASSERT_FALSE(svr.is_running());
  4277. });
  4278. svr.wait_until_ready();
  4279. {
  4280. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4281. "/ws");
  4282. auto res = client.connect();
  4283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4284. // The server dropped the connection instead of dying.
  4285. std::string msg;
  4286. EXPECT_FALSE(client.read(msg));
  4287. client.close();
  4288. }
  4289. EXPECT_TRUE(svr.is_running());
  4290. EXPECT_EQ(1, reported.load());
  4291. {
  4292. Client cli(HOST, port);
  4293. auto res = cli.Get("/ok");
  4294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4295. EXPECT_EQ(StatusCode::OK_200, res->status);
  4296. EXPECT_EQ("ok", res->body);
  4297. }
  4298. }
  4299. #ifdef CPPHTTPLIB_SSL_ENABLED
  4300. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4301. // SSLServer::process_and_close_socket() is a separate overload with its own
  4302. // guard, so it is exercised on its own.
  4303. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4304. ASSERT_TRUE(svr.is_valid());
  4305. svr.new_task_queue = [] { return new ThreadPool(1); };
  4306. std::atomic<int> reported{0};
  4307. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4308. if (err == Error::UserCallbackException) { reported++; }
  4309. });
  4310. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4311. res.set_content_provider(
  4312. 1024, "text/plain",
  4313. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4314. sink.write("hello", 5);
  4315. throw std::runtime_error("from the content provider");
  4316. });
  4317. });
  4318. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4319. res.set_content("ok", "text/plain");
  4320. });
  4321. auto port = svr.bind_to_any_port(HOST);
  4322. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4323. auto se = detail::scope_exit([&] {
  4324. svr.stop();
  4325. listen_thread.join();
  4326. ASSERT_FALSE(svr.is_running());
  4327. });
  4328. svr.wait_until_ready();
  4329. {
  4330. SSLClient cli(HOST, port);
  4331. cli.enable_server_certificate_verification(false);
  4332. cli.set_read_timeout(5, 0);
  4333. EXPECT_FALSE(cli.Get("/throw"));
  4334. }
  4335. EXPECT_TRUE(svr.is_running());
  4336. EXPECT_EQ(1, reported.load());
  4337. {
  4338. SSLClient cli(HOST, port);
  4339. cli.enable_server_certificate_verification(false);
  4340. auto res = cli.Get("/ok");
  4341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4342. EXPECT_EQ(StatusCode::OK_200, res->status);
  4343. EXPECT_EQ("ok", res->body);
  4344. }
  4345. }
  4346. #endif
  4347. #endif
  4348. TEST(NoContentTest, ContentLength) {
  4349. Server svr;
  4350. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4351. res.status = StatusCode::NoContent_204;
  4352. });
  4353. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4354. auto se = detail::scope_exit([&] {
  4355. svr.stop();
  4356. thread.join();
  4357. ASSERT_FALSE(svr.is_running());
  4358. });
  4359. svr.wait_until_ready();
  4360. {
  4361. Client cli(HOST, PORT);
  4362. auto res = cli.Get("/hi");
  4363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4364. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4365. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4366. }
  4367. }
  4368. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4369. #ifdef CPPHTTPLIB_SSL_ENABLED
  4370. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4371. ASSERT_TRUE(svr.is_valid());
  4372. #else
  4373. Server svr;
  4374. #endif
  4375. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4376. if (req.path == "/routing_handler") {
  4377. res.set_header("PRE_ROUTING", "on");
  4378. res.set_content("Routing Handler", "text/plain");
  4379. return httplib::Server::HandlerResponse::Handled;
  4380. }
  4381. return httplib::Server::HandlerResponse::Unhandled;
  4382. });
  4383. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4384. res.set_content("Error", "text/html");
  4385. });
  4386. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4387. if (req.path == "/routing_handler") {
  4388. res.set_header("POST_ROUTING", "on");
  4389. }
  4390. });
  4391. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4392. res.set_content("Hello World!\n", "text/plain");
  4393. });
  4394. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4395. auto se = detail::scope_exit([&] {
  4396. svr.stop();
  4397. thread.join();
  4398. ASSERT_FALSE(svr.is_running());
  4399. });
  4400. svr.wait_until_ready();
  4401. {
  4402. #ifdef CPPHTTPLIB_SSL_ENABLED
  4403. SSLClient cli(HOST, PORT);
  4404. cli.enable_server_certificate_verification(false);
  4405. #else
  4406. Client cli(HOST, PORT);
  4407. #endif
  4408. auto res = cli.Get("/routing_handler");
  4409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4410. EXPECT_EQ(StatusCode::OK_200, res->status);
  4411. EXPECT_EQ("Routing Handler", res->body);
  4412. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4413. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4414. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4415. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4416. }
  4417. {
  4418. #ifdef CPPHTTPLIB_SSL_ENABLED
  4419. SSLClient cli(HOST, PORT);
  4420. cli.enable_server_certificate_verification(false);
  4421. #else
  4422. Client cli(HOST, PORT);
  4423. #endif
  4424. auto res = cli.Get("/hi");
  4425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4426. EXPECT_EQ(StatusCode::OK_200, res->status);
  4427. EXPECT_EQ("Hello World!\n", res->body);
  4428. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4429. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4430. }
  4431. {
  4432. #ifdef CPPHTTPLIB_SSL_ENABLED
  4433. SSLClient cli(HOST, PORT);
  4434. cli.enable_server_certificate_verification(false);
  4435. #else
  4436. Client cli(HOST, PORT);
  4437. #endif
  4438. auto res = cli.Get("/aaa");
  4439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4440. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4441. EXPECT_EQ("Error", res->body);
  4442. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4443. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4444. }
  4445. }
  4446. TEST(RequestHandlerTest, PreRequestHandler) {
  4447. auto route_path = "/user/:user";
  4448. Server svr;
  4449. svr.Get("/hi", [](const Request &, Response &res) {
  4450. res.set_content("hi", "text/plain");
  4451. });
  4452. svr.Get(route_path, [](const Request &req, Response &res) {
  4453. res.set_content(req.path_params.at("user"), "text/plain");
  4454. });
  4455. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4456. if (req.matched_route == route_path) {
  4457. auto user = req.path_params.at("user");
  4458. if (user != "john") {
  4459. res.status = StatusCode::Forbidden_403;
  4460. res.set_content("error", "text/html");
  4461. return Server::HandlerResponse::Handled;
  4462. }
  4463. }
  4464. return Server::HandlerResponse::Unhandled;
  4465. });
  4466. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4467. auto se = detail::scope_exit([&] {
  4468. svr.stop();
  4469. thread.join();
  4470. ASSERT_FALSE(svr.is_running());
  4471. });
  4472. svr.wait_until_ready();
  4473. Client cli(HOST, PORT);
  4474. {
  4475. auto res = cli.Get("/hi");
  4476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4477. EXPECT_EQ(StatusCode::OK_200, res->status);
  4478. EXPECT_EQ("hi", res->body);
  4479. }
  4480. {
  4481. auto res = cli.Get("/user/john");
  4482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4483. EXPECT_EQ(StatusCode::OK_200, res->status);
  4484. EXPECT_EQ("john", res->body);
  4485. }
  4486. {
  4487. auto res = cli.Get("/user/invalid-user");
  4488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4489. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4490. EXPECT_EQ("error", res->body);
  4491. }
  4492. }
  4493. // The pre-request handler must run before the request body is read, so a
  4494. // rejected request never forces the server to buffer a (potentially large)
  4495. // body. Here the posted body is larger than the payload limit: if the body
  4496. // were read first the server would answer 413, but because the pre-request
  4497. // handler runs first it answers 403 and the body is never read.
  4498. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4499. Server svr;
  4500. svr.set_payload_max_length(8);
  4501. auto handler_ran = false;
  4502. svr.Post("/reject", [&](const Request &req, Response &res) {
  4503. handler_ran = true;
  4504. res.set_content(req.body, "text/plain");
  4505. });
  4506. svr.Post("/accept", [](const Request &req, Response &res) {
  4507. res.set_content(req.body, "text/plain");
  4508. });
  4509. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4510. if (req.matched_route == "/reject") {
  4511. res.status = StatusCode::Forbidden_403;
  4512. res.set_content("denied", "text/plain");
  4513. return Server::HandlerResponse::Handled;
  4514. }
  4515. return Server::HandlerResponse::Unhandled;
  4516. });
  4517. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4518. auto se = detail::scope_exit([&] {
  4519. svr.stop();
  4520. thread.join();
  4521. ASSERT_FALSE(svr.is_running());
  4522. });
  4523. svr.wait_until_ready();
  4524. Client cli(HOST, PORT);
  4525. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4526. // rejects with 403 before the body is read, so 413 is never reached.
  4527. {
  4528. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4530. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4531. EXPECT_EQ("denied", res->body);
  4532. EXPECT_FALSE(handler_ran);
  4533. }
  4534. // An approved route still reads the body and enforces the payload limit.
  4535. {
  4536. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4538. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4539. }
  4540. }
  4541. TEST(UserDataTest, BasicOperations) {
  4542. httplib::UserData ud;
  4543. // Initially empty
  4544. EXPECT_FALSE(ud.has("key"));
  4545. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4546. // set and get
  4547. ud.set("key", 42);
  4548. EXPECT_TRUE(ud.has("key"));
  4549. auto *p = ud.get<int>("key");
  4550. ASSERT_NE(nullptr, p);
  4551. EXPECT_EQ(42, *p);
  4552. // Type mismatch → nullptr
  4553. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4554. // Overwrite with different type
  4555. ud.set("key", std::string("hello"));
  4556. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4557. auto *s = ud.get<std::string>("key");
  4558. ASSERT_NE(nullptr, s);
  4559. EXPECT_EQ("hello", *s);
  4560. // erase
  4561. ud.erase("key");
  4562. EXPECT_FALSE(ud.has("key"));
  4563. // clear
  4564. ud.set("a", 1);
  4565. ud.set("b", 2);
  4566. ud.clear();
  4567. EXPECT_FALSE(ud.has("a"));
  4568. EXPECT_FALSE(ud.has("b"));
  4569. }
  4570. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4571. struct AuthCtx {
  4572. std::string user_id;
  4573. };
  4574. Server svr;
  4575. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4576. res.user_data.set("auth", AuthCtx{"alice"});
  4577. return Server::HandlerResponse::Unhandled;
  4578. });
  4579. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4580. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4581. ASSERT_NE(nullptr, ctx);
  4582. res.set_content("Hello " + ctx->user_id, "text/plain");
  4583. });
  4584. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4585. auto se = detail::scope_exit([&] {
  4586. svr.stop();
  4587. thread.join();
  4588. ASSERT_FALSE(svr.is_running());
  4589. });
  4590. svr.wait_until_ready();
  4591. Client cli(HOST, PORT);
  4592. auto res = cli.Get("/me");
  4593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4594. EXPECT_EQ(StatusCode::OK_200, res->status);
  4595. EXPECT_EQ("Hello alice", res->body);
  4596. }
  4597. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4598. struct RoleCtx {
  4599. std::string role;
  4600. };
  4601. Server svr;
  4602. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4603. res.user_data.set("role", RoleCtx{"admin"});
  4604. return Server::HandlerResponse::Unhandled;
  4605. });
  4606. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4607. auto *ctx = res.user_data.get<RoleCtx>("role");
  4608. ASSERT_NE(nullptr, ctx);
  4609. res.set_content(ctx->role, "text/plain");
  4610. });
  4611. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4612. auto se = detail::scope_exit([&] {
  4613. svr.stop();
  4614. thread.join();
  4615. ASSERT_FALSE(svr.is_running());
  4616. });
  4617. svr.wait_until_ready();
  4618. Client cli(HOST, PORT);
  4619. auto res = cli.Get("/role");
  4620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4621. EXPECT_EQ(StatusCode::OK_200, res->status);
  4622. EXPECT_EQ("admin", res->body);
  4623. }
  4624. TEST(InvalidFormatTest, StatusCode) {
  4625. Server svr;
  4626. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4627. res.set_content("Hello World!\n", "text/plain");
  4628. res.status = 9999; // Status should be a three-digit code...
  4629. });
  4630. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4631. auto se = detail::scope_exit([&] {
  4632. svr.stop();
  4633. thread.join();
  4634. ASSERT_FALSE(svr.is_running());
  4635. });
  4636. svr.wait_until_ready();
  4637. {
  4638. Client cli(HOST, PORT);
  4639. auto res = cli.Get("/hi");
  4640. ASSERT_FALSE(res);
  4641. }
  4642. }
  4643. TEST(URLFragmentTest, WithFragment) {
  4644. Server svr;
  4645. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4646. EXPECT_TRUE(req.target == "/hi");
  4647. });
  4648. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4649. auto se = detail::scope_exit([&] {
  4650. svr.stop();
  4651. thread.join();
  4652. ASSERT_FALSE(svr.is_running());
  4653. });
  4654. svr.wait_until_ready();
  4655. {
  4656. Client cli(HOST, PORT);
  4657. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4658. EXPECT_TRUE(res);
  4659. EXPECT_EQ(StatusCode::OK_200, res->status);
  4660. res = cli.Get("/hi%23key1=val1=key2=val2");
  4661. EXPECT_TRUE(res);
  4662. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4663. }
  4664. }
  4665. TEST(HeaderWriter, SetHeaderWriter) {
  4666. Server svr;
  4667. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4668. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4669. return detail::write_headers(strm, hdrs);
  4670. });
  4671. svr.Get("/hi", [](const Request &req, Response &res) {
  4672. auto it = req.headers.find("CustomClientHeader");
  4673. EXPECT_TRUE(it != req.headers.end());
  4674. EXPECT_EQ(it->second, "CustomClientValue");
  4675. res.set_content("Hello World!\n", "text/plain");
  4676. });
  4677. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4678. auto se = detail::scope_exit([&] {
  4679. svr.stop();
  4680. thread.join();
  4681. ASSERT_FALSE(svr.is_running());
  4682. });
  4683. svr.wait_until_ready();
  4684. {
  4685. Client cli(HOST, PORT);
  4686. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4687. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4688. return detail::write_headers(strm, hdrs);
  4689. });
  4690. auto res = cli.Get("/hi");
  4691. EXPECT_TRUE(res);
  4692. EXPECT_EQ(StatusCode::OK_200, res->status);
  4693. auto it = res->headers.find("CustomServerHeader");
  4694. EXPECT_TRUE(it != res->headers.end());
  4695. EXPECT_EQ(it->second, "CustomServerValue");
  4696. }
  4697. }
  4698. class ServerTest : public ::testing::Test {
  4699. protected:
  4700. ServerTest()
  4701. : cli_(HOST, PORT)
  4702. #ifdef CPPHTTPLIB_SSL_ENABLED
  4703. ,
  4704. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4705. #endif
  4706. {
  4707. #ifdef CPPHTTPLIB_SSL_ENABLED
  4708. cli_.enable_server_certificate_verification(false);
  4709. #endif
  4710. // Allow LARGE_DATA (100MB) responses
  4711. cli_.set_payload_max_length(200 * 1024 * 1024);
  4712. }
  4713. virtual void SetUp() {
  4714. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4715. svr_.set_payload_max_length(200 * 1024 * 1024);
  4716. svr_.set_mount_point("/", "./www");
  4717. svr_.set_mount_point("/mount", "./www2");
  4718. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4719. svr_.Get("/hi",
  4720. [&](const Request & /*req*/, Response &res) {
  4721. res.set_content("Hello World!", "text/plain");
  4722. })
  4723. .Get("/file_content",
  4724. [&](const Request & /*req*/, Response &res) {
  4725. res.set_file_content("./www/dir/test.html");
  4726. })
  4727. .Get("/file_content_with_content_type",
  4728. [&](const Request & /*req*/, Response &res) {
  4729. res.set_file_content("./www/file", "text/plain");
  4730. })
  4731. .Get("/invalid_file_content",
  4732. [&](const Request & /*req*/, Response &res) {
  4733. res.set_file_content("./www/dir/invalid_file_path");
  4734. })
  4735. .Get("/http_response_splitting",
  4736. [&](const Request & /*req*/, Response &res) {
  4737. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4738. EXPECT_EQ(0U, res.headers.size());
  4739. EXPECT_FALSE(res.has_header("a"));
  4740. res.set_header("a", "1\nSet-Cookie: a=1");
  4741. EXPECT_EQ(0U, res.headers.size());
  4742. EXPECT_FALSE(res.has_header("a"));
  4743. res.set_header("a", "1\rSet-Cookie: a=1");
  4744. EXPECT_EQ(0U, res.headers.size());
  4745. EXPECT_FALSE(res.has_header("a"));
  4746. res.set_header("a\r\nb", "0");
  4747. EXPECT_EQ(0U, res.headers.size());
  4748. EXPECT_FALSE(res.has_header("a"));
  4749. res.set_header("a\rb", "0");
  4750. EXPECT_EQ(0U, res.headers.size());
  4751. EXPECT_FALSE(res.has_header("a"));
  4752. res.set_header("a\nb", "0");
  4753. EXPECT_EQ(0U, res.headers.size());
  4754. EXPECT_FALSE(res.has_header("a"));
  4755. res.set_redirect("1\r\nSet-Cookie: a=1");
  4756. EXPECT_EQ(0U, res.headers.size());
  4757. EXPECT_FALSE(res.has_header("Location"));
  4758. })
  4759. .Get("/slow",
  4760. [&](const Request & /*req*/, Response &res) {
  4761. std::this_thread::sleep_for(std::chrono::seconds(4));
  4762. res.set_content("slow", "text/plain");
  4763. })
  4764. #if 0
  4765. .Post("/slowpost",
  4766. [&](const Request & /*req*/, Response &res) {
  4767. std::this_thread::sleep_for(std::chrono::seconds(2));
  4768. res.set_content("slow", "text/plain");
  4769. })
  4770. #endif
  4771. .Get("/remote_addr",
  4772. [&](const Request &req, Response &res) {
  4773. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4774. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4775. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4776. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4777. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4778. #endif
  4779. res.set_content(req.remote_addr, "text/plain");
  4780. })
  4781. .Get("/local_addr",
  4782. [&](const Request &req, Response &res) {
  4783. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4784. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4785. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4786. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4787. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4788. #endif
  4789. auto local_addr = req.local_addr;
  4790. auto local_port = std::to_string(req.local_port);
  4791. res.set_content(local_addr.append(":").append(local_port),
  4792. "text/plain");
  4793. })
  4794. .Get("/endwith%",
  4795. [&](const Request & /*req*/, Response &res) {
  4796. res.set_content("Hello World!", "text/plain");
  4797. })
  4798. .Get("/a\\+\\+b",
  4799. [&](const Request &req, Response &res) {
  4800. ASSERT_TRUE(req.has_param("a +b"));
  4801. auto val = req.get_param_value("a +b");
  4802. res.set_content(val, "text/plain");
  4803. })
  4804. .Get("/", [&](const Request & /*req*/,
  4805. Response &res) { res.set_redirect("/hi"); })
  4806. .Post("/1",
  4807. [](const Request & /*req*/, Response &res) {
  4808. res.set_redirect("/2", StatusCode::SeeOther_303);
  4809. })
  4810. .Get("/2",
  4811. [](const Request & /*req*/, Response &res) {
  4812. res.set_content("redirected.", "text/plain");
  4813. res.status = StatusCode::OK_200;
  4814. })
  4815. .Post("/person",
  4816. [&](const Request &req, Response &res) {
  4817. if (req.has_param("name") && req.has_param("note")) {
  4818. persons_[req.get_param_value("name")] =
  4819. req.get_param_value("note");
  4820. } else {
  4821. res.status = StatusCode::BadRequest_400;
  4822. }
  4823. })
  4824. .Put("/person",
  4825. [&](const Request &req, Response &res) {
  4826. if (req.has_param("name") && req.has_param("note")) {
  4827. persons_[req.get_param_value("name")] =
  4828. req.get_param_value("note");
  4829. } else {
  4830. res.status = StatusCode::BadRequest_400;
  4831. }
  4832. })
  4833. .Get("/person/(.*)",
  4834. [&](const Request &req, Response &res) {
  4835. string name = req.matches[1];
  4836. if (persons_.find(name) != persons_.end()) {
  4837. auto note = persons_[name];
  4838. res.set_content(note, "text/plain");
  4839. } else {
  4840. res.status = StatusCode::NotFound_404;
  4841. }
  4842. })
  4843. .Delete("/person",
  4844. [&](const Request &req, Response &res) {
  4845. if (req.has_param("name")) {
  4846. string name = req.get_param_value("name");
  4847. if (persons_.find(name) != persons_.end()) {
  4848. persons_.erase(name);
  4849. res.set_content("DELETED", "text/plain");
  4850. } else {
  4851. res.status = StatusCode::NotFound_404;
  4852. }
  4853. } else {
  4854. res.status = StatusCode::BadRequest_400;
  4855. }
  4856. })
  4857. .Post("/x-www-form-urlencoded-json",
  4858. [&](const Request &req, Response &res) {
  4859. auto json = req.get_param_value("json");
  4860. ASSERT_EQ(JSON_DATA, json);
  4861. res.set_content(json, "appliation/json");
  4862. res.status = StatusCode::OK_200;
  4863. })
  4864. .Get("/streamed-chunked",
  4865. [&](const Request & /*req*/, Response &res) {
  4866. res.set_chunked_content_provider(
  4867. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4868. sink.os << "123";
  4869. sink.os << "456";
  4870. sink.os << "789";
  4871. sink.done();
  4872. return true;
  4873. });
  4874. })
  4875. .Get("/streamed-chunked-with-prohibited-trailer",
  4876. [&](const Request & /*req*/, Response &res) {
  4877. auto i = new int(0);
  4878. // Declare both a prohibited trailer (Content-Length) and an
  4879. // allowed one
  4880. res.set_header("Trailer", "Content-Length, X-Allowed");
  4881. res.set_chunked_content_provider(
  4882. "text/plain",
  4883. [i](size_t /*offset*/, DataSink &sink) {
  4884. switch (*i) {
  4885. case 0: sink.os << "123"; break;
  4886. case 1: sink.os << "456"; break;
  4887. case 2: sink.os << "789"; break;
  4888. case 3: {
  4889. sink.done_with_trailer(
  4890. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4891. } break;
  4892. }
  4893. (*i)++;
  4894. return true;
  4895. },
  4896. [i](bool success) {
  4897. EXPECT_TRUE(success);
  4898. delete i;
  4899. });
  4900. })
  4901. .Get("/streamed-chunked2",
  4902. [&](const Request & /*req*/, Response &res) {
  4903. auto i = new int(0);
  4904. res.set_chunked_content_provider(
  4905. "text/plain",
  4906. [i](size_t /*offset*/, DataSink &sink) {
  4907. switch (*i) {
  4908. case 0: sink.os << "123"; break;
  4909. case 1: sink.os << "456"; break;
  4910. case 2: sink.os << "789"; break;
  4911. case 3: sink.done(); break;
  4912. }
  4913. (*i)++;
  4914. return true;
  4915. },
  4916. [i](bool success) {
  4917. EXPECT_TRUE(success);
  4918. delete i;
  4919. });
  4920. })
  4921. .Get("/streamed-chunked-with-trailer",
  4922. [&](const Request & /*req*/, Response &res) {
  4923. auto i = new int(0);
  4924. res.set_header("Trailer", "Dummy1, Dummy2");
  4925. res.set_chunked_content_provider(
  4926. "text/plain",
  4927. [i](size_t /*offset*/, DataSink &sink) {
  4928. switch (*i) {
  4929. case 0: sink.os << "123"; break;
  4930. case 1: sink.os << "456"; break;
  4931. case 2: sink.os << "789"; break;
  4932. case 3: {
  4933. sink.done_with_trailer(
  4934. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4935. } break;
  4936. }
  4937. (*i)++;
  4938. return true;
  4939. },
  4940. [i](bool success) {
  4941. EXPECT_TRUE(success);
  4942. delete i;
  4943. });
  4944. })
  4945. .Get("/streamed",
  4946. [&](const Request & /*req*/, Response &res) {
  4947. res.set_content_provider(
  4948. 6, "text/plain",
  4949. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4950. sink.os << (offset < 3 ? "a" : "b");
  4951. return true;
  4952. });
  4953. })
  4954. .Get("/streamed-without-length",
  4955. [&](const Request & /*req*/, Response &res) {
  4956. auto data = new std::string("abcdefg");
  4957. res.set_content_provider(
  4958. "text/plain",
  4959. [data](size_t offset, DataSink &sink) {
  4960. if (offset < data->size()) {
  4961. sink.os << data->substr(offset);
  4962. }
  4963. sink.done();
  4964. return true;
  4965. },
  4966. [data](bool success) {
  4967. EXPECT_TRUE(success);
  4968. delete data;
  4969. });
  4970. })
  4971. .Get("/streamed-with-range",
  4972. [&](const Request &req, Response &res) {
  4973. auto data = new std::string("abcdefg");
  4974. // An explicit status keeps the server from picking the 206 it
  4975. // would otherwise choose for a ranged request, so the response
  4976. // is not a partial representation.
  4977. auto status = req.get_param_value("status");
  4978. if (status == "200") {
  4979. res.status = StatusCode::OK_200;
  4980. } else if (status == "403") {
  4981. res.status = StatusCode::Forbidden_403;
  4982. }
  4983. res.set_content_provider(
  4984. data->size(), "text/plain",
  4985. [data](size_t offset, size_t length, DataSink &sink) {
  4986. size_t DATA_CHUNK_SIZE = 4;
  4987. const auto &d = *data;
  4988. auto out_len =
  4989. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4990. auto ret =
  4991. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4992. EXPECT_TRUE(ret);
  4993. return true;
  4994. },
  4995. [data, &req](bool success) {
  4996. EXPECT_EQ(success, !req.has_param("error"));
  4997. delete data;
  4998. });
  4999. })
  5000. .Get("/streamed-cancel",
  5001. [&](const Request & /*req*/, Response &res) {
  5002. res.set_content_provider(
  5003. size_t(-1), "text/plain",
  5004. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5005. sink.os << "data_chunk";
  5006. return true;
  5007. });
  5008. })
  5009. .Get("/regex-with-delimiter",
  5010. [&](const Request &req, Response & /*res*/) {
  5011. ASSERT_TRUE(req.has_param("key"));
  5012. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5013. })
  5014. .Get("/with-range",
  5015. [&](const Request & /*req*/, Response &res) {
  5016. res.set_content("abcdefg", "text/plain");
  5017. })
  5018. .Get("/test-start-time",
  5019. [&](const Request &req, Response & /*res*/) {
  5020. EXPECT_NE(req.start_time_,
  5021. std::chrono::steady_clock::time_point::min());
  5022. })
  5023. .Get("/with-range-customized-response",
  5024. [&](const Request & /*req*/, Response &res) {
  5025. res.status = StatusCode::BadRequest_400;
  5026. res.set_content(JSON_DATA, "application/json");
  5027. })
  5028. .Post("/chunked",
  5029. [&](const Request &req, Response & /*res*/) {
  5030. EXPECT_EQ(req.body, "dechunked post body");
  5031. })
  5032. .Post("/large-chunked",
  5033. [&](const Request &req, Response & /*res*/) {
  5034. std::string expected(6 * 30 * 1024u, 'a');
  5035. EXPECT_EQ(req.body, expected);
  5036. })
  5037. .Post("/multipart",
  5038. [&](const Request &req, Response & /*res*/) {
  5039. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5040. req.form.get_field_count("text2") +
  5041. req.form.get_field_count("file3") +
  5042. req.form.get_field_count("file4"));
  5043. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5044. req.form.get_file_count("file2"));
  5045. ASSERT_TRUE(!req.form.has_file("???"));
  5046. ASSERT_TRUE(!req.form.has_field("???"));
  5047. ASSERT_TRUE(req.body.empty());
  5048. {
  5049. const auto &text = req.form.get_field("text1");
  5050. EXPECT_EQ("text default", text);
  5051. }
  5052. {
  5053. const auto &text = req.form.get_field("text2");
  5054. EXPECT_EQ("aωb", text);
  5055. }
  5056. {
  5057. const auto &file = req.form.get_file("file1");
  5058. EXPECT_EQ("hello.txt", file.filename);
  5059. EXPECT_EQ("text/plain", file.content_type);
  5060. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5061. }
  5062. {
  5063. const auto &file = req.form.get_file("file2");
  5064. EXPECT_EQ("world.json", file.filename);
  5065. EXPECT_EQ("application/json", file.content_type);
  5066. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5067. }
  5068. {
  5069. const auto &text = req.form.get_field("file3");
  5070. EXPECT_EQ(0u, text.size());
  5071. }
  5072. {
  5073. const auto &text = req.form.get_field("file4");
  5074. EXPECT_EQ(0u, text.size());
  5075. }
  5076. })
  5077. .Post("/multipart/multi_file_values",
  5078. [&](const Request &req, Response & /*res*/) {
  5079. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5080. req.form.get_field_count("multi_text1"));
  5081. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5082. ASSERT_TRUE(!req.form.has_file("???"));
  5083. ASSERT_TRUE(!req.form.has_field("???"));
  5084. ASSERT_TRUE(req.body.empty());
  5085. {
  5086. const auto &text = req.form.get_field("text");
  5087. EXPECT_EQ("default text", text);
  5088. }
  5089. {
  5090. const auto &text1_values = req.form.get_fields("multi_text1");
  5091. EXPECT_EQ(2u, text1_values.size());
  5092. EXPECT_EQ("aaaaa", text1_values[0]);
  5093. EXPECT_EQ("bbbbb", text1_values[1]);
  5094. }
  5095. {
  5096. const auto &file1_values = req.form.get_files("multi_file1");
  5097. EXPECT_EQ(2u, file1_values.size());
  5098. auto file1 = file1_values[0];
  5099. EXPECT_EQ(file1.filename, "hello.txt");
  5100. EXPECT_EQ(file1.content_type, "text/plain");
  5101. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5102. auto file2 = file1_values[1];
  5103. EXPECT_EQ(file2.filename, "world.json");
  5104. EXPECT_EQ(file2.content_type, "application/json");
  5105. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5106. }
  5107. })
  5108. .Post("/empty",
  5109. [&](const Request &req, Response &res) {
  5110. EXPECT_EQ(req.body, "");
  5111. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5112. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5113. res.set_content("empty", "text/plain");
  5114. })
  5115. .Post("/empty-no-content-type",
  5116. [&](const Request &req, Response &res) {
  5117. EXPECT_EQ(req.body, "");
  5118. EXPECT_FALSE(req.has_header("Content-Type"));
  5119. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5120. res.set_content("empty-no-content-type", "text/plain");
  5121. })
  5122. .Post("/path-only",
  5123. [&](const Request &req, Response &res) {
  5124. EXPECT_EQ(req.body, "");
  5125. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5126. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5127. res.set_content("path-only", "text/plain");
  5128. })
  5129. .Post("/path-headers-only",
  5130. [&](const Request &req, Response &res) {
  5131. EXPECT_EQ(req.body, "");
  5132. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5133. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5134. EXPECT_EQ("world", req.get_header_value("hello"));
  5135. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5136. res.set_content("path-headers-only", "text/plain");
  5137. })
  5138. .Post("/post-large",
  5139. [&](const Request &req, Response &res) {
  5140. EXPECT_EQ(req.body, LARGE_DATA);
  5141. res.set_content(req.body, "text/plain");
  5142. })
  5143. .Post("/post-loopback",
  5144. [&](const Request &, Response &res,
  5145. ContentReader const &content_reader) {
  5146. std::string body;
  5147. content_reader([&](const char *data, size_t data_length) {
  5148. body.append(data, data_length);
  5149. return true;
  5150. });
  5151. res.set_content(body, "text/plain");
  5152. })
  5153. .Put("/put-loopback",
  5154. [&](const Request &, Response &res,
  5155. ContentReader const &content_reader) {
  5156. std::string body;
  5157. content_reader([&](const char *data, size_t data_length) {
  5158. body.append(data, data_length);
  5159. return true;
  5160. });
  5161. res.set_content(body, "text/plain");
  5162. })
  5163. .Patch("/patch-loopback",
  5164. [&](const Request &, Response &res,
  5165. ContentReader const &content_reader) {
  5166. std::string body;
  5167. content_reader([&](const char *data, size_t data_length) {
  5168. body.append(data, data_length);
  5169. return true;
  5170. });
  5171. res.set_content(body, "text/plain");
  5172. })
  5173. .Put("/empty-no-content-type",
  5174. [&](const Request &req, Response &res) {
  5175. EXPECT_EQ(req.body, "");
  5176. EXPECT_FALSE(req.has_header("Content-Type"));
  5177. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5178. res.set_content("empty-no-content-type", "text/plain");
  5179. })
  5180. .Put("/put",
  5181. [&](const Request &req, Response &res) {
  5182. EXPECT_EQ(req.body, "PUT");
  5183. res.set_content(req.body, "text/plain");
  5184. })
  5185. .Put("/put-large",
  5186. [&](const Request &req, Response &res) {
  5187. EXPECT_EQ(req.body, LARGE_DATA);
  5188. res.set_content(req.body, "text/plain");
  5189. })
  5190. .Patch("/patch",
  5191. [&](const Request &req, Response &res) {
  5192. EXPECT_EQ(req.body, "PATCH");
  5193. res.set_content(req.body, "text/plain");
  5194. })
  5195. .Delete("/delete",
  5196. [&](const Request & /*req*/, Response &res) {
  5197. res.set_content("DELETE", "text/plain");
  5198. })
  5199. .Delete("/delete-body",
  5200. [&](const Request &req, Response &res) {
  5201. EXPECT_EQ(req.body, "content");
  5202. res.set_content(req.body, "text/plain");
  5203. })
  5204. .Options(R"(\*)",
  5205. [&](const Request & /*req*/, Response &res) {
  5206. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5207. })
  5208. .CustomRoute("PROPFIND", "/dav/:id",
  5209. [&](const Request &req, Response &res) {
  5210. res.set_header("x-body-size",
  5211. std::to_string(req.body.size()));
  5212. res.set_header("x-matched-route", req.matched_route);
  5213. res.set_header("x-dav-id", req.path_params.at("id"));
  5214. res.status = StatusCode::MultiStatus_207;
  5215. res.set_content(req.body, "application/xml");
  5216. })
  5217. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5218. [&](const Request &req, Response &res) {
  5219. res.set_header("x-dav-match", req.matches[1]);
  5220. res.status = StatusCode::MultiStatus_207;
  5221. })
  5222. .CustomRoute("MKCOL", "/dav-mkcol",
  5223. [&](const Request &req, Response &res) {
  5224. EXPECT_TRUE(req.body.empty());
  5225. res.status = StatusCode::Created_201;
  5226. })
  5227. .CustomRoute(
  5228. "REPORT", "/dav-report",
  5229. [&](const Request & /*req*/, Response &res,
  5230. const ContentReader &content_reader) {
  5231. std::string body;
  5232. content_reader([&](const char *data, size_t data_length) {
  5233. body.append(data, data_length);
  5234. return true;
  5235. });
  5236. res.set_header("x-body-size", std::to_string(body.size()));
  5237. res.status = StatusCode::MultiStatus_207;
  5238. res.set_content(body, "application/xml");
  5239. })
  5240. .Get("/request-target",
  5241. [&](const Request &req, Response & /*res*/) {
  5242. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5243. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5244. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5245. })
  5246. .Get("/long-query-value",
  5247. [&](const Request &req, Response & /*res*/) {
  5248. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5249. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5250. })
  5251. .Get("/too-long-query-value",
  5252. [&](const Request &req, Response & /*res*/) {
  5253. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5254. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5255. })
  5256. .Get("/array-param",
  5257. [&](const Request &req, Response & /*res*/) {
  5258. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5259. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5260. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5261. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5262. })
  5263. .Get("/array-param-values",
  5264. [&](const Request &req, Response & /*res*/) {
  5265. auto values = req.get_param_values("array");
  5266. EXPECT_EQ(3u, values.size());
  5267. EXPECT_EQ("value1", values[0]);
  5268. EXPECT_EQ("value2", values[1]);
  5269. EXPECT_EQ("value3", values[2]);
  5270. auto empty = req.get_param_values("nonexistent");
  5271. EXPECT_TRUE(empty.empty());
  5272. })
  5273. .Post("/validate-no-multiple-headers",
  5274. [&](const Request &req, Response & /*res*/) {
  5275. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5276. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5277. })
  5278. .Post("/content_receiver",
  5279. [&](const Request &req, Response &res,
  5280. const ContentReader &content_reader) {
  5281. if (req.is_multipart_form_data()) {
  5282. std::vector<FormData> items;
  5283. content_reader(
  5284. [&](const FormData &file) {
  5285. items.push_back(file);
  5286. return true;
  5287. },
  5288. [&](const char *data, size_t data_length) {
  5289. items.back().content.append(data, data_length);
  5290. return true;
  5291. });
  5292. EXPECT_EQ(5u, items.size());
  5293. {
  5294. const auto &file = get_file_value(items, "text1");
  5295. EXPECT_TRUE(file.filename.empty());
  5296. EXPECT_EQ("text default", file.content);
  5297. }
  5298. {
  5299. const auto &file = get_file_value(items, "text2");
  5300. EXPECT_TRUE(file.filename.empty());
  5301. EXPECT_EQ("aωb", file.content);
  5302. }
  5303. {
  5304. const auto &file = get_file_value(items, "file1");
  5305. EXPECT_EQ("hello.txt", file.filename);
  5306. EXPECT_EQ("text/plain", file.content_type);
  5307. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5308. }
  5309. {
  5310. const auto &file = get_file_value(items, "file2");
  5311. EXPECT_EQ("world.json", file.filename);
  5312. EXPECT_EQ("application/json", file.content_type);
  5313. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5314. }
  5315. {
  5316. const auto &file = get_file_value(items, "file3");
  5317. EXPECT_TRUE(file.filename.empty());
  5318. EXPECT_EQ("application/octet-stream", file.content_type);
  5319. EXPECT_EQ(0u, file.content.size());
  5320. }
  5321. } else {
  5322. std::string body;
  5323. content_reader([&](const char *data, size_t data_length) {
  5324. EXPECT_EQ(7U, data_length);
  5325. body.append(data, data_length);
  5326. return true;
  5327. });
  5328. EXPECT_EQ(body, "content");
  5329. res.set_content(body, "text/plain");
  5330. }
  5331. })
  5332. .Put("/content_receiver",
  5333. [&](const Request & /*req*/, Response &res,
  5334. const ContentReader &content_reader) {
  5335. std::string body;
  5336. content_reader([&](const char *data, size_t data_length) {
  5337. body.append(data, data_length);
  5338. return true;
  5339. });
  5340. EXPECT_EQ(body, "content");
  5341. res.set_content(body, "text/plain");
  5342. })
  5343. .Patch("/content_receiver",
  5344. [&](const Request & /*req*/, Response &res,
  5345. const ContentReader &content_reader) {
  5346. std::string body;
  5347. content_reader([&](const char *data, size_t data_length) {
  5348. body.append(data, data_length);
  5349. return true;
  5350. });
  5351. EXPECT_EQ(body, "content");
  5352. res.set_content(body, "text/plain");
  5353. })
  5354. .Post("/query-string-and-body",
  5355. [&](const Request &req, Response & /*res*/) {
  5356. ASSERT_TRUE(req.has_param("key"));
  5357. EXPECT_EQ(req.get_param_value("key"), "value");
  5358. EXPECT_EQ(req.body, "content");
  5359. })
  5360. .Get("/last-request",
  5361. [&](const Request &req, Response & /*res*/) {
  5362. EXPECT_EQ("close", req.get_header_value("Connection"));
  5363. })
  5364. .Get(R"(/redirect/(\d+))",
  5365. [&](const Request &req, Response &res) {
  5366. auto num = std::stoi(req.matches[1]) + 1;
  5367. std::string url = "/redirect/" + std::to_string(num);
  5368. res.set_redirect(url);
  5369. })
  5370. .Post("/binary",
  5371. [&](const Request &req, Response &res) {
  5372. EXPECT_EQ(4U, req.body.size());
  5373. EXPECT_EQ("application/octet-stream",
  5374. req.get_header_value("Content-Type"));
  5375. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5376. res.set_content(req.body, "application/octet-stream");
  5377. })
  5378. .Put("/binary",
  5379. [&](const Request &req, Response &res) {
  5380. EXPECT_EQ(4U, req.body.size());
  5381. EXPECT_EQ("application/octet-stream",
  5382. req.get_header_value("Content-Type"));
  5383. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5384. res.set_content(req.body, "application/octet-stream");
  5385. })
  5386. .Patch("/binary",
  5387. [&](const Request &req, Response &res) {
  5388. EXPECT_EQ(4U, req.body.size());
  5389. EXPECT_EQ("application/octet-stream",
  5390. req.get_header_value("Content-Type"));
  5391. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5392. res.set_content(req.body, "application/octet-stream");
  5393. })
  5394. .Delete("/binary",
  5395. [&](const Request &req, Response &res) {
  5396. EXPECT_EQ(4U, req.body.size());
  5397. EXPECT_EQ("application/octet-stream",
  5398. req.get_header_value("Content-Type"));
  5399. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5400. res.set_content(req.body, "application/octet-stream");
  5401. })
  5402. .Get("/issue1772",
  5403. [&](const Request & /*req*/, Response &res) {
  5404. res.status = 401;
  5405. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5406. })
  5407. .Delete("/issue609",
  5408. [](const httplib::Request &, httplib::Response &res,
  5409. const httplib::ContentReader &) {
  5410. res.set_content("ok", "text/plain");
  5411. })
  5412. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5413. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5414. .Get("/compress",
  5415. [&](const Request & /*req*/, Response &res) {
  5416. res.set_content(
  5417. "12345678901234567890123456789012345678901234567890123456789"
  5418. "01234567890123456789012345678901234567890",
  5419. "text/plain");
  5420. })
  5421. .Get("/compress-with-charset",
  5422. [&](const Request & /*req*/, Response &res) {
  5423. res.set_content(
  5424. "12345678901234567890123456789012345678901234567890123456789"
  5425. "01234567890123456789012345678901234567890",
  5426. "application/json; charset=utf-8");
  5427. })
  5428. .Get("/nocompress",
  5429. [&](const Request & /*req*/, Response &res) {
  5430. res.set_content(
  5431. "12345678901234567890123456789012345678901234567890123456789"
  5432. "01234567890123456789012345678901234567890",
  5433. "application/octet-stream");
  5434. })
  5435. .Post("/compress-multipart",
  5436. [&](const Request &req, Response & /*res*/) {
  5437. EXPECT_EQ(2u, req.form.fields.size());
  5438. ASSERT_TRUE(!req.form.has_field("???"));
  5439. {
  5440. const auto &text = req.form.get_field("key1");
  5441. EXPECT_EQ("test", text);
  5442. }
  5443. {
  5444. const auto &text = req.form.get_field("key2");
  5445. EXPECT_EQ("--abcdefg123", text);
  5446. }
  5447. })
  5448. #endif
  5449. ;
  5450. persons_["john"] = "programmer";
  5451. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5452. svr_.wait_until_ready();
  5453. }
  5454. virtual void TearDown() {
  5455. svr_.stop();
  5456. if (!request_threads_.empty()) {
  5457. std::this_thread::sleep_for(std::chrono::seconds(1));
  5458. for (auto &t : request_threads_) {
  5459. t.join();
  5460. }
  5461. }
  5462. t_.join();
  5463. }
  5464. map<string, string> persons_;
  5465. #ifdef CPPHTTPLIB_SSL_ENABLED
  5466. SSLClient cli_;
  5467. SSLServer svr_;
  5468. #else
  5469. Client cli_;
  5470. Server svr_;
  5471. #endif
  5472. thread t_;
  5473. std::vector<thread> request_threads_;
  5474. };
  5475. TEST_F(ServerTest, GetMethod200) {
  5476. auto res = cli_.Get("/hi");
  5477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5478. EXPECT_EQ("HTTP/1.1", res->version);
  5479. EXPECT_EQ(StatusCode::OK_200, res->status);
  5480. EXPECT_EQ("OK", res->reason);
  5481. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5482. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5483. EXPECT_EQ("Hello World!", res->body);
  5484. }
  5485. TEST_F(ServerTest, GetEmptyFile) {
  5486. auto res = cli_.Get("/empty_file");
  5487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5488. EXPECT_EQ(StatusCode::OK_200, res->status);
  5489. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5490. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5491. EXPECT_EQ("", res->body);
  5492. }
  5493. TEST_F(ServerTest, GetFileContent) {
  5494. auto res = cli_.Get("/file_content");
  5495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5496. EXPECT_EQ(StatusCode::OK_200, res->status);
  5497. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5498. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5499. EXPECT_EQ("test.html", res->body);
  5500. }
  5501. TEST_F(ServerTest, GetFileContentWithRange) {
  5502. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5504. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5505. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5506. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5507. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5508. EXPECT_EQ("est", res->body);
  5509. }
  5510. TEST_F(ServerTest, GetFileContentWithContentType) {
  5511. auto res = cli_.Get("/file_content_with_content_type");
  5512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5513. EXPECT_EQ(StatusCode::OK_200, res->status);
  5514. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5515. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5516. EXPECT_EQ("file\n", res->body);
  5517. }
  5518. TEST_F(ServerTest, GetInvalidFileContent) {
  5519. auto res = cli_.Get("/invalid_file_content");
  5520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5521. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5522. }
  5523. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5524. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5526. EXPECT_EQ("HTTP/1.1", res->version);
  5527. EXPECT_EQ(StatusCode::OK_200, res->status);
  5528. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5529. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5530. EXPECT_EQ("Hello World!", res->body);
  5531. }
  5532. TEST_F(ServerTest, GetMethod302) {
  5533. auto res = cli_.Get("/");
  5534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5535. EXPECT_EQ(StatusCode::Found_302, res->status);
  5536. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5537. }
  5538. TEST_F(ServerTest, GetMethod302Redirect) {
  5539. cli_.set_follow_location(true);
  5540. auto res = cli_.Get("/");
  5541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5542. EXPECT_EQ(StatusCode::OK_200, res->status);
  5543. EXPECT_EQ("Hello World!", res->body);
  5544. EXPECT_EQ("/hi", res->location);
  5545. }
  5546. TEST_F(ServerTest, GetMethod404) {
  5547. auto res = cli_.Get("/invalid");
  5548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5549. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5550. }
  5551. TEST_F(ServerTest, HeadMethod200) {
  5552. auto res = cli_.Head("/hi");
  5553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5554. EXPECT_EQ(StatusCode::OK_200, res->status);
  5555. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5556. EXPECT_TRUE(res->body.empty());
  5557. }
  5558. TEST_F(ServerTest, HeadMethod200Static) {
  5559. auto res = cli_.Head("/mount/dir/index.html");
  5560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5561. EXPECT_EQ(StatusCode::OK_200, res->status);
  5562. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5563. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5564. EXPECT_TRUE(res->body.empty());
  5565. }
  5566. TEST_F(ServerTest, HeadMethod404) {
  5567. auto res = cli_.Head("/invalid");
  5568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5569. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5570. EXPECT_TRUE(res->body.empty());
  5571. }
  5572. TEST_F(ServerTest, GetMethodPersonJohn) {
  5573. auto res = cli_.Get("/person/john");
  5574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5575. EXPECT_EQ(StatusCode::OK_200, res->status);
  5576. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5577. EXPECT_EQ("programmer", res->body);
  5578. }
  5579. TEST_F(ServerTest, PostMethod1) {
  5580. auto res = cli_.Get("/person/john1");
  5581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5582. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5583. res = cli_.Post("/person", "name=john1&note=coder",
  5584. "application/x-www-form-urlencoded");
  5585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5586. ASSERT_EQ(StatusCode::OK_200, res->status);
  5587. res = cli_.Get("/person/john1");
  5588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5589. ASSERT_EQ(StatusCode::OK_200, res->status);
  5590. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5591. ASSERT_EQ("coder", res->body);
  5592. }
  5593. TEST_F(ServerTest, PostMethod2) {
  5594. auto res = cli_.Get("/person/john2");
  5595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5596. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5597. Params params;
  5598. params.emplace("name", "john2");
  5599. params.emplace("note", "coder");
  5600. res = cli_.Post("/person", params);
  5601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5602. ASSERT_EQ(StatusCode::OK_200, res->status);
  5603. res = cli_.Get("/person/john2");
  5604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5605. ASSERT_EQ(StatusCode::OK_200, res->status);
  5606. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5607. ASSERT_EQ("coder", res->body);
  5608. }
  5609. TEST_F(ServerTest, PutMethod3) {
  5610. auto res = cli_.Get("/person/john3");
  5611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5612. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5613. Params params;
  5614. params.emplace("name", "john3");
  5615. params.emplace("note", "coder");
  5616. res = cli_.Put("/person", params);
  5617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5618. ASSERT_EQ(StatusCode::OK_200, res->status);
  5619. res = cli_.Get("/person/john3");
  5620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5621. ASSERT_EQ(StatusCode::OK_200, res->status);
  5622. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5623. ASSERT_EQ("coder", res->body);
  5624. }
  5625. TEST_F(ServerTest, DeleteMethod1) {
  5626. auto res = cli_.Get("/person/john4");
  5627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5628. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5629. Params params;
  5630. params.emplace("name", "john4");
  5631. params.emplace("note", "coder");
  5632. res = cli_.Post("/person", params);
  5633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5634. ASSERT_EQ(StatusCode::OK_200, res->status);
  5635. res = cli_.Get("/person/john4");
  5636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5637. ASSERT_EQ(StatusCode::OK_200, res->status);
  5638. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5639. ASSERT_EQ("coder", res->body);
  5640. Params delete_params;
  5641. delete_params.emplace("name", "john4");
  5642. res = cli_.Delete("/person", delete_params);
  5643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5644. ASSERT_EQ(StatusCode::OK_200, res->status);
  5645. ASSERT_EQ("DELETED", res->body);
  5646. res = cli_.Get("/person/john4");
  5647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5648. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5649. }
  5650. TEST_F(ServerTest, DeleteMethod2) {
  5651. auto res = cli_.Get("/person/john5");
  5652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5653. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5654. Params params;
  5655. params.emplace("name", "john5");
  5656. params.emplace("note", "developer");
  5657. res = cli_.Post("/person", params);
  5658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5659. ASSERT_EQ(StatusCode::OK_200, res->status);
  5660. res = cli_.Get("/person/john5");
  5661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5662. ASSERT_EQ(StatusCode::OK_200, res->status);
  5663. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5664. ASSERT_EQ("developer", res->body);
  5665. Params delete_params;
  5666. delete_params.emplace("name", "john5");
  5667. Headers headers;
  5668. headers.emplace("Custom-Header", "test-value");
  5669. res = cli_.Delete("/person", headers, delete_params);
  5670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5671. ASSERT_EQ(StatusCode::OK_200, res->status);
  5672. ASSERT_EQ("DELETED", res->body);
  5673. res = cli_.Get("/person/john5");
  5674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5675. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5676. }
  5677. TEST_F(ServerTest, DeleteMethod3) {
  5678. auto res = cli_.Get("/person/john6");
  5679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5680. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5681. Params params;
  5682. params.emplace("name", "john6");
  5683. params.emplace("note", "tester");
  5684. res = cli_.Post("/person", params);
  5685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5686. ASSERT_EQ(StatusCode::OK_200, res->status);
  5687. res = cli_.Get("/person/john6");
  5688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5689. ASSERT_EQ(StatusCode::OK_200, res->status);
  5690. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5691. ASSERT_EQ("tester", res->body);
  5692. Params delete_params;
  5693. delete_params.emplace("name", "john6");
  5694. Headers headers;
  5695. headers.emplace("Custom-Header", "test-value");
  5696. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5698. ASSERT_EQ(StatusCode::OK_200, res->status);
  5699. ASSERT_EQ("DELETED", res->body);
  5700. res = cli_.Get("/person/john6");
  5701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5702. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5703. }
  5704. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5705. Params params;
  5706. params.emplace("json", JSON_DATA);
  5707. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5709. ASSERT_EQ(StatusCode::OK_200, res->status);
  5710. ASSERT_EQ(JSON_DATA, res->body);
  5711. }
  5712. TEST_F(ServerTest, PostEmptyContent) {
  5713. auto res = cli_.Post("/empty", "", "text/plain");
  5714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5715. ASSERT_EQ(StatusCode::OK_200, res->status);
  5716. ASSERT_EQ("empty", res->body);
  5717. }
  5718. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5719. auto res = cli_.Post("/empty-no-content-type");
  5720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5721. ASSERT_EQ(StatusCode::OK_200, res->status);
  5722. ASSERT_EQ("empty-no-content-type", res->body);
  5723. }
  5724. TEST_F(ServerTest, PostPathOnly) {
  5725. auto res = cli_.Post("/path-only");
  5726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5727. ASSERT_EQ(StatusCode::OK_200, res->status);
  5728. ASSERT_EQ("path-only", res->body);
  5729. }
  5730. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5731. auto res = cli_.Post("/path-headers-only",
  5732. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5734. ASSERT_EQ(StatusCode::OK_200, res->status);
  5735. ASSERT_EQ("path-headers-only", res->body);
  5736. }
  5737. TEST_F(ServerTest, PostLarge) {
  5738. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5740. ASSERT_EQ(StatusCode::OK_200, res->status);
  5741. EXPECT_EQ(LARGE_DATA, res->body);
  5742. }
  5743. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5744. auto res = cli_.Put("/empty-no-content-type");
  5745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5746. ASSERT_EQ(StatusCode::OK_200, res->status);
  5747. ASSERT_EQ("empty-no-content-type", res->body);
  5748. }
  5749. TEST_F(ServerTest, GetMethodDir) {
  5750. auto res = cli_.Get("/dir/");
  5751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5752. EXPECT_EQ(StatusCode::OK_200, res->status);
  5753. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5754. auto body = R"(<html>
  5755. <head>
  5756. </head>
  5757. <body>
  5758. <a href="/dir/test.html">Test</a>
  5759. <a href="/hi">hi</a>
  5760. </body>
  5761. </html>
  5762. )";
  5763. EXPECT_EQ(body, res->body);
  5764. }
  5765. TEST_F(ServerTest, GetMethodDirTest) {
  5766. auto res = cli_.Get("/dir/test.html");
  5767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5768. EXPECT_EQ(StatusCode::OK_200, res->status);
  5769. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5770. EXPECT_EQ("test.html", res->body);
  5771. }
  5772. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5773. auto res = cli_.Get("/dir/../dir/test.html");
  5774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5775. EXPECT_EQ(StatusCode::OK_200, res->status);
  5776. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5777. EXPECT_EQ("test.html", res->body);
  5778. }
  5779. TEST_F(ServerTest, GetMethodInvalidPath) {
  5780. auto res = cli_.Get("/dir/../test.html");
  5781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5782. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5783. }
  5784. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5785. auto res = cli_.Get("/../www/dir/test.html");
  5786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5787. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5788. }
  5789. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5790. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5792. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5793. }
  5794. TEST_F(ServerTest, GetMethodDirMountTest) {
  5795. auto res = cli_.Get("/mount/dir/test.html");
  5796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5797. EXPECT_EQ(StatusCode::OK_200, res->status);
  5798. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5799. EXPECT_EQ("test.html", res->body);
  5800. }
  5801. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5802. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5804. EXPECT_EQ(StatusCode::OK_200, res->status);
  5805. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5806. EXPECT_EQ("test.html", res->body);
  5807. }
  5808. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5809. auto res = cli_.Get("/mount/dir/../test.html");
  5810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5811. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5812. }
  5813. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5814. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5816. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5817. }
  5818. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5819. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5821. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5822. }
  5823. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5824. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5826. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5827. }
  5828. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5829. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5831. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5832. }
  5833. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  5834. auto res = cli_.Get("/mount/dir");
  5835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5836. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5837. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5838. }
  5839. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  5840. auto res = cli_.Get("//dir");
  5841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5842. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5843. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5844. }
  5845. TEST_F(ServerTest, PostMethod303) {
  5846. auto res = cli_.Post("/1", "body", "text/plain");
  5847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5848. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5849. EXPECT_EQ("/2", res->get_header_value("Location"));
  5850. }
  5851. TEST_F(ServerTest, PostMethod303Redirect) {
  5852. cli_.set_follow_location(true);
  5853. auto res = cli_.Post("/1", "body", "text/plain");
  5854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5855. EXPECT_EQ(StatusCode::OK_200, res->status);
  5856. EXPECT_EQ("redirected.", res->body);
  5857. EXPECT_EQ("/2", res->location);
  5858. }
  5859. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5860. auto res = cli_.Get("/dir/test.abcde");
  5861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5862. EXPECT_EQ(StatusCode::OK_200, res->status);
  5863. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5864. EXPECT_EQ("abcde", res->body);
  5865. }
  5866. TEST_F(ServerTest, StaticFileRange) {
  5867. auto res =
  5868. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5870. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5871. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5872. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5873. EXPECT_EQ(true, res->has_header("Content-Range"));
  5874. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5875. EXPECT_EQ(std::string("cd"), res->body);
  5876. }
  5877. TEST_F(ServerTest, StaticFileRanges) {
  5878. auto res = cli_.Get("/dir/test.abcde",
  5879. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5881. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5882. EXPECT_TRUE(
  5883. res->get_header_value("Content-Type")
  5884. .find(
  5885. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5886. 0);
  5887. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5888. }
  5889. TEST_F(ServerTest, StaticFileRangeHead) {
  5890. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5892. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5893. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5894. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5895. EXPECT_EQ(true, res->has_header("Content-Range"));
  5896. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5897. }
  5898. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5899. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5901. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5902. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5903. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5904. EXPECT_EQ(true, res->has_header("Content-Range"));
  5905. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5906. res->get_header_value("Content-Range"));
  5907. EXPECT_EQ("LAST\n", res->body);
  5908. }
  5909. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5910. auto res =
  5911. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5913. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5914. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5915. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5916. EXPECT_EQ(true, res->has_header("Content-Range"));
  5917. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5918. }
  5919. TEST_F(ServerTest, StaticFileBigFile) {
  5920. auto res = cli_.Get("/dir/1MB.txt");
  5921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5922. EXPECT_EQ(StatusCode::OK_200, res->status);
  5923. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5924. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5925. }
  5926. TEST_F(ServerTest, InvalidBaseDirMount) {
  5927. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5928. }
  5929. TEST_F(ServerTest, Binary) {
  5930. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5931. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5932. "application/octet-stream");
  5933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5934. ASSERT_EQ(StatusCode::OK_200, res->status);
  5935. ASSERT_EQ(4U, res->body.size());
  5936. res = cli_.Put("/binary", binary.data(), binary.size(),
  5937. "application/octet-stream");
  5938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5939. ASSERT_EQ(StatusCode::OK_200, res->status);
  5940. ASSERT_EQ(4U, res->body.size());
  5941. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5942. "application/octet-stream");
  5943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5944. ASSERT_EQ(StatusCode::OK_200, res->status);
  5945. ASSERT_EQ(4U, res->body.size());
  5946. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5947. "application/octet-stream");
  5948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5949. ASSERT_EQ(StatusCode::OK_200, res->status);
  5950. ASSERT_EQ(4U, res->body.size());
  5951. }
  5952. TEST_F(ServerTest, BinaryString) {
  5953. auto binary = std::string("\x00\x01\x02\x03", 4);
  5954. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5956. ASSERT_EQ(StatusCode::OK_200, res->status);
  5957. ASSERT_EQ(4U, res->body.size());
  5958. res = cli_.Put("/binary", binary, "application/octet-stream");
  5959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5960. ASSERT_EQ(StatusCode::OK_200, res->status);
  5961. ASSERT_EQ(4U, res->body.size());
  5962. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5964. ASSERT_EQ(StatusCode::OK_200, res->status);
  5965. ASSERT_EQ(4U, res->body.size());
  5966. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5968. ASSERT_EQ(StatusCode::OK_200, res->status);
  5969. ASSERT_EQ(4U, res->body.size());
  5970. }
  5971. TEST_F(ServerTest, EmptyRequest) {
  5972. auto res = cli_.Get("");
  5973. ASSERT_TRUE(!res);
  5974. EXPECT_EQ(Error::Connection, res.error());
  5975. }
  5976. TEST_F(ServerTest, LongRequest) {
  5977. std::string request;
  5978. for (size_t i = 0; i < 545; i++) {
  5979. request += "/TooLongRequest";
  5980. }
  5981. request += "OK";
  5982. auto res = cli_.Get(request.c_str());
  5983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5984. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5985. }
  5986. TEST_F(ServerTest, TooLongRequest) {
  5987. std::string request;
  5988. for (size_t i = 0; i < 546; i++) {
  5989. request += "/TooLongRequest";
  5990. }
  5991. request += "_NG";
  5992. auto start = std::chrono::high_resolution_clock::now();
  5993. cli_.set_keep_alive(true);
  5994. auto res = cli_.Get(request.c_str());
  5995. auto end = std::chrono::high_resolution_clock::now();
  5996. auto elapsed =
  5997. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5998. .count();
  5999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6000. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6001. EXPECT_LE(elapsed, 1000);
  6002. EXPECT_EQ("close", res->get_header_value("Connection"));
  6003. EXPECT_FALSE(cli_.is_socket_open());
  6004. }
  6005. TEST_F(ServerTest, AlmostTooLongRequest) {
  6006. // test for #2046 - URI length check shouldn't include other content on req
  6007. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6008. // leading /, space, HTTP/1.1)
  6009. std::string request =
  6010. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6011. auto res = cli_.Get(request.c_str());
  6012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6013. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6014. }
  6015. TEST_F(ServerTest, LongHeader) {
  6016. Request req;
  6017. req.method = "GET";
  6018. req.path = "/hi";
  6019. std::string host_and_port;
  6020. host_and_port += HOST;
  6021. host_and_port += ":";
  6022. host_and_port += std::to_string(PORT);
  6023. req.headers.emplace("Host", host_and_port.c_str());
  6024. req.headers.emplace("Accept", "*/*");
  6025. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6026. req.headers.emplace(
  6027. "Header-Name",
  6028. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6029. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6030. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6031. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6032. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6033. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6034. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6035. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6036. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6037. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6038. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6039. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6040. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6041. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6042. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6043. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6044. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6045. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6046. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6047. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6048. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6049. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6050. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6051. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6052. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6053. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6054. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6055. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6056. "@@@@@@@@@@@@@@@@");
  6057. auto res = std::make_shared<Response>();
  6058. auto error = Error::Success;
  6059. auto ret = cli_.send(req, *res, error);
  6060. ASSERT_TRUE(ret);
  6061. EXPECT_EQ(StatusCode::OK_200, res->status);
  6062. }
  6063. TEST_F(ServerTest, LongQueryValue) {
  6064. auto start = std::chrono::high_resolution_clock::now();
  6065. cli_.set_keep_alive(true);
  6066. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6067. auto end = std::chrono::high_resolution_clock::now();
  6068. auto elapsed =
  6069. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6070. .count();
  6071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6072. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6073. EXPECT_LE(elapsed, 1000);
  6074. EXPECT_EQ("close", res->get_header_value("Connection"));
  6075. EXPECT_FALSE(cli_.is_socket_open());
  6076. }
  6077. TEST_F(ServerTest, TooLongQueryValue) {
  6078. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6079. ASSERT_FALSE(res);
  6080. EXPECT_EQ(Error::Read, res.error());
  6081. }
  6082. TEST_F(ServerTest, TooLongHeader) {
  6083. Request req;
  6084. req.method = "GET";
  6085. req.path = "/hi";
  6086. std::string host_and_port;
  6087. host_and_port += HOST;
  6088. host_and_port += ":";
  6089. host_and_port += std::to_string(PORT);
  6090. req.headers.emplace("Host", host_and_port.c_str());
  6091. req.headers.emplace("Accept", "*/*");
  6092. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6093. req.headers.emplace(
  6094. "Header-Name",
  6095. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6096. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6097. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6098. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6099. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6100. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6101. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6102. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6103. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6104. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6105. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6106. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6107. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6108. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6109. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6110. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6111. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6112. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6113. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6114. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6115. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6116. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6117. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6118. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6119. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6120. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6121. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6122. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6123. "@@@@@@@@@@@@@@@@@");
  6124. auto res = std::make_shared<Response>();
  6125. auto error = Error::Success;
  6126. auto ret = cli_.send(req, *res, error);
  6127. ASSERT_TRUE(ret);
  6128. EXPECT_EQ(StatusCode::OK_200, res->status);
  6129. }
  6130. TEST_F(ServerTest, HeaderCountAtLimit) {
  6131. // Test with headers just under the 100 limit
  6132. httplib::Headers headers;
  6133. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6134. // This should keep us just under the 100 header limit
  6135. for (int i = 0; i < 95; i++) {
  6136. std::string name = "X-Test-Header-" + std::to_string(i);
  6137. std::string value = "value" + std::to_string(i);
  6138. headers.emplace(name, value);
  6139. }
  6140. // This should work fine as we're under the limit
  6141. auto res = cli_.Get("/hi", headers);
  6142. EXPECT_TRUE(res);
  6143. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6144. }
  6145. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6146. // Test with many headers to exceed the 100 limit
  6147. httplib::Headers headers;
  6148. // Add 150 headers to definitely exceed the 100 limit
  6149. for (int i = 0; i < 150; i++) {
  6150. std::string name = "X-Test-Header-" + std::to_string(i);
  6151. std::string value = "value" + std::to_string(i);
  6152. headers.emplace(name, value);
  6153. }
  6154. // This should fail due to exceeding header count limit
  6155. cli_.set_keep_alive(true);
  6156. auto res = cli_.Get("/hi", headers);
  6157. // The server should respond with 400 Bad Request
  6158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6159. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6160. EXPECT_EQ("close", res->get_header_value("Connection"));
  6161. EXPECT_FALSE(cli_.is_socket_open());
  6162. }
  6163. TEST_F(ServerTest, PercentEncoding) {
  6164. auto res = cli_.Get("/e%6edwith%");
  6165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6166. EXPECT_EQ(StatusCode::OK_200, res->status);
  6167. }
  6168. TEST_F(ServerTest, PercentEncodingUnicode) {
  6169. auto res = cli_.Get("/e%u006edwith%");
  6170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6171. EXPECT_EQ(StatusCode::OK_200, res->status);
  6172. }
  6173. TEST_F(ServerTest, InvalidPercentEncoding) {
  6174. auto res = cli_.Get("/%endwith%");
  6175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6176. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6177. }
  6178. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6179. auto res = cli_.Get("/%uendwith%");
  6180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6181. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6182. }
  6183. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6184. auto res = cli_.Get("/hello?aaa=bbb%");
  6185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6186. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6187. }
  6188. TEST_F(ServerTest, PlusSignEncoding) {
  6189. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6191. EXPECT_EQ(StatusCode::OK_200, res->status);
  6192. EXPECT_EQ("a +b", res->body);
  6193. }
  6194. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6195. // This test simulates a potential DoS attack using many headers
  6196. // to verify our security fix prevents memory exhaustion
  6197. httplib::Headers attack_headers;
  6198. // Attempt to add many headers like an attacker would (200 headers to far
  6199. // exceed limit)
  6200. for (int i = 0; i < 200; i++) {
  6201. std::string name = "X-Attack-Header-" + std::to_string(i);
  6202. std::string value = "attack_payload_" + std::to_string(i);
  6203. attack_headers.emplace(name, value);
  6204. }
  6205. // Try to POST with excessive headers
  6206. cli_.set_keep_alive(true);
  6207. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6208. // Should either fail or return 400 Bad Request due to security limit
  6209. if (res) {
  6210. // If we get a response, it should be 400 Bad Request
  6211. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6212. EXPECT_EQ("close", res->get_header_value("Connection"));
  6213. }
  6214. EXPECT_FALSE(cli_.is_socket_open());
  6215. }
  6216. TEST_F(ServerTest, MultipartFormData) {
  6217. UploadFormDataItems items = {
  6218. {"text1", "text default", "", ""},
  6219. {"text2", "aωb", "", ""},
  6220. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6221. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6222. {"file3", "", "", "application/octet-stream"},
  6223. {"file4", "", "", " application/json tmp-string "}};
  6224. auto res = cli_.Post("/multipart", items);
  6225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6226. EXPECT_EQ(StatusCode::OK_200, res->status);
  6227. }
  6228. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6229. UploadFormDataItems items = {
  6230. {"text", "default text", "", ""},
  6231. {"multi_text1", "aaaaa", "", ""},
  6232. {"multi_text1", "bbbbb", "", ""},
  6233. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6234. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6235. "application/json"},
  6236. };
  6237. auto res = cli_.Post("/multipart/multi_file_values", items);
  6238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6239. EXPECT_EQ(StatusCode::OK_200, res->status);
  6240. }
  6241. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6242. auto res = cli_.Get("/hi");
  6243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6244. EXPECT_EQ(StatusCode::OK_200, res->status);
  6245. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6246. EXPECT_EQ("Hello World!", res->body);
  6247. }
  6248. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6249. Request req;
  6250. req.method = "POST";
  6251. req.path = "/chunked";
  6252. std::string host_and_port;
  6253. host_and_port += HOST;
  6254. host_and_port += ":";
  6255. host_and_port += std::to_string(PORT);
  6256. req.headers.emplace("Host", host_and_port.c_str());
  6257. req.headers.emplace("Accept", "*/*");
  6258. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6259. req.headers.emplace("Content-Type", "text/plain");
  6260. req.headers.emplace("Content-Length", "0");
  6261. req.headers.emplace(
  6262. "Transfer-Encoding",
  6263. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6264. // Client does not chunk, so make a chunked body manually.
  6265. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6266. auto res = std::make_shared<Response>();
  6267. auto error = Error::Success;
  6268. auto ret = cli_.send(req, *res, error);
  6269. ASSERT_TRUE(ret);
  6270. EXPECT_EQ(StatusCode::OK_200, res->status);
  6271. }
  6272. template <typename ClientT>
  6273. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6274. int expected_status) {
  6275. Request req;
  6276. req.method = "POST";
  6277. req.path = "/chunked";
  6278. std::string host_and_port;
  6279. host_and_port += HOST;
  6280. host_and_port += ":";
  6281. host_and_port += std::to_string(PORT);
  6282. req.headers.emplace("Host", host_and_port.c_str());
  6283. req.headers.emplace("Content-Length", "0");
  6284. req.headers.emplace("Transfer-Encoding", "chunked");
  6285. req.body = body;
  6286. auto res = std::make_shared<Response>();
  6287. auto error = Error::Success;
  6288. ASSERT_TRUE(cli.send(req, *res, error));
  6289. EXPECT_EQ(expected_status, res->status);
  6290. }
  6291. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6292. // rather than treat them as valid lengths.
  6293. template <typename ClientT>
  6294. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6295. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6296. }
  6297. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6298. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6299. }
  6300. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6301. expect_chunked_body_rejected(
  6302. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6303. }
  6304. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6305. // chunk-size line carries no CR, LF or other control character ahead of its
  6306. // terminator. Such a line must be refused rather than read as extension text.
  6307. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6308. expect_chunked_body_rejected(
  6309. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6310. }
  6311. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6312. expect_chunked_body_rejected(
  6313. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6314. }
  6315. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6316. expect_chunked_body_rejected(
  6317. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6318. }
  6319. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6320. // The literal stays split: a hex escape consumes every hex digit that
  6321. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6322. expect_chunked_body_rejected(
  6323. cli_, "4;a\x01"
  6324. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6325. }
  6326. TEST_F(ServerTest, AcceptsChunkExtension) {
  6327. expect_chunked_body_status(cli_,
  6328. "4;name=value\r\ndech\r\n"
  6329. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6330. "0;last\r\n\r\n",
  6331. StatusCode::OK_200);
  6332. }
  6333. TEST_F(ServerTest, GetStreamed2) {
  6334. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6336. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6337. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6338. EXPECT_EQ(true, res->has_header("Content-Range"));
  6339. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6340. EXPECT_EQ(std::string("ab"), res->body);
  6341. }
  6342. TEST_F(ServerTest, GetStreamed) {
  6343. auto res = cli_.Get("/streamed");
  6344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6345. EXPECT_EQ(StatusCode::OK_200, res->status);
  6346. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6347. EXPECT_EQ(std::string("aaabbb"), res->body);
  6348. }
  6349. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6350. auto res = cli_.Get("/streamed-without-length",
  6351. Headers{make_range_header({{0, -1}})});
  6352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6353. EXPECT_EQ(StatusCode::OK_200, res->status);
  6354. EXPECT_EQ(false, res->has_header("Content-Length"));
  6355. EXPECT_EQ(false, res->has_header("Content-Range"));
  6356. EXPECT_EQ(std::string("abcdefg"), res->body);
  6357. }
  6358. TEST_F(ServerTest, GetStreamedWithRange1) {
  6359. auto res =
  6360. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6362. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6363. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6364. EXPECT_EQ(true, res->has_header("Content-Range"));
  6365. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6366. EXPECT_EQ(std::string("def"), res->body);
  6367. }
  6368. TEST_F(ServerTest, GetStreamedWithRange2) {
  6369. auto res =
  6370. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6372. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6373. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6374. EXPECT_EQ(true, res->has_header("Content-Range"));
  6375. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6376. EXPECT_EQ(std::string("bcdefg"), res->body);
  6377. }
  6378. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6379. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6381. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6382. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6383. EXPECT_EQ(true, res->has_header("Content-Range"));
  6384. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6385. EXPECT_EQ(std::string("efg"), res->body);
  6386. }
  6387. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6388. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6389. // the entire representation.
  6390. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6391. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6393. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6394. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6395. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6396. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6397. }
  6398. }
  6399. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6400. auto res =
  6401. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6403. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6404. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6405. EXPECT_EQ(false, res->has_header("Content-Range"));
  6406. EXPECT_EQ(0U, res->body.size());
  6407. }
  6408. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6409. // Only a 206 is served as a partial representation. Under any other status
  6410. // `apply_ranges()` reported the full content length, so the body must match
  6411. // that header, and the content provider must never be asked for an offset
  6412. // outside the representation.
  6413. auto check = [&](int status, const char *range) {
  6414. auto path =
  6415. std::string("/streamed-with-range?status=") + std::to_string(status);
  6416. auto ctx = path + " Range: " + range;
  6417. auto res = cli_.Get(path, Headers{{"Range", range}});
  6418. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6419. EXPECT_EQ(status, res->status) << ctx;
  6420. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6421. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6422. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6423. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6424. };
  6425. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6426. check(403, "bytes=3-5");
  6427. // The offset is far past the representation.
  6428. check(403, "bytes=100000-100200");
  6429. // `first_pos` is still -1 here, and the bounds asserts in
  6430. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6431. check(403, "bytes=-3");
  6432. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6433. // multipart branch would have written one that is empty.
  6434. check(403, "bytes=1-2, 4-5");
  6435. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6436. // covers the whole representation.
  6437. check(200, "bytes=3-5");
  6438. check(200, "bytes=1-2, 4-5");
  6439. }
  6440. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6441. auto res =
  6442. cli_.Get("/streamed-with-range",
  6443. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6444. "92233720368547758079223372036854775807"}});
  6445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6446. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6447. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6448. EXPECT_EQ(false, res->has_header("Content-Range"));
  6449. EXPECT_EQ(0U, res->body.size());
  6450. }
  6451. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6452. auto res = cli_.Get(
  6453. "/with-range",
  6454. Headers{{"Range",
  6455. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6456. {"Accept-Encoding", ""}});
  6457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6458. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6459. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6460. EXPECT_EQ(true, res->has_header("Content-Range"));
  6461. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6462. EXPECT_EQ(std::string("abcdefg"), res->body);
  6463. }
  6464. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6465. auto res = cli_.Get("/with-range", Headers{
  6466. {"Range", "bytes=0-"},
  6467. {"Accept-Encoding", ""},
  6468. });
  6469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6470. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6471. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6472. EXPECT_EQ(true, res->has_header("Content-Range"));
  6473. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6474. EXPECT_EQ(std::string("abcdefg"), res->body);
  6475. }
  6476. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6477. auto res = cli_.Get("/streamed-with-range",
  6478. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6480. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6481. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6482. EXPECT_EQ(false, res->has_header("Content-Range"));
  6483. EXPECT_EQ(267U, res->body.size());
  6484. // Check that both range contents are present
  6485. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6486. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6487. // Check that Content-Range headers are present for both ranges
  6488. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6489. std::string::npos);
  6490. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6491. std::string::npos);
  6492. }
  6493. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6494. Ranges ranges;
  6495. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6496. ranges.emplace_back(0, -1);
  6497. }
  6498. auto res = cli_.Get("/streamed-with-range?error",
  6499. Headers{{make_range_header(ranges)}});
  6500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6501. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6502. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6503. EXPECT_EQ(false, res->has_header("Content-Range"));
  6504. EXPECT_EQ(0U, res->body.size());
  6505. }
  6506. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6507. auto res = cli_.Get("/streamed-with-range",
  6508. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6510. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6511. EXPECT_EQ(5U, res->body.size());
  6512. // Check that overlapping ranges are coalesced into a single range
  6513. EXPECT_EQ("bcdef", res->body);
  6514. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6515. // Should be single range, not multipart
  6516. EXPECT_TRUE(res->has_header("Content-Range"));
  6517. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6518. }
  6519. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6520. auto res = cli_.Get("/streamed-with-range",
  6521. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6523. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6524. EXPECT_EQ(268U, res->body.size());
  6525. // Check that both range contents are present
  6526. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6527. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6528. // Check that Content-Range headers are present for both ranges
  6529. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6530. std::string::npos);
  6531. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6532. std::string::npos);
  6533. }
  6534. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6535. auto res = cli_.Get("/streamed-with-range",
  6536. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6538. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6539. EXPECT_EQ(269U, res->body.size());
  6540. // Check that both duplicate range contents are present
  6541. size_t first_abc = res->body.find("abc\r\n");
  6542. EXPECT_TRUE(first_abc != std::string::npos);
  6543. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6544. EXPECT_TRUE(second_abc != std::string::npos);
  6545. // Check that Content-Range headers are present for both ranges
  6546. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6547. EXPECT_TRUE(first_range != std::string::npos);
  6548. size_t second_range =
  6549. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6550. EXPECT_TRUE(second_range != std::string::npos);
  6551. }
  6552. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6553. auto res =
  6554. cli_.Get("/streamed-with-range?error",
  6555. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6557. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6558. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6559. EXPECT_EQ(false, res->has_header("Content-Range"));
  6560. EXPECT_EQ(0U, res->body.size());
  6561. }
  6562. TEST_F(ServerTest, GetStreamedEndless) {
  6563. uint64_t offset = 0;
  6564. auto res = cli_.Get("/streamed-cancel",
  6565. [&](const char * /*data*/, uint64_t data_length) {
  6566. if (offset < 100) {
  6567. offset += data_length;
  6568. return true;
  6569. }
  6570. return false;
  6571. });
  6572. ASSERT_TRUE(!res);
  6573. EXPECT_EQ(Error::Canceled, res.error());
  6574. }
  6575. TEST_F(ServerTest, ClientStop) {
  6576. std::atomic_size_t count{4};
  6577. std::vector<std::thread> threads;
  6578. for (auto i = count.load(); i != 0; --i) {
  6579. threads.emplace_back([&]() {
  6580. auto res = cli_.Get("/streamed-cancel",
  6581. [&](const char *, uint64_t) { return true; });
  6582. --count;
  6583. ASSERT_TRUE(!res);
  6584. EXPECT_TRUE(res.error() == Error::Canceled ||
  6585. res.error() == Error::Read || res.error() == Error::Write);
  6586. });
  6587. }
  6588. std::this_thread::sleep_for(std::chrono::seconds(2));
  6589. while (count != 0) {
  6590. cli_.stop();
  6591. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6592. }
  6593. for (auto &t : threads) {
  6594. t.join();
  6595. }
  6596. }
  6597. TEST_F(ServerTest, GetWithRange1) {
  6598. auto res = cli_.Get("/with-range", Headers{
  6599. make_range_header({{3, 5}}),
  6600. {"Accept-Encoding", ""},
  6601. });
  6602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6603. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6604. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6605. EXPECT_EQ(true, res->has_header("Content-Range"));
  6606. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6607. EXPECT_EQ(std::string("def"), res->body);
  6608. }
  6609. TEST_F(ServerTest, GetWithRange2) {
  6610. auto res = cli_.Get("/with-range", Headers{
  6611. make_range_header({{1, -1}}),
  6612. {"Accept-Encoding", ""},
  6613. });
  6614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6615. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6616. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6617. EXPECT_EQ(true, res->has_header("Content-Range"));
  6618. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6619. EXPECT_EQ(std::string("bcdefg"), res->body);
  6620. }
  6621. TEST_F(ServerTest, GetWithRange3) {
  6622. auto res = cli_.Get("/with-range", Headers{
  6623. make_range_header({{0, 0}}),
  6624. {"Accept-Encoding", ""},
  6625. });
  6626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6627. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6628. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6629. EXPECT_EQ(true, res->has_header("Content-Range"));
  6630. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6631. EXPECT_EQ(std::string("a"), res->body);
  6632. }
  6633. TEST_F(ServerTest, GetWithRange4) {
  6634. auto res = cli_.Get("/with-range", Headers{
  6635. make_range_header({{-1, 2}}),
  6636. {"Accept-Encoding", ""},
  6637. });
  6638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6639. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6640. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6641. EXPECT_EQ(true, res->has_header("Content-Range"));
  6642. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6643. EXPECT_EQ(std::string("fg"), res->body);
  6644. }
  6645. TEST_F(ServerTest, GetWithRange5) {
  6646. auto res = cli_.Get("/with-range", Headers{
  6647. make_range_header({{0, 5}}),
  6648. {"Accept-Encoding", ""},
  6649. });
  6650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6651. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6652. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6653. EXPECT_EQ(true, res->has_header("Content-Range"));
  6654. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6655. EXPECT_EQ(std::string("abcdef"), res->body);
  6656. }
  6657. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6658. auto res =
  6659. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6661. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6662. }
  6663. TEST_F(ServerTest, GetWithRangeMultipart) {
  6664. auto res =
  6665. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6667. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6668. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6669. EXPECT_EQ(false, res->has_header("Content-Range"));
  6670. EXPECT_EQ(267U, res->body.size());
  6671. }
  6672. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6673. auto res = cli_.Get("/with-range",
  6674. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6676. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6677. }
  6678. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6679. auto res = cli_.Get("/with-range-customized-response",
  6680. Headers{{make_range_header({{1, 2}})}});
  6681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6682. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6683. EXPECT_EQ(true, res->has_header("Content-Length"));
  6684. EXPECT_EQ(false, res->has_header("Content-Range"));
  6685. EXPECT_EQ(JSON_DATA, res->body);
  6686. }
  6687. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6688. auto res = cli_.Get("/with-range-customized-response",
  6689. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6691. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6692. EXPECT_EQ(true, res->has_header("Content-Length"));
  6693. EXPECT_EQ(false, res->has_header("Content-Range"));
  6694. EXPECT_EQ(JSON_DATA, res->body);
  6695. }
  6696. TEST_F(ServerTest, Issue1772) {
  6697. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6699. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6700. }
  6701. TEST_F(ServerTest, Issue609) {
  6702. auto res = cli_.Delete("/issue609");
  6703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6704. EXPECT_EQ(StatusCode::OK_200, res->status);
  6705. EXPECT_EQ(std::string("ok"), res->body);
  6706. }
  6707. TEST_F(ServerTest, GetStreamedChunked) {
  6708. auto res = cli_.Get("/streamed-chunked");
  6709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6710. EXPECT_EQ(StatusCode::OK_200, res->status);
  6711. EXPECT_EQ(std::string("123456789"), res->body);
  6712. }
  6713. TEST_F(ServerTest, GetStreamedChunked2) {
  6714. auto res = cli_.Get("/streamed-chunked2");
  6715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6716. EXPECT_EQ(StatusCode::OK_200, res->status);
  6717. EXPECT_EQ(std::string("123456789"), res->body);
  6718. }
  6719. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6720. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6722. EXPECT_EQ(StatusCode::OK_200, res->status);
  6723. EXPECT_EQ(std::string("123456789"), res->body);
  6724. EXPECT_TRUE(res->has_header("Trailer"));
  6725. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6726. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6727. // Trailers are now stored separately from headers (security fix)
  6728. EXPECT_EQ(2U, res->trailers.size());
  6729. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6730. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6731. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6732. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6733. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6734. // Verify trailers are NOT in headers (security verification)
  6735. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6736. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6737. }
  6738. TEST_F(ServerTest, LargeChunkedPost) {
  6739. Request req;
  6740. req.method = "POST";
  6741. req.path = "/large-chunked";
  6742. std::string host_and_port;
  6743. host_and_port += HOST;
  6744. host_and_port += ":";
  6745. host_and_port += std::to_string(PORT);
  6746. req.headers.emplace("Host", host_and_port.c_str());
  6747. req.headers.emplace("Accept", "*/*");
  6748. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6749. req.headers.emplace("Content-Type", "text/plain");
  6750. req.headers.emplace("Content-Length", "0");
  6751. req.headers.emplace("Transfer-Encoding", "chunked");
  6752. std::string long_string(30 * 1024u, 'a');
  6753. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6754. // Attempt to make a large enough post to exceed OS buffers, to test that
  6755. // the server handles short reads if the full chunk data isn't available.
  6756. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6757. auto res = std::make_shared<Response>();
  6758. auto error = Error::Success;
  6759. auto ret = cli_.send(req, *res, error);
  6760. ASSERT_TRUE(ret);
  6761. EXPECT_EQ(StatusCode::OK_200, res->status);
  6762. }
  6763. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6764. auto res = cli_.Get("/remote_addr");
  6765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6766. EXPECT_EQ(StatusCode::OK_200, res->status);
  6767. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6768. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6769. }
  6770. TEST_F(ServerTest, GetMethodLocalAddr) {
  6771. auto res = cli_.Get("/local_addr");
  6772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6773. EXPECT_EQ(StatusCode::OK_200, res->status);
  6774. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6775. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6776. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6777. }
  6778. TEST_F(ServerTest, HTTPResponseSplitting) {
  6779. auto res = cli_.Get("/http_response_splitting");
  6780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6781. EXPECT_EQ(StatusCode::OK_200, res->status);
  6782. }
  6783. TEST_F(ServerTest, SlowRequest) {
  6784. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6785. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6786. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6787. }
  6788. #if 0
  6789. TEST_F(ServerTest, SlowPost) {
  6790. char buffer[64 * 1024];
  6791. memset(buffer, 0x42, sizeof(buffer));
  6792. auto res = cli_.Post(
  6793. "/slowpost", 64 * 1024 * 1024,
  6794. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6795. auto ret = sink.write(buffer, sizeof(buffer));
  6796. EXPECT_TRUE(ret);
  6797. return true;
  6798. },
  6799. "text/plain");
  6800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6801. EXPECT_EQ(StatusCode::OK_200, res->status);
  6802. }
  6803. TEST_F(ServerTest, SlowPostFail) {
  6804. char buffer[64 * 1024];
  6805. memset(buffer, 0x42, sizeof(buffer));
  6806. cli_.set_write_timeout(std::chrono::seconds(0));
  6807. auto res = cli_.Post(
  6808. "/slowpost", 64 * 1024 * 1024,
  6809. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6810. sink.write(buffer, sizeof(buffer));
  6811. return true;
  6812. },
  6813. "text/plain");
  6814. ASSERT_TRUE(!res);
  6815. EXPECT_EQ(Error::Write, res.error());
  6816. }
  6817. #endif
  6818. TEST_F(ServerTest, Put) {
  6819. auto res = cli_.Put("/put", "PUT", "text/plain");
  6820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6821. EXPECT_EQ(StatusCode::OK_200, res->status);
  6822. EXPECT_EQ("PUT", res->body);
  6823. }
  6824. TEST_F(ServerTest, PutWithContentProvider) {
  6825. auto res = cli_.Put(
  6826. "/put", 3,
  6827. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6828. sink.os << "PUT";
  6829. return true;
  6830. },
  6831. "text/plain");
  6832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6833. EXPECT_EQ(StatusCode::OK_200, res->status);
  6834. EXPECT_EQ("PUT", res->body);
  6835. }
  6836. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6837. auto res = cli_.Post(
  6838. "/post", 42,
  6839. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6840. return false;
  6841. },
  6842. "text/plain");
  6843. ASSERT_TRUE(!res);
  6844. EXPECT_EQ(Error::Canceled, res.error());
  6845. }
  6846. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6847. auto res = cli_.Put(
  6848. "/put",
  6849. [](size_t /*offset*/, DataSink &sink) {
  6850. sink.os << "PUT";
  6851. sink.done();
  6852. return true;
  6853. },
  6854. "text/plain");
  6855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6856. EXPECT_EQ(StatusCode::OK_200, res->status);
  6857. EXPECT_EQ("PUT", res->body);
  6858. }
  6859. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6860. auto res = cli_.Post(
  6861. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6862. "text/plain");
  6863. ASSERT_TRUE(!res);
  6864. EXPECT_EQ(Error::Canceled, res.error());
  6865. }
  6866. TEST_F(ServerTest, PostLoopBack) {
  6867. std::string body;
  6868. auto res = cli_.Post(
  6869. "/post-loopback", 9,
  6870. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6871. EXPECT_EQ(9u, length);
  6872. sink.write("123", 3);
  6873. sink.write("456", 3);
  6874. sink.write("789", 3);
  6875. return true;
  6876. },
  6877. "text/plain",
  6878. [&body](const char *data, size_t data_length) {
  6879. body.append(data, data_length);
  6880. return true;
  6881. });
  6882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6883. EXPECT_EQ(StatusCode::OK_200, res->status);
  6884. EXPECT_EQ("123456789", body);
  6885. }
  6886. TEST_F(ServerTest, PutLoopBack) {
  6887. std::string body;
  6888. auto res = cli_.Put(
  6889. "/put-loopback", 9,
  6890. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6891. EXPECT_EQ(9u, length);
  6892. sink.write("123", 3);
  6893. sink.write("456", 3);
  6894. sink.write("789", 3);
  6895. return true;
  6896. },
  6897. "text/plain",
  6898. [&body](const char *data, size_t data_length) {
  6899. body.append(data, data_length);
  6900. return true;
  6901. });
  6902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6903. EXPECT_EQ(StatusCode::OK_200, res->status);
  6904. EXPECT_EQ("123456789", body);
  6905. }
  6906. TEST_F(ServerTest, PatchLoopBack) {
  6907. std::string body;
  6908. auto res = cli_.Patch(
  6909. "/patch-loopback", 9,
  6910. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6911. EXPECT_EQ(9u, length);
  6912. sink.write("123", 3);
  6913. sink.write("456", 3);
  6914. sink.write("789", 3);
  6915. return true;
  6916. },
  6917. "text/plain",
  6918. [&body](const char *data, size_t data_length) {
  6919. body.append(data, data_length);
  6920. return true;
  6921. });
  6922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6923. EXPECT_EQ(StatusCode::OK_200, res->status);
  6924. EXPECT_EQ("123456789", body);
  6925. }
  6926. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6927. std::string body;
  6928. auto res = cli_.Post(
  6929. "/post-loopback",
  6930. [](size_t /*offset*/, DataSink &sink) {
  6931. sink.write("123", 3);
  6932. sink.write("456", 3);
  6933. sink.write("789", 3);
  6934. sink.done();
  6935. return true;
  6936. },
  6937. "text/plain",
  6938. [&body](const char *data, size_t data_length) {
  6939. body.append(data, data_length);
  6940. return true;
  6941. });
  6942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6943. EXPECT_EQ(StatusCode::OK_200, res->status);
  6944. EXPECT_EQ("123456789", body);
  6945. }
  6946. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6947. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6948. cli_.set_compress(true);
  6949. auto res = cli_.Put(
  6950. "/put", 3,
  6951. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6952. sink.os << "PUT";
  6953. return true;
  6954. },
  6955. "text/plain");
  6956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6957. EXPECT_EQ(StatusCode::OK_200, res->status);
  6958. EXPECT_EQ("PUT", res->body);
  6959. }
  6960. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6961. cli_.set_compress(true);
  6962. auto res = cli_.Post(
  6963. "/post", 42,
  6964. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6965. return false;
  6966. },
  6967. "text/plain");
  6968. ASSERT_TRUE(!res);
  6969. EXPECT_EQ(Error::Canceled, res.error());
  6970. }
  6971. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6972. cli_.set_compress(true);
  6973. auto res = cli_.Put(
  6974. "/put",
  6975. [](size_t /*offset*/, DataSink &sink) {
  6976. sink.os << "PUT";
  6977. sink.done();
  6978. return true;
  6979. },
  6980. "text/plain");
  6981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6982. EXPECT_EQ(StatusCode::OK_200, res->status);
  6983. EXPECT_EQ("PUT", res->body);
  6984. }
  6985. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6986. cli_.set_compress(true);
  6987. auto res = cli_.Post(
  6988. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6989. "text/plain");
  6990. ASSERT_TRUE(!res);
  6991. EXPECT_EQ(Error::Canceled, res.error());
  6992. }
  6993. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6994. cli_.set_compress(true);
  6995. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6997. EXPECT_EQ(StatusCode::OK_200, res->status);
  6998. EXPECT_EQ(LARGE_DATA, res->body);
  6999. }
  7000. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7001. #ifdef CPPHTTPLIB_SSL_ENABLED
  7002. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7003. Client cli(s.c_str());
  7004. cli.enable_server_certificate_verification(false);
  7005. #else
  7006. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7007. Client cli(s.c_str());
  7008. #endif
  7009. cli.set_compress(true);
  7010. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7012. EXPECT_EQ(StatusCode::OK_200, res->status);
  7013. EXPECT_EQ(LARGE_DATA, res->body);
  7014. // The compressed size should be less than a 10th of the original. May vary
  7015. // depending on the zlib library.
  7016. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7017. static_cast<uint64_t>(10 * 1024 * 1024));
  7018. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7019. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7020. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7021. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7022. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7023. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7024. #endif
  7025. }
  7026. TEST_F(ServerTest, PutContentWithDeflate) {
  7027. cli_.set_compress(false);
  7028. Headers headers;
  7029. headers.emplace("Content-Encoding", "deflate");
  7030. // PUT in deflate format:
  7031. auto res = cli_.Put("/put", headers,
  7032. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7034. EXPECT_EQ(StatusCode::OK_200, res->status);
  7035. EXPECT_EQ("PUT", res->body);
  7036. }
  7037. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7038. Headers headers;
  7039. headers.emplace("Accept-Encoding", "gzip, deflate");
  7040. auto res = cli_.Get("/streamed-chunked", headers);
  7041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7042. EXPECT_EQ(StatusCode::OK_200, res->status);
  7043. EXPECT_EQ(std::string("123456789"), res->body);
  7044. }
  7045. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7046. Headers headers;
  7047. headers.emplace("Accept-Encoding", "gzip, deflate");
  7048. auto res = cli_.Get("/streamed-chunked2", headers);
  7049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7050. EXPECT_EQ(StatusCode::OK_200, res->status);
  7051. EXPECT_EQ(std::string("123456789"), res->body);
  7052. }
  7053. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7054. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7056. EXPECT_EQ(StatusCode::OK_200, res->status);
  7057. }
  7058. TEST(GzipDecompressor, ChunkedDecompression) {
  7059. std::string data;
  7060. for (size_t i = 0; i < 32 * 1024; ++i) {
  7061. data.push_back(static_cast<char>('a' + i % 26));
  7062. }
  7063. std::string compressed_data;
  7064. {
  7065. httplib::detail::gzip_compressor compressor;
  7066. bool result = compressor.compress(
  7067. data.data(), data.size(),
  7068. /*last=*/true,
  7069. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7070. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7071. compressed_data_size);
  7072. return true;
  7073. });
  7074. ASSERT_TRUE(result);
  7075. }
  7076. std::string decompressed_data;
  7077. {
  7078. httplib::detail::gzip_decompressor decompressor;
  7079. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7080. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7081. size_t chunk_size = 130;
  7082. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7083. chunk_begin += chunk_size) {
  7084. size_t current_chunk_size =
  7085. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7086. bool result = decompressor.decompress(
  7087. compressed_data.data() + chunk_begin, current_chunk_size,
  7088. [&](const char *decompressed_data_chunk,
  7089. size_t decompressed_data_chunk_size) {
  7090. decompressed_data.insert(decompressed_data.size(),
  7091. decompressed_data_chunk,
  7092. decompressed_data_chunk_size);
  7093. return true;
  7094. });
  7095. ASSERT_TRUE(result);
  7096. }
  7097. }
  7098. ASSERT_EQ(data, decompressed_data);
  7099. }
  7100. TEST(GzipDecompressor, DeflateDecompression) {
  7101. std::string original_text = "Raw deflate without gzip";
  7102. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7103. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7104. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7105. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7106. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7107. std::string decompressed_data;
  7108. {
  7109. httplib::detail::gzip_decompressor decompressor;
  7110. bool result = decompressor.decompress(
  7111. compressed_data.data(), compressed_data.size(),
  7112. [&](const char *decompressed_data_chunk,
  7113. size_t decompressed_data_chunk_size) {
  7114. decompressed_data.insert(decompressed_data.size(),
  7115. decompressed_data_chunk,
  7116. decompressed_data_chunk_size);
  7117. return true;
  7118. });
  7119. ASSERT_TRUE(result);
  7120. }
  7121. ASSERT_EQ(original_text, decompressed_data);
  7122. }
  7123. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7124. std::string original_text = "Raw deflate without gzip";
  7125. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7126. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7127. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7128. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7129. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7130. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7131. std::string decompressed_data;
  7132. {
  7133. httplib::detail::gzip_decompressor decompressor;
  7134. bool result = decompressor.decompress(
  7135. compressed_data.data(), compressed_data.size(),
  7136. [&](const char *decompressed_data_chunk,
  7137. size_t decompressed_data_chunk_size) {
  7138. decompressed_data.insert(decompressed_data.size(),
  7139. decompressed_data_chunk,
  7140. decompressed_data_chunk_size);
  7141. return true;
  7142. });
  7143. ASSERT_TRUE(result);
  7144. }
  7145. ASSERT_EQ(original_text, decompressed_data);
  7146. }
  7147. #endif
  7148. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7149. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7150. Headers headers;
  7151. headers.emplace("Accept-Encoding", "br");
  7152. auto res = cli_.Get("/streamed-chunked", headers);
  7153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7154. EXPECT_EQ(StatusCode::OK_200, res->status);
  7155. EXPECT_EQ(std::string("123456789"), res->body);
  7156. }
  7157. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7158. Headers headers;
  7159. headers.emplace("Accept-Encoding", "br");
  7160. auto res = cli_.Get("/streamed-chunked2", headers);
  7161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7162. EXPECT_EQ(StatusCode::OK_200, res->status);
  7163. EXPECT_EQ(std::string("123456789"), res->body);
  7164. }
  7165. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7166. cli_.set_compress(true);
  7167. auto res = cli_.Put(
  7168. "/put", 3,
  7169. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7170. sink.os << "PUT";
  7171. return true;
  7172. },
  7173. "text/plain");
  7174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7175. EXPECT_EQ(StatusCode::OK_200, res->status);
  7176. EXPECT_EQ("PUT", res->body);
  7177. }
  7178. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7179. cli_.set_compress(true);
  7180. auto res = cli_.Put(
  7181. "/put",
  7182. [](size_t /*offset*/, DataSink &sink) {
  7183. sink.os << "PUT";
  7184. sink.done();
  7185. return true;
  7186. },
  7187. "text/plain");
  7188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7189. EXPECT_EQ(StatusCode::OK_200, res->status);
  7190. EXPECT_EQ("PUT", res->body);
  7191. }
  7192. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7193. cli_.set_compress(true);
  7194. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7196. EXPECT_EQ(StatusCode::OK_200, res->status);
  7197. EXPECT_EQ(LARGE_DATA, res->body);
  7198. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7199. }
  7200. #endif
  7201. TEST_F(ServerTest, Patch) {
  7202. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7204. EXPECT_EQ(StatusCode::OK_200, res->status);
  7205. EXPECT_EQ("PATCH", res->body);
  7206. }
  7207. TEST_F(ServerTest, Delete) {
  7208. auto res = cli_.Delete("/delete");
  7209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7210. EXPECT_EQ(StatusCode::OK_200, res->status);
  7211. EXPECT_EQ("DELETE", res->body);
  7212. }
  7213. TEST_F(ServerTest, DeleteContentReceiver) {
  7214. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7216. EXPECT_EQ(StatusCode::OK_200, res->status);
  7217. EXPECT_EQ("content", res->body);
  7218. }
  7219. TEST_F(ServerTest, Options) {
  7220. auto res = cli_.Options("*");
  7221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7222. EXPECT_EQ(StatusCode::OK_200, res->status);
  7223. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7224. EXPECT_TRUE(res->body.empty());
  7225. }
  7226. TEST_F(ServerTest, URL) {
  7227. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7229. EXPECT_EQ(StatusCode::OK_200, res->status);
  7230. }
  7231. TEST_F(ServerTest, ArrayParam) {
  7232. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7234. EXPECT_EQ(StatusCode::OK_200, res->status);
  7235. }
  7236. TEST_F(ServerTest, ArrayParamValues) {
  7237. auto res =
  7238. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7240. EXPECT_EQ(StatusCode::OK_200, res->status);
  7241. }
  7242. TEST_F(ServerTest, NoMultipleHeaders) {
  7243. Headers headers = {{"Content-Length", "5"}};
  7244. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7245. "text/plain");
  7246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7247. EXPECT_EQ(StatusCode::OK_200, res->status);
  7248. }
  7249. TEST_F(ServerTest, PostContentReceiver) {
  7250. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7252. ASSERT_EQ(StatusCode::OK_200, res->status);
  7253. ASSERT_EQ("content", res->body);
  7254. }
  7255. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7256. UploadFormDataItems items = {
  7257. {"text1", "text default", "", ""},
  7258. {"text2", "aωb", "", ""},
  7259. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7260. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7261. {"file3", "", "", "application/octet-stream"},
  7262. };
  7263. auto res = cli_.Post("/content_receiver", items);
  7264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7265. EXPECT_EQ(StatusCode::OK_200, res->status);
  7266. }
  7267. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7268. UploadFormDataItems items = {
  7269. {"text1", "text default", "", ""},
  7270. {"text2", "aωb", "", ""},
  7271. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7272. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7273. {"file3", "", "", "application/octet-stream"},
  7274. };
  7275. auto boundary = std::string("+++++");
  7276. std::string body;
  7277. for (const auto &item : items) {
  7278. body += "--" + boundary + "\r\n";
  7279. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7280. if (!item.filename.empty()) {
  7281. body += "; filename=\"" + item.filename + "\"";
  7282. }
  7283. body += "\r\n";
  7284. if (!item.content_type.empty()) {
  7285. body += "Content-Type: " + item.content_type + "\r\n";
  7286. }
  7287. body += "\r\n";
  7288. body += item.content + "\r\n";
  7289. }
  7290. body += "--" + boundary + "--\r\n";
  7291. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7292. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7294. EXPECT_EQ(StatusCode::OK_200, res->status);
  7295. }
  7296. TEST(MultipartFormDataTest, FieldEscaping) {
  7297. Server svr;
  7298. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7299. const ContentReader &content_reader) {
  7300. ASSERT_TRUE(req.is_multipart_form_data());
  7301. std::vector<FormData> received;
  7302. content_reader(
  7303. [&](const FormData &file) {
  7304. received.push_back(file);
  7305. return true;
  7306. },
  7307. [&](const char *data, size_t data_length) {
  7308. received.back().content.append(data, data_length);
  7309. return true;
  7310. });
  7311. // '"', CR and LF in names and filenames are escaped following the
  7312. // WHATWG HTML standard, so each part still parses as a single part
  7313. // with no injected headers. Content types get CR/LF escaped too,
  7314. // while '"' (legal there, e.g. quoted charset) is preserved.
  7315. ASSERT_EQ(4U, received.size());
  7316. EXPECT_EQ("na%22me", received[0].name);
  7317. EXPECT_EQ("quoted name", received[0].content);
  7318. EXPECT_EQ("file", received[1].name);
  7319. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7320. received[1].filename);
  7321. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7322. EXPECT_EQ("injected", received[1].content);
  7323. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7324. EXPECT_EQ("my%22file.txt", received[2].filename);
  7325. EXPECT_EQ("cr lf name", received[2].content);
  7326. EXPECT_EQ("typed", received[3].name);
  7327. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7328. received[3].content_type);
  7329. EXPECT_EQ("typed content", received[3].content);
  7330. });
  7331. auto port = svr.bind_to_any_port("localhost");
  7332. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7333. auto se = detail::scope_exit([&] {
  7334. svr.stop();
  7335. t.join();
  7336. ASSERT_FALSE(svr.is_running());
  7337. });
  7338. svr.wait_until_ready();
  7339. Client cli("localhost", port);
  7340. UploadFormDataItems items = {
  7341. {"na\"me", "quoted name", "", ""},
  7342. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7343. "application/octet-stream"},
  7344. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7345. {"typed", "typed content", "",
  7346. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7347. };
  7348. auto res = cli.Post("/post", items);
  7349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7350. EXPECT_EQ(StatusCode::OK_200, res->status);
  7351. }
  7352. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7353. const UploadFormDataItems items = {
  7354. {"name1", "Content 1", "", ""},
  7355. {"name2", "Content 2", "file2.txt", "text/plain"},
  7356. };
  7357. Server svr;
  7358. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7359. const ContentReader &content_reader) {
  7360. ASSERT_TRUE(req.is_multipart_form_data());
  7361. std::vector<FormData> received;
  7362. content_reader(
  7363. [&](const FormData &file) {
  7364. received.push_back(file);
  7365. return true;
  7366. },
  7367. [&](const char *data, size_t data_length) {
  7368. received.back().content.append(data, data_length);
  7369. return true;
  7370. });
  7371. ASSERT_EQ(2U, received.size());
  7372. EXPECT_EQ("name1", received[0].name);
  7373. EXPECT_EQ("Content 1", received[0].content);
  7374. EXPECT_EQ("name2", received[1].name);
  7375. EXPECT_EQ("Content 2", received[1].content);
  7376. EXPECT_EQ("file2.txt", received[1].filename);
  7377. EXPECT_EQ("text/plain", received[1].content_type);
  7378. });
  7379. auto port = svr.bind_to_any_port("localhost");
  7380. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7381. auto se = detail::scope_exit([&] {
  7382. svr.stop();
  7383. t.join();
  7384. ASSERT_FALSE(svr.is_running());
  7385. });
  7386. svr.wait_until_ready();
  7387. Client cli("localhost", port);
  7388. // Whole-body serialization with a generated boundary
  7389. {
  7390. MultipartFormDataWriter writer;
  7391. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7392. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7393. writer.content_type());
  7394. auto body = writer.serialize(items);
  7395. EXPECT_EQ(body.size(), writer.content_length(items));
  7396. auto res = cli.Post("/post", body, writer.content_type());
  7397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7398. EXPECT_EQ(StatusCode::OK_200, res->status);
  7399. }
  7400. // Per-part framing with a custom boundary via a content provider
  7401. {
  7402. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7403. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7404. MultipartFormDataWriter writer("custom-boundary_123");
  7405. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7406. std::string body;
  7407. for (const auto &item : items) {
  7408. body += writer.item_begin(item);
  7409. body += item.content;
  7410. body += MultipartFormDataWriter::item_end();
  7411. }
  7412. body += writer.finish();
  7413. EXPECT_EQ(body.size(), writer.content_length(items));
  7414. auto res = cli.Post(
  7415. "/post", body.size(),
  7416. [&](size_t offset, size_t length, DataSink &sink) {
  7417. sink.write(body.data() + offset, length);
  7418. return true;
  7419. },
  7420. writer.content_type());
  7421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7422. EXPECT_EQ(StatusCode::OK_200, res->status);
  7423. }
  7424. }
  7425. TEST_F(ServerTest, PostContentReceiverGzip) {
  7426. cli_.set_compress(true);
  7427. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7429. ASSERT_EQ(StatusCode::OK_200, res->status);
  7430. ASSERT_EQ("content", res->body);
  7431. }
  7432. TEST_F(ServerTest, PutContentReceiver) {
  7433. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7435. ASSERT_EQ(StatusCode::OK_200, res->status);
  7436. ASSERT_EQ("content", res->body);
  7437. }
  7438. TEST_F(ServerTest, PatchContentReceiver) {
  7439. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7441. ASSERT_EQ(StatusCode::OK_200, res->status);
  7442. ASSERT_EQ("content", res->body);
  7443. }
  7444. template <typename ClientType>
  7445. void TestWithHeadersAndContentReceiver(
  7446. ClientType &cli,
  7447. std::function<Result(ClientType &, const std::string &, const Headers &,
  7448. const std::string &, const std::string &,
  7449. ContentReceiver, DownloadProgress)>
  7450. request_func) {
  7451. Headers headers;
  7452. headers.emplace("X-Custom-Header", "test-value");
  7453. std::string received_body;
  7454. auto res = request_func(
  7455. cli, "/content_receiver", headers, "content", "application/json",
  7456. [&](const char *data, size_t data_length) {
  7457. received_body.append(data, data_length);
  7458. return true;
  7459. },
  7460. nullptr);
  7461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7462. EXPECT_EQ(StatusCode::OK_200, res->status);
  7463. EXPECT_EQ("content", received_body);
  7464. }
  7465. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7466. #ifdef CPPHTTPLIB_SSL_ENABLED
  7467. using ClientT = SSLClient;
  7468. #else
  7469. using ClientT = Client;
  7470. #endif
  7471. TestWithHeadersAndContentReceiver<ClientT>(
  7472. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7473. const std::string &body, const std::string &content_type,
  7474. ContentReceiver receiver, DownloadProgress progress) {
  7475. return cli.Post(path, headers, body, content_type, receiver, progress);
  7476. });
  7477. }
  7478. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7479. #ifdef CPPHTTPLIB_SSL_ENABLED
  7480. using ClientT = SSLClient;
  7481. #else
  7482. using ClientT = Client;
  7483. #endif
  7484. TestWithHeadersAndContentReceiver<ClientT>(
  7485. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7486. const std::string &body, const std::string &content_type,
  7487. ContentReceiver receiver, DownloadProgress progress) {
  7488. return cli.Put(path, headers, body, content_type, receiver, progress);
  7489. });
  7490. }
  7491. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7492. #ifdef CPPHTTPLIB_SSL_ENABLED
  7493. using ClientT = SSLClient;
  7494. #else
  7495. using ClientT = Client;
  7496. #endif
  7497. TestWithHeadersAndContentReceiver<ClientT>(
  7498. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7499. const std::string &body, const std::string &content_type,
  7500. ContentReceiver receiver, DownloadProgress progress) {
  7501. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7502. });
  7503. }
  7504. template <typename ClientType>
  7505. void TestWithHeadersAndContentReceiverWithProgress(
  7506. ClientType &cli,
  7507. std::function<Result(ClientType &, const std::string &, const Headers &,
  7508. const std::string &, const std::string &,
  7509. ContentReceiver, DownloadProgress)>
  7510. request_func) {
  7511. Headers headers;
  7512. headers.emplace("X-Test-Header", "progress-test");
  7513. std::string received_body;
  7514. auto progress_called = false;
  7515. auto res = request_func(
  7516. cli, "/content_receiver", headers, "content", "text/plain",
  7517. [&](const char *data, size_t data_length) {
  7518. received_body.append(data, data_length);
  7519. return true;
  7520. },
  7521. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7522. progress_called = true;
  7523. return true;
  7524. });
  7525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7526. EXPECT_EQ(StatusCode::OK_200, res->status);
  7527. EXPECT_EQ("content", received_body);
  7528. EXPECT_TRUE(progress_called);
  7529. }
  7530. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7531. #ifdef CPPHTTPLIB_SSL_ENABLED
  7532. using ClientT = SSLClient;
  7533. #else
  7534. using ClientT = Client;
  7535. #endif
  7536. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7537. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7538. const std::string &body, const std::string &content_type,
  7539. ContentReceiver receiver, DownloadProgress progress) {
  7540. return cli.Post(path, headers, body, content_type, receiver, progress);
  7541. });
  7542. }
  7543. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7544. #ifdef CPPHTTPLIB_SSL_ENABLED
  7545. using ClientT = SSLClient;
  7546. #else
  7547. using ClientT = Client;
  7548. #endif
  7549. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7550. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7551. const std::string &body, const std::string &content_type,
  7552. ContentReceiver receiver, DownloadProgress progress) {
  7553. return cli.Put(path, headers, body, content_type, receiver, progress);
  7554. });
  7555. }
  7556. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7557. #ifdef CPPHTTPLIB_SSL_ENABLED
  7558. using ClientT = SSLClient;
  7559. #else
  7560. using ClientT = Client;
  7561. #endif
  7562. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7563. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7564. const std::string &body, const std::string &content_type,
  7565. ContentReceiver receiver, DownloadProgress progress) {
  7566. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7567. });
  7568. }
  7569. template <typename ClientType>
  7570. void TestWithHeadersAndContentReceiverError(
  7571. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7572. const Headers &, const std::string &,
  7573. const std::string &, ContentReceiver)>
  7574. request_func) {
  7575. Headers headers;
  7576. headers.emplace("X-Error-Test", "true");
  7577. std::string received_body;
  7578. auto receiver_failed = false;
  7579. auto res =
  7580. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7581. [&](const char *data, size_t data_length) {
  7582. received_body.append(data, data_length);
  7583. receiver_failed = true;
  7584. return false;
  7585. });
  7586. ASSERT_FALSE(res);
  7587. EXPECT_TRUE(receiver_failed);
  7588. }
  7589. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7590. #ifdef CPPHTTPLIB_SSL_ENABLED
  7591. using ClientT = SSLClient;
  7592. #else
  7593. using ClientT = Client;
  7594. #endif
  7595. TestWithHeadersAndContentReceiverError<ClientT>(
  7596. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7597. const std::string &body, const std::string &content_type,
  7598. ContentReceiver receiver) {
  7599. return cli.Post(path, headers, body, content_type, receiver);
  7600. });
  7601. }
  7602. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7603. #ifdef CPPHTTPLIB_SSL_ENABLED
  7604. using ClientT = SSLClient;
  7605. #else
  7606. using ClientT = Client;
  7607. #endif
  7608. TestWithHeadersAndContentReceiverError<ClientT>(
  7609. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7610. const std::string &body, const std::string &content_type,
  7611. ContentReceiver receiver) {
  7612. return cli.Put(path, headers, body, content_type, receiver);
  7613. });
  7614. }
  7615. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7616. #ifdef CPPHTTPLIB_SSL_ENABLED
  7617. using ClientT = SSLClient;
  7618. #else
  7619. using ClientT = Client;
  7620. #endif
  7621. TestWithHeadersAndContentReceiverError<ClientT>(
  7622. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7623. const std::string &body, const std::string &content_type,
  7624. ContentReceiver receiver) {
  7625. return cli.Patch(path, headers, body, content_type, receiver);
  7626. });
  7627. }
  7628. TEST_F(ServerTest, PostQueryStringAndBody) {
  7629. auto res =
  7630. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7632. ASSERT_EQ(StatusCode::OK_200, res->status);
  7633. }
  7634. TEST_F(ServerTest, HTTP2Magic) {
  7635. Request req;
  7636. req.method = "PRI";
  7637. req.path = "*";
  7638. req.body = "SM";
  7639. auto res = std::make_shared<Response>();
  7640. auto error = Error::Success;
  7641. auto ret = cli_.send(req, *res, error);
  7642. ASSERT_TRUE(ret);
  7643. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7644. }
  7645. TEST_F(ServerTest, KeepAlive) {
  7646. auto res = cli_.Get("/hi");
  7647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7648. EXPECT_EQ(StatusCode::OK_200, res->status);
  7649. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7650. EXPECT_EQ("Hello World!", res->body);
  7651. res = cli_.Get("/hi");
  7652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7653. EXPECT_EQ(StatusCode::OK_200, res->status);
  7654. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7655. EXPECT_EQ("Hello World!", res->body);
  7656. res = cli_.Get("/hi");
  7657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7658. EXPECT_EQ(StatusCode::OK_200, res->status);
  7659. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7660. EXPECT_EQ("Hello World!", res->body);
  7661. res = cli_.Get("/not-exist");
  7662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7663. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7664. res = cli_.Post("/empty", "", "text/plain");
  7665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7666. EXPECT_EQ(StatusCode::OK_200, res->status);
  7667. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7668. EXPECT_EQ("empty", res->body);
  7669. EXPECT_EQ("close", res->get_header_value("Connection"));
  7670. res = cli_.Post(
  7671. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7672. "text/plain");
  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("empty", res->body);
  7677. cli_.set_keep_alive(false);
  7678. res = cli_.Get("/last-request");
  7679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7680. EXPECT_EQ(StatusCode::OK_200, res->status);
  7681. EXPECT_EQ("close", res->get_header_value("Connection"));
  7682. }
  7683. TEST_F(ServerTest, TooManyRedirect) {
  7684. cli_.set_follow_location(true);
  7685. auto res = cli_.Get("/redirect/0");
  7686. ASSERT_TRUE(!res);
  7687. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7688. }
  7689. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7690. Request req;
  7691. req.method = "FOOBAR";
  7692. req.path = "/hi";
  7693. cli_.set_keep_alive(true);
  7694. auto res = cli_.send(req);
  7695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7696. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7697. EXPECT_EQ("close", res->get_header_value("Connection"));
  7698. EXPECT_FALSE(cli_.is_socket_open());
  7699. }
  7700. TEST_F(ServerTest, CustomRouteReadsBody) {
  7701. const std::string xml =
  7702. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7703. Request req;
  7704. req.method = "PROPFIND";
  7705. req.path = "/dav/dir";
  7706. req.set_header("Depth", "1");
  7707. req.body = xml;
  7708. auto res = cli_.send(req);
  7709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7710. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7711. EXPECT_EQ(xml, res->body);
  7712. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7713. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7714. }
  7715. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7716. Request req;
  7717. req.method = "PROPFIND";
  7718. req.path = "/dav/42";
  7719. auto res = cli_.send(req);
  7720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7721. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7722. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7723. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7724. }
  7725. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7726. Request req;
  7727. req.method = "PROPFIND";
  7728. req.path = "/dav-re/123";
  7729. auto res = cli_.send(req);
  7730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7731. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7732. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7733. }
  7734. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7735. Request req;
  7736. req.method = "MKCOL";
  7737. req.path = "/dav-mkcol";
  7738. auto res = cli_.send(req);
  7739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7740. EXPECT_EQ(StatusCode::Created_201, res->status);
  7741. }
  7742. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7743. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7744. Request req;
  7745. req.method = "REPORT";
  7746. req.path = "/dav-report";
  7747. req.body = xml;
  7748. auto res = cli_.send(req);
  7749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7750. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7751. EXPECT_EQ(xml, res->body);
  7752. }
  7753. // A content reader route must fire even when the request carries no body,
  7754. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7755. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7756. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7757. Request req;
  7758. req.method = "REPORT";
  7759. req.path = "/dav-report";
  7760. auto res = cli_.send(req);
  7761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7762. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7763. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7764. }
  7765. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7766. Request req;
  7767. req.method = "PROPFIND";
  7768. req.path = "/not-dav";
  7769. auto res = cli_.send(req);
  7770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7771. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7772. }
  7773. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7774. Request req;
  7775. req.method = "UNLOCK";
  7776. req.path = "/dav/dir";
  7777. cli_.set_keep_alive(true);
  7778. auto res = cli_.send(req);
  7779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7780. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7781. EXPECT_EQ("close", res->get_header_value("Connection"));
  7782. EXPECT_FALSE(cli_.is_socket_open());
  7783. }
  7784. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7785. // The mount point serves this path, but only for GET and HEAD.
  7786. auto get_res = cli_.Get("/dir/index.html");
  7787. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7788. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7789. Request req;
  7790. req.method = "PROPFIND";
  7791. req.path = "/dir/index.html";
  7792. auto res = cli_.send(req);
  7793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7794. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7795. }
  7796. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7797. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7798. cli_.set_keep_alive(true);
  7799. for (auto i = 0; i < 2; i++) {
  7800. Request req;
  7801. req.method = "PROPFIND";
  7802. req.path = "/dav/dir";
  7803. req.body = xml;
  7804. auto res = cli_.send(req);
  7805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7806. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7807. EXPECT_EQ(xml, res->body);
  7808. EXPECT_TRUE(cli_.is_socket_open());
  7809. }
  7810. // A built-in method must still be served on the same connection.
  7811. cli_.set_keep_alive(false);
  7812. auto res = cli_.Get("/hi");
  7813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7814. EXPECT_EQ(StatusCode::OK_200, res->status);
  7815. EXPECT_EQ("close", res->get_header_value("Connection"));
  7816. }
  7817. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7818. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7819. Request req;
  7820. req.method = "PROPFIND";
  7821. req.path = "/dav/dir";
  7822. req.set_header("Expect", "100-continue");
  7823. req.body = xml;
  7824. auto res = cli_.send(req);
  7825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7826. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7827. EXPECT_EQ(xml, res->body);
  7828. }
  7829. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7830. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7831. TEST_F(ServerTest, Gzip) {
  7832. Headers headers;
  7833. headers.emplace("Accept-Encoding", "gzip, deflate");
  7834. auto res = cli_.Get("/compress", headers);
  7835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7836. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7837. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7838. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7839. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7840. "7890123456789012345678901234567890",
  7841. res->body);
  7842. EXPECT_EQ(StatusCode::OK_200, res->status);
  7843. }
  7844. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7845. Headers headers;
  7846. headers.emplace("Accept-Encoding", "gzip, deflate");
  7847. auto res = cli_.Get("/compress-with-charset", headers);
  7848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7849. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7850. EXPECT_EQ("application/json; charset=utf-8",
  7851. res->get_header_value("Content-Type"));
  7852. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7853. "7890123456789012345678901234567890",
  7854. res->body);
  7855. EXPECT_EQ(StatusCode::OK_200, res->status);
  7856. }
  7857. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7858. Headers headers;
  7859. headers.emplace("Accept-Encoding", "");
  7860. auto res = cli_.Get("/compress", headers);
  7861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7862. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7863. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7864. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7865. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7866. "7890123456789012345678901234567890",
  7867. res->body);
  7868. EXPECT_EQ(StatusCode::OK_200, res->status);
  7869. }
  7870. TEST_F(ServerTest, GzipWithContentReceiver) {
  7871. Headers headers;
  7872. headers.emplace("Accept-Encoding", "gzip, deflate");
  7873. std::string body;
  7874. auto res = cli_.Get("/compress", headers,
  7875. [&](const char *data, uint64_t data_length) {
  7876. EXPECT_EQ(100U, data_length);
  7877. body.append(data, data_length);
  7878. return true;
  7879. });
  7880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7881. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7882. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7883. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7884. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7885. "7890123456789012345678901234567890",
  7886. body);
  7887. EXPECT_EQ(StatusCode::OK_200, res->status);
  7888. }
  7889. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7890. Headers headers;
  7891. headers.emplace("Accept-Encoding", "gzip, deflate");
  7892. cli_.set_decompress(false);
  7893. auto res = cli_.Get("/compress", headers);
  7894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7895. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7896. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7897. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7898. EXPECT_EQ(33U, res->body.size());
  7899. EXPECT_EQ(StatusCode::OK_200, res->status);
  7900. }
  7901. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7902. Headers headers;
  7903. headers.emplace("Accept-Encoding", "");
  7904. std::string body;
  7905. auto res = cli_.Get("/compress", headers,
  7906. [&](const char *data, uint64_t data_length) {
  7907. EXPECT_EQ(100U, data_length);
  7908. body.append(data, data_length);
  7909. return true;
  7910. });
  7911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7912. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7913. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7914. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7915. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7916. "7890123456789012345678901234567890",
  7917. body);
  7918. EXPECT_EQ(StatusCode::OK_200, res->status);
  7919. }
  7920. TEST_F(ServerTest, NoGzip) {
  7921. Headers headers;
  7922. headers.emplace("Accept-Encoding", "gzip, deflate");
  7923. auto res = cli_.Get("/nocompress", headers);
  7924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7925. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7926. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7927. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7928. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7929. "7890123456789012345678901234567890",
  7930. res->body);
  7931. EXPECT_EQ(StatusCode::OK_200, res->status);
  7932. }
  7933. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7934. Headers headers;
  7935. headers.emplace("Accept-Encoding", "gzip, deflate");
  7936. std::string body;
  7937. auto res = cli_.Get("/nocompress", headers,
  7938. [&](const char *data, uint64_t data_length) {
  7939. EXPECT_EQ(100U, data_length);
  7940. body.append(data, data_length);
  7941. return true;
  7942. });
  7943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7944. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7945. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7946. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7947. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7948. "7890123456789012345678901234567890",
  7949. body);
  7950. EXPECT_EQ(StatusCode::OK_200, res->status);
  7951. }
  7952. TEST_F(ServerTest, MultipartFormDataGzip) {
  7953. UploadFormDataItems items = {
  7954. {"key1", "test", "", ""},
  7955. {"key2", "--abcdefg123", "", ""},
  7956. };
  7957. cli_.set_compress(true);
  7958. auto res = cli_.Post("/compress-multipart", items);
  7959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7960. EXPECT_EQ(StatusCode::OK_200, res->status);
  7961. }
  7962. #endif
  7963. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7964. // Static file compression is opt-in, so these run their own server rather than
  7965. // flipping it on for the shared ServerTest fixture, which would silently
  7966. // rewrite what every other static file test is asserting.
  7967. class StaticFileCompressionTest : public ::testing::Test {
  7968. protected:
  7969. void TearDown() override {
  7970. if (t_.joinable()) {
  7971. svr_.stop();
  7972. t_.join();
  7973. }
  7974. }
  7975. int start(const std::function<void(Server &)> &configure = nullptr) {
  7976. // Serves the same tree as a directory of build-time compressed assets
  7977. // would be served: the mount point names the coding the files are already
  7978. // stored in. Registered before "/" so it is the one that matches.
  7979. svr_.set_mount_point("/pre-encoded", "./www",
  7980. {{"Content-Encoding", "gzip"}});
  7981. svr_.set_mount_point("/", "./www");
  7982. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7983. res.set_file_content("./www/dir/index.html", "text/html");
  7984. });
  7985. svr_.Get("/pre-encoded-file-content",
  7986. [](const Request & /*req*/, Response &res) {
  7987. res.set_header("Content-Encoding", "gzip");
  7988. res.set_file_content("./www/dir/index.html", "text/html");
  7989. });
  7990. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7991. res.set_content_provider(
  7992. 6, "text/plain",
  7993. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7994. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7995. return true;
  7996. });
  7997. });
  7998. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7999. res.set_content_provider(
  8000. 1000, "text/plain",
  8001. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8002. if (offset < 100) {
  8003. std::string data(100, 'A');
  8004. sink.write(data.data(), data.size());
  8005. return true;
  8006. }
  8007. std::this_thread::sleep_for(std::chrono::seconds(2));
  8008. std::string data(900, 'B');
  8009. sink.write(data.data(), data.size());
  8010. return true;
  8011. });
  8012. });
  8013. if (configure) { configure(svr_); }
  8014. auto port = svr_.bind_to_any_port(HOST);
  8015. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8016. svr_.wait_until_ready();
  8017. return port;
  8018. }
  8019. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8020. // Every file under ./www except 1MB.txt is smaller than the default
  8021. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8022. // it out of the way.
  8023. static void enable_without_floor(Server &svr) {
  8024. svr.set_static_file_compression(true);
  8025. svr.set_static_file_compression_min_length(0);
  8026. }
  8027. Server svr_;
  8028. std::thread t_;
  8029. };
  8030. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8031. auto port = start();
  8032. Client cli(HOST, port);
  8033. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8035. EXPECT_EQ(StatusCode::OK_200, res->status);
  8036. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8037. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8038. EXPECT_EQ(1048576U, res->body.size());
  8039. }
  8040. TEST_F(StaticFileCompressionTest, MountPoint) {
  8041. auto port = start(enable);
  8042. Client cli(HOST, port);
  8043. cli.set_decompress(false);
  8044. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8046. EXPECT_EQ(StatusCode::OK_200, res->status);
  8047. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8048. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8049. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8050. // The response stays self-delimiting: a length, not a chunked body.
  8051. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8052. EXPECT_EQ(std::to_string(res->body.size()),
  8053. res->get_header_value("Content-Length"));
  8054. EXPECT_LT(res->body.size(), 1048576U);
  8055. EXPECT_FALSE(res->body.empty());
  8056. }
  8057. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8058. auto port = start(enable);
  8059. Client cli(HOST, port);
  8060. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8062. EXPECT_EQ(StatusCode::OK_200, res->status);
  8063. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8064. EXPECT_EQ(1048576U, res->body.size());
  8065. }
  8066. TEST_F(StaticFileCompressionTest, FileContent) {
  8067. auto port = start(enable_without_floor);
  8068. Client cli(HOST, port);
  8069. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8071. EXPECT_EQ(StatusCode::OK_200, res->status);
  8072. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8073. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8074. EXPECT_EQ(104U, res->body.size());
  8075. }
  8076. // A handler that serves an already-encoded file names the coding itself. The
  8077. // file-backed path decided its coding from Accept-Encoding and the content
  8078. // type alone, so it compressed the stored bytes a second time and appended a
  8079. // second Content-Encoding field line.
  8080. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8081. auto port = start(enable_without_floor);
  8082. Client cli(HOST, port);
  8083. cli.set_decompress(false);
  8084. auto res = cli.Get("/pre-encoded-file-content",
  8085. Headers{{"Accept-Encoding", "gzip"}});
  8086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8087. EXPECT_EQ(StatusCode::OK_200, res->status);
  8088. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8089. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8090. // Vary belongs to a coding the server chose, and it chose none here.
  8091. EXPECT_FALSE(res->has_header("Vary"));
  8092. // The file travels exactly as it is stored on disk.
  8093. EXPECT_EQ(104U, res->body.size());
  8094. }
  8095. // The 1MB file clears the default floor, so this one runs the configuration a
  8096. // deployment would actually have.
  8097. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8098. auto port = start(enable);
  8099. Client cli(HOST, port);
  8100. cli.set_decompress(false);
  8101. auto res =
  8102. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8104. EXPECT_EQ(StatusCode::OK_200, res->status);
  8105. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8106. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8107. EXPECT_FALSE(res->has_header("Vary"));
  8108. EXPECT_EQ(1048576U, res->body.size());
  8109. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8110. }
  8111. TEST_F(StaticFileCompressionTest, Head) {
  8112. auto port = start(enable);
  8113. Client cli(HOST, port);
  8114. cli.set_decompress(false);
  8115. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8116. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8117. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8119. EXPECT_EQ(StatusCode::OK_200, res->status);
  8120. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8121. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8122. // HEAD still reports the size a GET would return.
  8123. EXPECT_EQ(get->get_header_value("Content-Length"),
  8124. res->get_header_value("Content-Length"));
  8125. EXPECT_TRUE(res->body.empty());
  8126. }
  8127. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8128. auto port = start(enable);
  8129. Client cli(HOST, port);
  8130. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8131. {"Accept-Encoding", "gzip"}});
  8132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8133. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8134. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8135. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8136. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8137. EXPECT_EQ("cd", res->body);
  8138. }
  8139. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8140. auto port = start(enable);
  8141. Client cli(HOST, port);
  8142. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8144. EXPECT_EQ(StatusCode::OK_200, res->status);
  8145. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8146. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8147. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8148. }
  8149. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8150. auto port = start(enable);
  8151. Client cli(HOST, port);
  8152. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8154. EXPECT_EQ(StatusCode::OK_200, res->status);
  8155. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8156. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8157. EXPECT_TRUE(res->body.empty());
  8158. }
  8159. TEST_F(StaticFileCompressionTest, MinLength) {
  8160. auto port = start(enable);
  8161. Client cli(HOST, port);
  8162. // 104 bytes, well under the default floor. Compressing it would add the
  8163. // gzip header and trailer to a body that already fits in one packet.
  8164. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8166. EXPECT_EQ(StatusCode::OK_200, res->status);
  8167. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8168. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8169. }
  8170. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8171. auto port = start([](Server &svr) {
  8172. svr.set_static_file_compression(true);
  8173. svr.set_static_file_compression_min_length(1);
  8174. });
  8175. Client cli(HOST, port);
  8176. cli.set_decompress(false);
  8177. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8179. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8180. // A 9-byte file comes back larger than it went in, because gzip's header and
  8181. // trailer outweigh anything deflate can save. That is the end of the range
  8182. // the floor exists to keep out.
  8183. EXPECT_GT(res->body.size(), 9U);
  8184. }
  8185. TEST_F(StaticFileCompressionTest, MaxLength) {
  8186. auto port = start([](Server &svr) {
  8187. svr.set_static_file_compression(true);
  8188. svr.set_static_file_compression_min_length(0);
  8189. svr.set_static_file_compression_max_length(1024);
  8190. });
  8191. Client cli(HOST, port);
  8192. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8193. // defines `small` as a macro on Windows.
  8194. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8195. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8196. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8197. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8198. // Under it: compressed.
  8199. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8200. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8201. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8202. }
  8203. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8204. auto port = start(enable_without_floor);
  8205. Client cli(HOST, port);
  8206. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8207. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8208. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8209. auto identity_etag = identity->get_header_value("ETag");
  8210. ASSERT_FALSE(identity_etag.empty());
  8211. auto gzipped =
  8212. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8213. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8214. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8215. auto gzip_etag = gzipped->get_header_value("ETag");
  8216. ASSERT_FALSE(gzip_etag.empty());
  8217. // Two representations, two validators.
  8218. EXPECT_NE(identity_etag, gzip_etag);
  8219. // Each one revalidates against the request that would produce it...
  8220. auto fresh =
  8221. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8222. {"If-None-Match", gzip_etag}});
  8223. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8224. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8225. auto fresh_identity =
  8226. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8227. {"If-None-Match", identity_etag}});
  8228. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8229. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8230. // ...and not against the other representation.
  8231. auto crossed =
  8232. cli.Get("/dir/index.html",
  8233. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8234. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8235. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8236. }
  8237. // The opt-in covers responses the server reads off disk itself. A caller's own
  8238. // known-length provider keeps its Content-Length and, more importantly, keeps
  8239. // delivering incrementally: routing it through a compressor would hold every
  8240. // write back until zlib's window filled.
  8241. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8242. auto port = start(enable);
  8243. Client cli(HOST, port);
  8244. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8246. EXPECT_EQ(StatusCode::OK_200, res->status);
  8247. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8248. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8249. EXPECT_EQ("aaabbb", res->body);
  8250. }
  8251. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8252. auto port = start(enable);
  8253. Client cli(HOST, port);
  8254. cli.set_read_timeout(1, 0);
  8255. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8256. Headers{{"Accept-Encoding", "gzip"}});
  8257. ASSERT_TRUE(handle.is_valid());
  8258. // The provider writes 100 bytes and then stalls for longer than the read
  8259. // timeout. Those first bytes have to arrive anyway: run the response through
  8260. // a compressor and zlib holds them until its window fills, so the read would
  8261. // come back empty instead.
  8262. char buf[256];
  8263. auto n = handle.read(buf, sizeof(buf));
  8264. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8265. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8266. }
  8267. #endif
  8268. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8269. TEST_F(ServerTest, Brotli) {
  8270. Headers headers;
  8271. headers.emplace("Accept-Encoding", "br");
  8272. auto res = cli_.Get("/compress", headers);
  8273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8274. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8275. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8276. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8277. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8278. "7890123456789012345678901234567890",
  8279. res->body);
  8280. EXPECT_EQ(StatusCode::OK_200, res->status);
  8281. }
  8282. #endif
  8283. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8284. TEST_F(ServerTest, Zstd) {
  8285. Headers headers;
  8286. headers.emplace("Accept-Encoding", "zstd");
  8287. auto res = cli_.Get("/compress", headers);
  8288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8289. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8290. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8291. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8292. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8293. "7890123456789012345678901234567890",
  8294. res->body);
  8295. EXPECT_EQ(StatusCode::OK_200, res->status);
  8296. }
  8297. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8298. Headers headers;
  8299. headers.emplace("Accept-Encoding", "");
  8300. auto res = cli_.Get("/compress", headers);
  8301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8302. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8303. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8304. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8305. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8306. "7890123456789012345678901234567890",
  8307. res->body);
  8308. EXPECT_EQ(StatusCode::OK_200, res->status);
  8309. }
  8310. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8311. Headers headers;
  8312. headers.emplace("Accept-Encoding", "zstd");
  8313. std::string body;
  8314. auto res = cli_.Get("/compress", headers,
  8315. [&](const char *data, uint64_t data_length) {
  8316. EXPECT_EQ(100U, data_length);
  8317. body.append(data, data_length);
  8318. return true;
  8319. });
  8320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8321. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8322. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8323. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8324. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8325. "7890123456789012345678901234567890",
  8326. body);
  8327. EXPECT_EQ(StatusCode::OK_200, res->status);
  8328. }
  8329. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8330. Headers headers;
  8331. headers.emplace("Accept-Encoding", "zstd");
  8332. cli_.set_decompress(false);
  8333. auto res = cli_.Get("/compress", headers);
  8334. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8335. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8336. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8337. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8339. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8340. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8341. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8342. EXPECT_EQ(StatusCode::OK_200, res->status);
  8343. ASSERT_EQ(26U, res->body.size());
  8344. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8345. 0);
  8346. }
  8347. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8348. Headers headers;
  8349. headers.emplace("Accept-Encoding", "");
  8350. std::string body;
  8351. auto res = cli_.Get("/compress", headers,
  8352. [&](const char *data, uint64_t data_length) {
  8353. EXPECT_EQ(100U, data_length);
  8354. body.append(data, data_length);
  8355. return true;
  8356. });
  8357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8358. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8359. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8360. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8361. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8362. "7890123456789012345678901234567890",
  8363. body);
  8364. EXPECT_EQ(StatusCode::OK_200, res->status);
  8365. }
  8366. TEST_F(ServerTest, NoZstd) {
  8367. Headers headers;
  8368. headers.emplace("Accept-Encoding", "zstd");
  8369. auto res = cli_.Get("/nocompress", headers);
  8370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8371. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8372. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8373. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8374. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8375. "7890123456789012345678901234567890",
  8376. res->body);
  8377. EXPECT_EQ(StatusCode::OK_200, res->status);
  8378. }
  8379. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8380. Headers headers;
  8381. headers.emplace("Accept-Encoding", "zstd");
  8382. std::string body;
  8383. auto res = cli_.Get("/nocompress", headers,
  8384. [&](const char *data, uint64_t data_length) {
  8385. EXPECT_EQ(100U, data_length);
  8386. body.append(data, data_length);
  8387. return true;
  8388. });
  8389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8390. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8391. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8392. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8393. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8394. "7890123456789012345678901234567890",
  8395. body);
  8396. EXPECT_EQ(StatusCode::OK_200, res->status);
  8397. }
  8398. // TODO: How to enable zstd ??
  8399. TEST_F(ServerTest, MultipartFormDataZstd) {
  8400. UploadFormDataItems items = {
  8401. {"key1", "test", "", ""},
  8402. {"key2", "--abcdefg123", "", ""},
  8403. };
  8404. Headers headers;
  8405. headers.emplace("Accept-Encoding", "zstd");
  8406. cli_.set_compress(true);
  8407. auto res = cli_.Post("/compress-multipart", headers, items);
  8408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8409. EXPECT_EQ(StatusCode::OK_200, res->status);
  8410. }
  8411. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8412. Headers headers;
  8413. headers.emplace("Accept-Encoding", "zstd");
  8414. cli_.set_compress(true);
  8415. auto res = cli_.Put(
  8416. "/put", headers, 3,
  8417. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8418. sink.os << "PUT";
  8419. return true;
  8420. },
  8421. "text/plain");
  8422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8423. EXPECT_EQ(StatusCode::OK_200, res->status);
  8424. EXPECT_EQ("PUT", res->body);
  8425. }
  8426. // Pre-compression logging tests
  8427. TEST_F(ServerTest, PreCompressionLogging) {
  8428. // Test data for compression (matches the actual /compress endpoint content)
  8429. const std::string test_content =
  8430. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8431. "3456789012345678901234567890";
  8432. // Variables to capture logging data
  8433. std::string pre_compression_body;
  8434. std::string pre_compression_content_type;
  8435. std::string pre_compression_content_encoding;
  8436. std::string post_compression_body;
  8437. std::string post_compression_content_type;
  8438. std::string post_compression_content_encoding;
  8439. // Set up pre-compression logger
  8440. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8441. const Response &res) {
  8442. pre_compression_body = res.body;
  8443. pre_compression_content_type = res.get_header_value("Content-Type");
  8444. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8445. });
  8446. // Set up post-compression logger
  8447. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8448. post_compression_body = res.body;
  8449. post_compression_content_type = res.get_header_value("Content-Type");
  8450. post_compression_content_encoding =
  8451. res.get_header_value("Content-Encoding");
  8452. });
  8453. // Test with gzip compression
  8454. Headers headers;
  8455. headers.emplace("Accept-Encoding", "gzip");
  8456. auto res = cli_.Get("/compress", headers);
  8457. // Verify response was compressed
  8458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8459. EXPECT_EQ(StatusCode::OK_200, res->status);
  8460. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8461. // Verify pre-compression logger captured uncompressed content
  8462. EXPECT_EQ(test_content, pre_compression_body);
  8463. EXPECT_EQ("text/plain", pre_compression_content_type);
  8464. EXPECT_TRUE(pre_compression_content_encoding
  8465. .empty()); // No encoding header before compression
  8466. // Verify post-compression logger captured compressed content
  8467. EXPECT_NE(test_content,
  8468. post_compression_body); // Should be different after compression
  8469. EXPECT_EQ("text/plain", post_compression_content_type);
  8470. EXPECT_EQ("gzip", post_compression_content_encoding);
  8471. // Verify compressed content is smaller
  8472. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8473. }
  8474. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8475. const std::string test_content =
  8476. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8477. "3456789012345678901234567890";
  8478. std::string pre_compression_body;
  8479. std::string post_compression_body;
  8480. svr_.set_pre_compression_logger(
  8481. [&](const Request & /*req*/, const Response &res) {
  8482. pre_compression_body = res.body;
  8483. });
  8484. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8485. post_compression_body = res.body;
  8486. });
  8487. Headers headers;
  8488. headers.emplace("Accept-Encoding", "br");
  8489. auto res = cli_.Get("/compress", headers);
  8490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8491. EXPECT_EQ(StatusCode::OK_200, res->status);
  8492. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8493. // Verify pre-compression content is uncompressed
  8494. EXPECT_EQ(test_content, pre_compression_body);
  8495. // Verify post-compression content is compressed
  8496. EXPECT_NE(test_content, post_compression_body);
  8497. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8498. }
  8499. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8500. const std::string test_content =
  8501. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8502. "3456789012345678901234567890";
  8503. std::string pre_compression_body;
  8504. std::string post_compression_body;
  8505. svr_.set_pre_compression_logger(
  8506. [&](const Request & /*req*/, const Response &res) {
  8507. pre_compression_body = res.body;
  8508. });
  8509. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8510. post_compression_body = res.body;
  8511. });
  8512. // Request without compression (use /nocompress endpoint)
  8513. Headers headers;
  8514. auto res = cli_.Get("/nocompress", headers);
  8515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8516. EXPECT_EQ(StatusCode::OK_200, res->status);
  8517. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8518. // Pre-compression logger should not be called when no compression is applied
  8519. EXPECT_TRUE(
  8520. pre_compression_body.empty()); // Pre-compression logger not called
  8521. EXPECT_EQ(
  8522. test_content,
  8523. post_compression_body); // Post-compression logger captures final content
  8524. }
  8525. TEST_F(ServerTest, LoggerSeesContentLength) {
  8526. size_t logged_content_length = 0;
  8527. std::string logged_content_length_header;
  8528. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8529. logged_content_length = res.content_length_;
  8530. logged_content_length_header = res.get_header_value("Content-Length");
  8531. });
  8532. auto res = cli_.Get("/nocompress");
  8533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8534. EXPECT_EQ(StatusCode::OK_200, res->status);
  8535. EXPECT_EQ(res->body.size(), logged_content_length);
  8536. EXPECT_EQ(std::to_string(logged_content_length),
  8537. logged_content_length_header);
  8538. }
  8539. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8540. const std::string test_content =
  8541. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8542. "3456789012345678901234567890";
  8543. std::string pre_compression_body;
  8544. bool pre_logger_called = false;
  8545. // Set only pre-compression logger
  8546. svr_.set_pre_compression_logger(
  8547. [&](const Request & /*req*/, const Response &res) {
  8548. pre_compression_body = res.body;
  8549. pre_logger_called = true;
  8550. });
  8551. Headers headers;
  8552. headers.emplace("Accept-Encoding", "gzip");
  8553. auto res = cli_.Get("/compress", headers);
  8554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8555. EXPECT_EQ(StatusCode::OK_200, res->status);
  8556. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8557. // Verify pre-compression logger was called
  8558. EXPECT_TRUE(pre_logger_called);
  8559. EXPECT_EQ(test_content, pre_compression_body);
  8560. }
  8561. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8562. {
  8563. // Test with Expect: 100-continue header - success case
  8564. // Server returns 100 Continue, client sends body, server returns 200 OK
  8565. Request req;
  8566. req.method = "POST";
  8567. req.path = "/post-large";
  8568. req.set_header("Expect", "100-continue");
  8569. req.body = LARGE_DATA;
  8570. Response res;
  8571. auto error = Error::Success;
  8572. cli_.set_keep_alive(true);
  8573. auto ret = cli_.send(req, res, error);
  8574. EXPECT_TRUE(ret);
  8575. EXPECT_EQ(StatusCode::OK_200, res.status);
  8576. EXPECT_EQ(LARGE_DATA, res.body);
  8577. }
  8578. {
  8579. // Test with Expect: 100-continue header - error case
  8580. // Client should not send the body when server returns an error
  8581. Request req;
  8582. req.method = "POST";
  8583. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8584. req.set_header("Expect", "100-continue");
  8585. req.body = LARGE_DATA;
  8586. Response res;
  8587. auto error = Error::Success;
  8588. auto start = std::chrono::high_resolution_clock::now();
  8589. cli_.set_keep_alive(true);
  8590. auto ret = cli_.send(req, res, error);
  8591. auto end = std::chrono::high_resolution_clock::now();
  8592. auto elapsed =
  8593. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8594. .count();
  8595. // With Expect: 100-continue, request completes successfully but with error
  8596. EXPECT_TRUE(ret);
  8597. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8598. EXPECT_EQ("close", res.get_header_value("Connection"));
  8599. EXPECT_FALSE(cli_.is_socket_open());
  8600. EXPECT_LE(elapsed, 2000);
  8601. }
  8602. {
  8603. // Send an extra GET request to ensure error recovery without hanging
  8604. Request req;
  8605. req.method = "GET";
  8606. req.path = "/hi";
  8607. auto start = std::chrono::high_resolution_clock::now();
  8608. auto res = cli_.send(req);
  8609. auto end = std::chrono::high_resolution_clock::now();
  8610. auto elapsed =
  8611. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8612. .count();
  8613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8614. EXPECT_EQ(StatusCode::OK_200, res->status);
  8615. EXPECT_EQ("Hello World!", res->body);
  8616. EXPECT_LE(elapsed, 500);
  8617. }
  8618. }
  8619. TEST(ZstdDecompressor, ChunkedDecompression) {
  8620. std::string data;
  8621. for (size_t i = 0; i < 32 * 1024; ++i) {
  8622. data.push_back(static_cast<char>('a' + i % 26));
  8623. }
  8624. std::string compressed_data;
  8625. {
  8626. httplib::detail::zstd_compressor compressor;
  8627. bool result = compressor.compress(
  8628. data.data(), data.size(),
  8629. /*last=*/true,
  8630. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8631. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8632. compressed_data_size);
  8633. return true;
  8634. });
  8635. ASSERT_TRUE(result);
  8636. }
  8637. std::string decompressed_data;
  8638. {
  8639. httplib::detail::zstd_decompressor decompressor;
  8640. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8641. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8642. size_t chunk_size = 130;
  8643. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8644. chunk_begin += chunk_size) {
  8645. size_t current_chunk_size =
  8646. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8647. bool result = decompressor.decompress(
  8648. compressed_data.data() + chunk_begin, current_chunk_size,
  8649. [&](const char *decompressed_data_chunk,
  8650. size_t decompressed_data_chunk_size) {
  8651. decompressed_data.insert(decompressed_data.size(),
  8652. decompressed_data_chunk,
  8653. decompressed_data_chunk_size);
  8654. return true;
  8655. });
  8656. ASSERT_TRUE(result);
  8657. }
  8658. }
  8659. ASSERT_EQ(data, decompressed_data);
  8660. }
  8661. TEST(ZstdDecompressor, Decompress) {
  8662. std::string original_text = "Compressed with ZSTD";
  8663. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8664. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8665. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8666. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8667. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8668. std::string decompressed_data;
  8669. {
  8670. httplib::detail::zstd_decompressor decompressor;
  8671. bool result = decompressor.decompress(
  8672. compressed_data.data(), compressed_data.size(),
  8673. [&](const char *decompressed_data_chunk,
  8674. size_t decompressed_data_chunk_size) {
  8675. decompressed_data.insert(decompressed_data.size(),
  8676. decompressed_data_chunk,
  8677. decompressed_data_chunk_size);
  8678. return true;
  8679. });
  8680. ASSERT_TRUE(result);
  8681. }
  8682. ASSERT_EQ(original_text, decompressed_data);
  8683. }
  8684. #endif
  8685. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8686. // separate chunks so that the server sees each part in its own read(). Used to
  8687. // place a read boundary at a specific offset of a request body.
  8688. static bool send_request_in_parts(time_t read_timeout_sec,
  8689. const std::vector<std::string> &parts,
  8690. std::string *resp = nullptr,
  8691. int port = PORT) {
  8692. auto error = Error::Success;
  8693. auto client_sock = detail::create_client_socket(
  8694. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8695. /*connection_timeout_sec=*/5, 0,
  8696. /*read_timeout_sec=*/5, 0,
  8697. /*write_timeout_sec=*/5, 0, std::string(), error);
  8698. if (client_sock == INVALID_SOCKET) { return false; }
  8699. auto ret = detail::process_client_socket(
  8700. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8701. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8702. for (size_t i = 0; i < parts.size(); i++) {
  8703. const auto &part = parts[i];
  8704. if (part.size() !=
  8705. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8706. return false;
  8707. }
  8708. if (i + 1 < parts.size()) {
  8709. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8710. }
  8711. }
  8712. char buf[512];
  8713. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8714. while (line_reader.getline()) {
  8715. if (resp) { *resp += line_reader.ptr(); }
  8716. }
  8717. return true;
  8718. });
  8719. detail::close_socket(client_sock);
  8720. return ret;
  8721. }
  8722. // Sends a raw request to a server listening at HOST:PORT.
  8723. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8724. std::string *resp = nullptr, int port = PORT) {
  8725. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8726. }
  8727. #ifdef CPPHTTPLIB_SSL_ENABLED
  8728. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  8729. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8730. ASSERT_TRUE(svr.is_valid());
  8731. svr.set_read_timeout(1, 0);
  8732. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8733. auto se = detail::scope_exit([&] {
  8734. svr.stop();
  8735. t.join();
  8736. ASSERT_FALSE(svr.is_running());
  8737. });
  8738. svr.wait_until_ready();
  8739. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  8740. // keeps each wait well within the read timeout. The server gives up a
  8741. // second in, so the bytes sent after that fail.
  8742. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  8743. parts.resize(26, std::string(1, '\0'));
  8744. EXPECT_FALSE(send_request_in_parts(5, parts));
  8745. }
  8746. #endif
  8747. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8748. Server svr;
  8749. std::string header_value;
  8750. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8751. header_value = req.get_header_value("foo");
  8752. res.set_content("ok", "text/plain");
  8753. });
  8754. thread t = thread([&] { svr.listen(HOST, PORT); });
  8755. auto se = detail::scope_exit([&] {
  8756. svr.stop();
  8757. t.join();
  8758. ASSERT_FALSE(svr.is_running());
  8759. });
  8760. svr.wait_until_ready();
  8761. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8762. // like characters are not treated the same - use vertical tab and escape.
  8763. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8764. "foo: \t \v bar \x1B\t \r\n"
  8765. "Connection: close\r\n"
  8766. "\r\n";
  8767. std::string res;
  8768. ASSERT_TRUE(send_request(5, req, &res));
  8769. EXPECT_EQ(header_value, "");
  8770. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8771. }
  8772. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8773. Server svr;
  8774. std::string received;
  8775. svr.Get("/order", [&](const Request &req, Response &res) {
  8776. received = entries_to_string(req.headers);
  8777. res.set_content("ok", "text/plain");
  8778. });
  8779. auto port = svr.bind_to_any_port(HOST);
  8780. thread t = thread([&] { svr.listen_after_bind(); });
  8781. auto se = detail::scope_exit([&] {
  8782. svr.stop();
  8783. t.join();
  8784. ASSERT_FALSE(svr.is_running());
  8785. });
  8786. svr.wait_until_ready();
  8787. const std::string req = "GET /order HTTP/1.1\r\n"
  8788. "X-First: 1\r\n"
  8789. "X-Dup: a\r\n"
  8790. "X-Second: 2\r\n"
  8791. "X-Dup: b\r\n"
  8792. "Connection: close\r\n"
  8793. "\r\n";
  8794. std::string res;
  8795. ASSERT_TRUE(send_request(5, req, &res, port));
  8796. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8797. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8798. }
  8799. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8800. Server svr;
  8801. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8802. res.set_header("Set-Cookie", "first=1");
  8803. res.set_header("X-Between", "y");
  8804. res.set_header("Set-Cookie", "second=2");
  8805. res.set_content("ok", "text/plain");
  8806. });
  8807. auto port = svr.bind_to_any_port(HOST);
  8808. thread t = thread([&] { svr.listen_after_bind(); });
  8809. auto se = detail::scope_exit([&] {
  8810. svr.stop();
  8811. t.join();
  8812. ASSERT_FALSE(svr.is_running());
  8813. });
  8814. svr.wait_until_ready();
  8815. Client cli(HOST, port);
  8816. auto res = cli.Get("/cookies");
  8817. ASSERT_TRUE(res);
  8818. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8819. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8820. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8821. }
  8822. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8823. Server svr;
  8824. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8825. auto i = new int(0);
  8826. res.set_header("Trailer", "X-Safe, X-Reflected");
  8827. res.set_chunked_content_provider(
  8828. "text/plain",
  8829. [i](size_t /*offset*/, DataSink &sink) {
  8830. if (*i == 0) {
  8831. sink.os << "body";
  8832. } else {
  8833. Headers trailer;
  8834. // A valid trailer that must survive.
  8835. trailer.emplace("X-Safe", "safe");
  8836. // Attacker-controlled value carrying CR/LF (response splitting).
  8837. trailer.emplace("X-Reflected",
  8838. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8839. // Attacker-controlled name carrying CR/LF.
  8840. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8841. sink.done_with_trailer(trailer);
  8842. }
  8843. (*i)++;
  8844. return true;
  8845. },
  8846. [i](bool /*success*/) { delete i; });
  8847. });
  8848. thread t = thread([&] { svr.listen(HOST, PORT); });
  8849. auto se = detail::scope_exit([&] {
  8850. svr.stop();
  8851. t.join();
  8852. ASSERT_FALSE(svr.is_running());
  8853. });
  8854. svr.wait_until_ready();
  8855. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8856. "Host: " + HOST +
  8857. "\r\n"
  8858. "Connection: close\r\n"
  8859. "\r\n";
  8860. std::string res;
  8861. ASSERT_TRUE(send_request(5, req, &res));
  8862. // The injected fields must not appear anywhere in the raw response.
  8863. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8864. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8865. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8866. // Invalid trailers are dropped entirely, matching set_header().
  8867. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8868. // The valid trailer still passes through.
  8869. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8870. }
  8871. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8872. Server svr;
  8873. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8874. // res.headers is a public field an application can populate directly,
  8875. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8876. // A valid header that must survive.
  8877. res.headers.emplace("X-Safe", "safe");
  8878. // Attacker-controlled value carrying CR/LF (response splitting).
  8879. res.headers.emplace("X-Reflected",
  8880. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8881. // Attacker-controlled name carrying CR/LF.
  8882. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8883. res.set_content("body", "text/plain");
  8884. });
  8885. thread t = thread([&] { svr.listen(HOST, PORT); });
  8886. auto se = detail::scope_exit([&] {
  8887. svr.stop();
  8888. t.join();
  8889. ASSERT_FALSE(svr.is_running());
  8890. });
  8891. svr.wait_until_ready();
  8892. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8893. "Host: " + HOST +
  8894. "\r\n"
  8895. "Connection: close\r\n"
  8896. "\r\n";
  8897. std::string res;
  8898. ASSERT_TRUE(send_request(5, req, &res));
  8899. // The injected fields must not appear anywhere in the raw response.
  8900. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8901. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8902. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8903. // Invalid headers are dropped entirely, matching set_header().
  8904. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8905. // The valid header still passes through.
  8906. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8907. }
  8908. // Forward declaration: in split builds split.py strips `inline` and moves the
  8909. // definition into httplib.cc, so detail::write_request_line is not visible from
  8910. // the public httplib.h. Re-declaring it here lets the tests link against the
  8911. // symbol in both header-only and split builds.
  8912. namespace httplib {
  8913. namespace detail {
  8914. ssize_t write_request_line(Stream &strm, const std::string &method,
  8915. const std::string &path);
  8916. } // namespace detail
  8917. } // namespace httplib
  8918. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8919. // A well-formed target is written verbatim.
  8920. {
  8921. detail::BufferStream strm;
  8922. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8923. EXPECT_GT(n, 0);
  8924. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8925. }
  8926. // A target carrying CR/LF, SP or other control octets must be rejected
  8927. // before anything reaches the wire, otherwise it splits the request line and
  8928. // injects a header or a whole request.
  8929. const std::string evil_targets[] = {
  8930. "/a\r\nInjected: pwned",
  8931. "/a\rInjected",
  8932. "/a\nInjected",
  8933. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8934. "/a b",
  8935. "/a\tb",
  8936. "/a\x7f",
  8937. };
  8938. for (const auto &evil : evil_targets) {
  8939. detail::BufferStream strm;
  8940. auto n = detail::write_request_line(strm, "GET", evil);
  8941. EXPECT_LT(n, 0);
  8942. EXPECT_TRUE(strm.get_buffer().empty());
  8943. }
  8944. }
  8945. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8946. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8947. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8948. // target reaches write_request. The client must fail cleanly with
  8949. // Error::Write instead of putting a request-line-less, header-injecting
  8950. // request on the wire.
  8951. Server svr;
  8952. svr.Get("/a", [](const Request &, Response &res) {
  8953. res.set_content("ok", "text/plain");
  8954. });
  8955. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8956. auto se = detail::scope_exit([&] {
  8957. svr.stop();
  8958. thread.join();
  8959. ASSERT_FALSE(svr.is_running());
  8960. });
  8961. svr.wait_until_ready();
  8962. {
  8963. Client cli(HOST, PORT);
  8964. cli.set_path_encode(false);
  8965. // The request is rejected before anything is written, so the connection
  8966. // stays silent and the subsequent response read would otherwise block for
  8967. // the full default read timeout. Shorten it -- the assertion is on the
  8968. // error, not the timeout.
  8969. cli.set_read_timeout(1, 0);
  8970. auto res = cli.Get("/a\r\nInjected: pwned");
  8971. EXPECT_FALSE(res);
  8972. EXPECT_EQ(Error::Write, res.error());
  8973. }
  8974. }
  8975. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8976. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8977. // including extension methods.
  8978. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8979. for (const auto &method : good_methods) {
  8980. detail::BufferStream strm;
  8981. auto n = detail::write_request_line(strm, method, "/");
  8982. EXPECT_GT(n, 0);
  8983. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8984. }
  8985. // A method carrying CR/LF would split the request line and smuggle a whole
  8986. // request ahead of the real one. A space or an empty method corrupts the
  8987. // request line. All must be rejected before anything reaches the wire.
  8988. const std::string evil_methods[] = {
  8989. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8990. "GET\r\nInjected: pwned",
  8991. "GET\r",
  8992. "GET\n",
  8993. "GE T",
  8994. "",
  8995. };
  8996. for (const auto &evil : evil_methods) {
  8997. detail::BufferStream strm;
  8998. auto n = detail::write_request_line(strm, evil, "/");
  8999. EXPECT_LT(n, 0);
  9000. EXPECT_TRUE(strm.get_buffer().empty());
  9001. }
  9002. }
  9003. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9004. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9005. // through Client::send must fail with Error::Write and no request, neither
  9006. // the smuggled one nor the real one, may reach the server.
  9007. Server svr;
  9008. std::atomic<int> request_count(0);
  9009. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9010. request_count++;
  9011. res.status = StatusCode::OK_200;
  9012. return Server::HandlerResponse::Handled;
  9013. });
  9014. auto port = svr.bind_to_any_port(HOST);
  9015. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9016. auto se = detail::scope_exit([&] {
  9017. svr.stop();
  9018. thread.join();
  9019. ASSERT_FALSE(svr.is_running());
  9020. });
  9021. svr.wait_until_ready();
  9022. {
  9023. Client cli(HOST, port);
  9024. const std::string evil_methods[] = {
  9025. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9026. "GE T",
  9027. "",
  9028. };
  9029. for (const auto &evil : evil_methods) {
  9030. Request req;
  9031. req.method = evil;
  9032. req.path = "/";
  9033. auto res = cli.send(req);
  9034. EXPECT_FALSE(res);
  9035. EXPECT_EQ(Error::Write, res.error());
  9036. }
  9037. auto handle =
  9038. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9039. EXPECT_FALSE(handle.is_valid());
  9040. EXPECT_EQ(Error::Write, handle.error);
  9041. // A valid request on the same client still goes through.
  9042. auto res = cli.Get("/");
  9043. ASSERT_TRUE(res);
  9044. EXPECT_EQ(StatusCode::OK_200, res->status);
  9045. }
  9046. EXPECT_EQ(1, request_count.load());
  9047. }
  9048. // Sends a raw request and verifies that there isn't a crash or exception.
  9049. static void test_raw_request(const std::string &req,
  9050. std::string *out = nullptr) {
  9051. Server svr;
  9052. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9053. res.set_content("ok", "text/plain");
  9054. });
  9055. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9056. res.set_content("ok", "text/plain");
  9057. });
  9058. svr.Get("/header_field_value_check",
  9059. [&](const Request & /*req*/, Response &res) {
  9060. res.set_content("ok", "text/plain");
  9061. });
  9062. svr.CustomRoute("PROPFIND", "/dav",
  9063. [&](const Request & /*req*/, Response &res) {
  9064. res.status = StatusCode::MultiStatus_207;
  9065. });
  9066. // Server read timeout must be longer than the client read timeout for the
  9067. // bug to reproduce, probably to force the server to process a request
  9068. // without a trailing blank line.
  9069. const time_t client_read_timeout_sec = 1;
  9070. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9071. bool listen_thread_ok = false;
  9072. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9073. auto se = detail::scope_exit([&] {
  9074. svr.stop();
  9075. t.join();
  9076. ASSERT_FALSE(svr.is_running());
  9077. EXPECT_TRUE(listen_thread_ok);
  9078. });
  9079. svr.wait_until_ready();
  9080. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9081. }
  9082. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9083. // A certain header line causes an exception if the header property is parsed
  9084. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9085. test_raw_request(
  9086. "GET /hi HTTP/1.1\r\n"
  9087. " : "
  9088. " "
  9089. " ");
  9090. }
  9091. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9092. // A certain header line causes an exception if the header property *name* is
  9093. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9094. // greedy matcher and requires backtracking when there are a lot of ":"
  9095. // characters.
  9096. // This occurs with libc++ but not libstdc++.
  9097. test_raw_request(
  9098. "GET /hi HTTP/1.1\r\n"
  9099. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9100. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9101. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9102. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9103. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9104. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9105. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9106. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9107. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9108. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9109. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9110. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9111. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9112. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9113. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9114. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9115. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9116. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9117. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9118. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9119. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9120. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9121. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9122. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9123. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9124. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9125. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9126. "&&&%%%");
  9127. }
  9128. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9129. // Make sure this doesn't crash the server.
  9130. // In a previous version of the header line regex, the "\r" rendered the line
  9131. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9132. // a new position where the leading white space ended and the field value
  9133. // began.
  9134. // The crash occurs with libc++ but not libstdc++.
  9135. test_raw_request("GET /hi HTTP/1.1\r\n"
  9136. "a:" +
  9137. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9138. "\r\n"
  9139. "\r\n");
  9140. }
  9141. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9142. std::string out;
  9143. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9144. "Content-Type: text/plain\r\n"
  9145. "Transfer-Encoding: chunked\r\n"
  9146. "\r\n"
  9147. "nothex\r\n",
  9148. &out);
  9149. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9150. }
  9151. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9152. std::string out;
  9153. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9154. "Content-Type: text/plain\r\n"
  9155. "Transfer-Encoding: chunked\r\n"
  9156. "\r\n"
  9157. "3\r\n"
  9158. "xyz\r\n"
  9159. "NaN\r\n",
  9160. &out);
  9161. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9162. }
  9163. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9164. std::string out;
  9165. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9166. "Content-Type: text/plain\r\n"
  9167. "Transfer-Encoding: chunked\r\n"
  9168. "\r\n"
  9169. // Length is too large for 64 bits.
  9170. "1ffffffffffffffff\r\n"
  9171. "xyz\r\n",
  9172. &out);
  9173. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9174. }
  9175. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9176. test_raw_request("GET /hi HTTP/1.1\r\n"
  9177. "Content-Type: text/plain\r\n\r");
  9178. }
  9179. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9180. std::string out;
  9181. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9182. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9183. }
  9184. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9185. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9186. std::string out;
  9187. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9188. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9189. }
  9190. }
  9191. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9192. std::string out;
  9193. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9194. "Connection: close\r\n\r\n",
  9195. &out);
  9196. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9197. }
  9198. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9199. Server svr;
  9200. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9201. EXPECT_TRUE(!req.remote_addr.empty());
  9202. });
  9203. thread t = thread([&] { svr.listen(HOST, PORT); });
  9204. auto se = detail::scope_exit([&] {
  9205. svr.stop();
  9206. t.join();
  9207. ASSERT_FALSE(svr.is_running());
  9208. });
  9209. svr.wait_until_ready();
  9210. // Send an invalid request line to trigger Bad Request
  9211. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9212. std::string out;
  9213. ASSERT_TRUE(send_request(5, bad_req, &out));
  9214. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9215. }
  9216. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9217. // answered right away rather than blocking on a read that waits for EOF.
  9218. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9219. std::string out;
  9220. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9221. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9222. }
  9223. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9224. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9225. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9226. for (const auto *method : methods) {
  9227. Server svr;
  9228. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9229. EXPECT_FALSE(svr.is_valid()) << method;
  9230. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9231. }
  9232. }
  9233. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9234. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9235. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9236. for (const auto *method : methods) {
  9237. Server svr;
  9238. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9239. EXPECT_FALSE(svr.is_valid()) << method;
  9240. }
  9241. }
  9242. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9243. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9244. "COPY", "MOVE", "LOCK",
  9245. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9246. Server svr;
  9247. for (const auto *method : methods) {
  9248. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9249. }
  9250. EXPECT_TRUE(svr.is_valid());
  9251. }
  9252. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9253. Server svr;
  9254. svr.CustomRoute("POST", "/x",
  9255. [](const Request &, Response &, const ContentReader &) {});
  9256. EXPECT_FALSE(svr.is_valid());
  9257. }
  9258. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9259. Server svr;
  9260. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9261. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9262. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9263. EXPECT_FALSE(svr.is_valid());
  9264. }
  9265. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9266. Server svr;
  9267. auto captured = Error::Success;
  9268. svr.set_error_logger(
  9269. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9270. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9271. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9272. }
  9273. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9274. std::string out;
  9275. std::string request(
  9276. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9277. test_raw_request(request, &out);
  9278. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9279. }
  9280. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9281. std::string out;
  9282. std::string request(
  9283. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9284. test_raw_request(request, &out);
  9285. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9286. }
  9287. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9288. std::string out;
  9289. std::string request(
  9290. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9291. test_raw_request(request, &out);
  9292. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9293. }
  9294. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9295. std::string out;
  9296. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9297. "Test: \r\n\r\n",
  9298. &out);
  9299. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9300. }
  9301. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9302. Server svr;
  9303. std::string x_custom;
  9304. std::string cookie;
  9305. std::string xff;
  9306. std::string x_unicode;
  9307. std::string x_iis;
  9308. svr.Get("/check", [&](const Request &req, Response &res) {
  9309. x_custom = req.get_header_value("X-Custom");
  9310. cookie = req.get_header_value("Cookie");
  9311. xff = req.get_header_value("X-Forwarded-For");
  9312. x_unicode = req.get_header_value("X-Unicode");
  9313. x_iis = req.get_header_value("X-IIS");
  9314. res.set_content("ok", "text/plain");
  9315. });
  9316. thread t = thread([&] { svr.listen(HOST, PORT); });
  9317. auto se = detail::scope_exit([&] {
  9318. svr.stop();
  9319. t.join();
  9320. ASSERT_FALSE(svr.is_running());
  9321. });
  9322. svr.wait_until_ready();
  9323. const std::string req = "GET /check HTTP/1.1\r\n"
  9324. "Host: localhost\r\n"
  9325. "X-Custom: a%0D%0AInjected: b\r\n"
  9326. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9327. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9328. "X-Unicode: %E3%81%82\r\n"
  9329. "X-IIS: %u00E9\r\n"
  9330. "Connection: close\r\n"
  9331. "\r\n";
  9332. std::string res;
  9333. ASSERT_TRUE(send_request(5, req, &res));
  9334. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9335. // Every value must be returned verbatim (wire form), with no decoding.
  9336. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9337. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9338. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9339. EXPECT_EQ("%E3%81%82", x_unicode);
  9340. EXPECT_EQ("%u00E9", x_iis);
  9341. }
  9342. // Applications that previously relied on automatic percent-decoding can
  9343. // reproduce the old behavior by explicitly calling decode_path_component()
  9344. // or, for RFC 3986 conformance, decode_uri_component().
  9345. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9346. Server svr;
  9347. std::string decoded;
  9348. svr.Get("/check", [&](const Request &req, Response &res) {
  9349. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9350. res.set_content("ok", "text/plain");
  9351. });
  9352. thread t = thread([&] { svr.listen(HOST, PORT); });
  9353. auto se = detail::scope_exit([&] {
  9354. svr.stop();
  9355. t.join();
  9356. ASSERT_FALSE(svr.is_running());
  9357. });
  9358. svr.wait_until_ready();
  9359. const std::string req = "GET /check HTTP/1.1\r\n"
  9360. "Host: localhost\r\n"
  9361. "X-Custom: hello%20world\r\n"
  9362. "Connection: close\r\n"
  9363. "\r\n";
  9364. std::string res;
  9365. ASSERT_TRUE(send_request(5, req, &res));
  9366. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9367. EXPECT_EQ("hello world", decoded);
  9368. }
  9369. // Regression test for #2033. Browsers send Referer values that include
  9370. // percent-encoded characters such as %0A inside the URL. Decoding the
  9371. // header value would either trip the post-decode CR/LF/NUL guard (the
  9372. // original bug, returning 400) or, after that guard was relaxed, silently
  9373. // store a literal LF — both unacceptable. The wire form must round-trip.
  9374. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9375. Server svr;
  9376. std::string referer;
  9377. svr.Get("/check", [&](const Request &req, Response &res) {
  9378. referer = req.get_header_value("Referer");
  9379. res.set_content("ok", "text/plain");
  9380. });
  9381. thread t = thread([&] { svr.listen(HOST, PORT); });
  9382. auto se = detail::scope_exit([&] {
  9383. svr.stop();
  9384. t.join();
  9385. ASSERT_FALSE(svr.is_running());
  9386. });
  9387. svr.wait_until_ready();
  9388. const std::string req = "GET /check HTTP/1.1\r\n"
  9389. "Host: localhost\r\n"
  9390. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9391. "Connection: close\r\n"
  9392. "\r\n";
  9393. std::string res;
  9394. ASSERT_TRUE(send_request(5, req, &res));
  9395. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9396. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9397. }
  9398. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9399. Server svr;
  9400. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9401. res.set_header("Cache-Control", "no-cache");
  9402. res.set_chunked_content_provider(
  9403. "text/event-stream", [](size_t offset, DataSink &sink) {
  9404. std::string s = "data:";
  9405. s += std::to_string(offset);
  9406. s += "\n\n";
  9407. auto ret = sink.write(s.data(), s.size());
  9408. EXPECT_TRUE(ret);
  9409. std::this_thread::sleep_for(std::chrono::seconds(1));
  9410. return true;
  9411. });
  9412. });
  9413. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9414. svr.wait_until_ready();
  9415. Client client(HOST, PORT);
  9416. const Headers headers = {{"Accept", "text/event-stream"}};
  9417. auto get_thread = std::thread([&client, &headers]() {
  9418. auto res = client.Get(
  9419. "/events", headers,
  9420. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9421. });
  9422. auto se = detail::scope_exit([&] {
  9423. svr.stop();
  9424. get_thread.join();
  9425. listen_thread.join();
  9426. ASSERT_FALSE(svr.is_running());
  9427. });
  9428. // Give GET time to get a few messages.
  9429. std::this_thread::sleep_for(std::chrono::seconds(2));
  9430. }
  9431. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9432. httplib::Server svr;
  9433. svr.Post("/hi",
  9434. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9435. res.status = StatusCode::OK_200;
  9436. });
  9437. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9438. svr.wait_until_ready();
  9439. Client cli(HOST, PORT);
  9440. auto res = cli.Post("/hi", "data", "text/plain");
  9441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9442. EXPECT_EQ(StatusCode::OK_200, res->status);
  9443. svr.stop();
  9444. thread.join();
  9445. ASSERT_FALSE(svr.is_running());
  9446. res = cli.Post("/hi", "data", "text/plain");
  9447. ASSERT_FALSE(res);
  9448. }
  9449. TEST(ServerStopTest, ListenFailure) {
  9450. Server svr;
  9451. auto t = thread([&]() {
  9452. auto ret = svr.listen("????", PORT);
  9453. EXPECT_FALSE(ret);
  9454. });
  9455. svr.wait_until_ready();
  9456. svr.stop();
  9457. t.join();
  9458. }
  9459. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9460. TEST(ServerStopTest, Decommision) {
  9461. Server svr;
  9462. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9463. for (int i = 0; i < 4; i++) {
  9464. auto is_even = !(i % 2);
  9465. std::thread t{[&] {
  9466. try {
  9467. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9468. if (is_even) {
  9469. throw std::runtime_error("Some thing that happens to go wrong.");
  9470. }
  9471. svr.listen(HOST, PORT);
  9472. } catch (...) { svr.decommission(); }
  9473. }};
  9474. svr.wait_until_ready();
  9475. // Server is up
  9476. {
  9477. Client cli(HOST, PORT);
  9478. auto res = cli.Get("/hi");
  9479. if (is_even) {
  9480. EXPECT_FALSE(res);
  9481. } else {
  9482. EXPECT_TRUE(res);
  9483. EXPECT_EQ("hi...", res->body);
  9484. }
  9485. }
  9486. svr.stop();
  9487. t.join();
  9488. // Server is down...
  9489. {
  9490. Client cli(HOST, PORT);
  9491. auto res = cli.Get("/hi");
  9492. EXPECT_FALSE(res);
  9493. }
  9494. }
  9495. }
  9496. #endif
  9497. // Helper function for string body upload progress tests
  9498. template <typename SetupHandler, typename ClientCall>
  9499. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9500. ClientCall &&client_call,
  9501. const string &body) {
  9502. Server svr;
  9503. setup_handler(svr);
  9504. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9505. auto se = detail::scope_exit([&] {
  9506. svr.stop();
  9507. t.join();
  9508. });
  9509. svr.wait_until_ready();
  9510. Client cli(HOST, PORT);
  9511. vector<uint64_t> progress_values;
  9512. bool progress_called = false;
  9513. auto res =
  9514. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9515. progress_values.push_back(current);
  9516. progress_called = true;
  9517. return true;
  9518. });
  9519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9520. EXPECT_EQ(200, res->status);
  9521. EXPECT_TRUE(progress_called);
  9522. }
  9523. TEST(UploadProgressTest, PostStringBodyBasic) {
  9524. TestStringBodyUploadProgress(
  9525. [](Server &svr) {
  9526. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9527. res.set_content("received", "text/plain");
  9528. });
  9529. },
  9530. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9531. return cli.Post("/test", body, "text/plain", progress_callback);
  9532. },
  9533. "test data for upload progress");
  9534. }
  9535. TEST(UploadProgressTest, PutStringBodyBasic) {
  9536. TestStringBodyUploadProgress(
  9537. [](Server &svr) {
  9538. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9539. res.set_content("put received", "text/plain");
  9540. });
  9541. },
  9542. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9543. return cli.Put("/test", body, "text/plain", progress_callback);
  9544. },
  9545. "put test data for upload progress");
  9546. }
  9547. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9548. TestStringBodyUploadProgress(
  9549. [](Server &svr) {
  9550. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9551. res.set_content("patch received", "text/plain");
  9552. });
  9553. },
  9554. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9555. return cli.Patch("/test", body, "text/plain", progress_callback);
  9556. },
  9557. "patch test data for upload progress");
  9558. }
  9559. // Helper function for content provider upload progress tests
  9560. template <typename SetupHandler, typename ClientCall>
  9561. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9562. ClientCall &&client_call) {
  9563. Server svr;
  9564. setup_handler(svr);
  9565. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9566. auto se = detail::scope_exit([&] {
  9567. svr.stop();
  9568. t.join();
  9569. });
  9570. svr.wait_until_ready();
  9571. Client cli(HOST, PORT);
  9572. vector<uint64_t> progress_values;
  9573. auto res =
  9574. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9575. progress_values.push_back(current);
  9576. return true;
  9577. });
  9578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9579. EXPECT_EQ(200, res->status);
  9580. EXPECT_FALSE(progress_values.empty());
  9581. }
  9582. TEST(UploadProgressTest, PostContentProviderProgress) {
  9583. TestContentProviderUploadProgress(
  9584. [](Server &svr) {
  9585. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9586. res.set_content("provider received", "text/plain");
  9587. });
  9588. },
  9589. [](Client &cli, UploadProgress progress_callback) {
  9590. return cli.Post(
  9591. "/test", 10,
  9592. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9593. sink.os << "test data";
  9594. return true;
  9595. },
  9596. "text/plain", progress_callback);
  9597. });
  9598. }
  9599. // Helper function for multipart upload progress tests
  9600. template <typename SetupHandler, typename ClientCall>
  9601. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9602. ClientCall &&client_call,
  9603. const string &endpoint) {
  9604. Server svr;
  9605. setup_handler(svr);
  9606. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9607. auto se = detail::scope_exit([&] {
  9608. svr.stop();
  9609. t.join();
  9610. });
  9611. svr.wait_until_ready();
  9612. Client cli(HOST, PORT);
  9613. vector<uint64_t> progress_values;
  9614. UploadFormDataItems items = {
  9615. {"field1", "value1", "", ""},
  9616. {"field2", "longer value for progress tracking test", "", ""},
  9617. {"file1", "file content data for upload progress", "test.txt",
  9618. "text/plain"}};
  9619. auto res = client_call(cli, endpoint, items,
  9620. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9621. progress_values.push_back(current);
  9622. return true;
  9623. });
  9624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9625. EXPECT_EQ(200, res->status);
  9626. EXPECT_FALSE(progress_values.empty());
  9627. }
  9628. TEST(UploadProgressTest, PostMultipartProgress) {
  9629. TestMultipartUploadProgress(
  9630. [](Server &svr) {
  9631. svr.Post("/multipart", [](const Request &req, Response &res) {
  9632. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9633. res.set_content("multipart received", "text/plain");
  9634. });
  9635. },
  9636. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9637. UploadProgress progress_callback) {
  9638. return cli.Post(endpoint, items, progress_callback);
  9639. },
  9640. "/multipart");
  9641. }
  9642. // Helper function for basic download progress tests
  9643. template <typename SetupHandler, typename ClientCall>
  9644. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9645. ClientCall &&client_call, const string &endpoint,
  9646. size_t expected_content_size) {
  9647. Server svr;
  9648. setup_handler(svr);
  9649. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9650. auto se = detail::scope_exit([&] {
  9651. svr.stop();
  9652. t.join();
  9653. });
  9654. svr.wait_until_ready();
  9655. Client cli(HOST, PORT);
  9656. vector<uint64_t> progress_values;
  9657. auto res = client_call(cli, endpoint,
  9658. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9659. progress_values.push_back(current);
  9660. return true;
  9661. });
  9662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9663. EXPECT_EQ(200, res->status);
  9664. EXPECT_FALSE(progress_values.empty());
  9665. EXPECT_EQ(expected_content_size, res->body.size());
  9666. }
  9667. TEST(DownloadProgressTest, GetBasic) {
  9668. TestBasicDownloadProgress(
  9669. [](Server &svr) {
  9670. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9671. string content(1000, 'D');
  9672. res.set_content(content, "text/plain");
  9673. });
  9674. },
  9675. [](Client &cli, const string &endpoint,
  9676. DownloadProgress progress_callback) {
  9677. return cli.Get(endpoint, progress_callback);
  9678. },
  9679. "/download", 1000u);
  9680. }
  9681. // Helper function for content receiver download progress tests
  9682. template <typename SetupHandler, typename ClientCall>
  9683. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9684. ClientCall &&client_call,
  9685. const string &endpoint,
  9686. size_t expected_content_size) {
  9687. Server svr;
  9688. setup_handler(svr);
  9689. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9690. auto se = detail::scope_exit([&] {
  9691. svr.stop();
  9692. t.join();
  9693. });
  9694. svr.wait_until_ready();
  9695. Client cli(HOST, PORT);
  9696. vector<uint64_t> progress_values;
  9697. string received_body;
  9698. auto res = client_call(
  9699. cli, endpoint,
  9700. [&](const char *data, size_t data_length) -> bool {
  9701. received_body.append(data, data_length);
  9702. return true;
  9703. },
  9704. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9705. progress_values.push_back(current);
  9706. return true;
  9707. });
  9708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9709. EXPECT_EQ(200, res->status);
  9710. EXPECT_FALSE(progress_values.empty());
  9711. EXPECT_EQ(expected_content_size, received_body.size());
  9712. EXPECT_TRUE(res->body.empty());
  9713. }
  9714. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9715. TestContentReceiverDownloadProgress(
  9716. [](Server &svr) {
  9717. svr.Get("/download-receiver",
  9718. [](const Request & /*req*/, Response &res) {
  9719. string content(2000, 'R');
  9720. res.set_content(content, "text/plain");
  9721. });
  9722. },
  9723. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9724. DownloadProgress progress_callback) {
  9725. return cli.Get(endpoint, content_receiver, progress_callback);
  9726. },
  9727. "/download-receiver", 2000u);
  9728. }
  9729. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9730. // A provider reaching a pass with nothing to hand over - an empty buffer
  9731. // popped off a queue, say - must not be taken to mean the body is finished.
  9732. // It used to end the loop with the terminating chunk unwritten while the
  9733. // server still considered the response complete, so the peer waited for an
  9734. // end that never arrived.
  9735. Server svr;
  9736. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9737. auto step = std::make_shared<int>(0);
  9738. res.set_chunked_content_provider("text/plain",
  9739. [step](size_t /*offset*/, DataSink &sink) {
  9740. switch ((*step)++) {
  9741. case 0: sink.write("", 0); break;
  9742. case 1: sink.write("hello", 5); break;
  9743. default: sink.done(); break;
  9744. }
  9745. return true;
  9746. });
  9747. });
  9748. auto port = svr.bind_to_any_port(HOST);
  9749. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9750. auto listen_se = detail::scope_exit([&] {
  9751. svr.stop();
  9752. listen_thread.join();
  9753. ASSERT_FALSE(svr.is_running());
  9754. });
  9755. svr.wait_until_ready();
  9756. Client cli(HOST, port);
  9757. // Without the fix the body is never terminated, so bound the wait rather
  9758. // than letting the test hang on the default read timeout.
  9759. cli.set_read_timeout(5, 0);
  9760. auto res = cli.Get("/stream");
  9761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9762. EXPECT_EQ(StatusCode::OK_200, res->status);
  9763. EXPECT_EQ("hello", res->body);
  9764. }
  9765. TEST(StreamingTest, NoContentLengthStreaming) {
  9766. Server svr;
  9767. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9768. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9769. if (offset < 6) {
  9770. sink.os << (offset < 3 ? "a" : "b");
  9771. } else {
  9772. sink.done();
  9773. }
  9774. return true;
  9775. });
  9776. });
  9777. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9778. auto listen_se = detail::scope_exit([&] {
  9779. svr.stop();
  9780. listen_thread.join();
  9781. ASSERT_FALSE(svr.is_running());
  9782. });
  9783. svr.wait_until_ready();
  9784. Client client(HOST, PORT);
  9785. auto get_thread = std::thread([&client]() {
  9786. std::string s;
  9787. auto res =
  9788. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9789. s += std::string(data, len);
  9790. return true;
  9791. });
  9792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9793. EXPECT_EQ(StatusCode::OK_200, res->status);
  9794. EXPECT_EQ("aaabbb", s);
  9795. });
  9796. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9797. // Give GET time to get a few messages.
  9798. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9799. }
  9800. TEST(MountTest, Unmount) {
  9801. Server svr;
  9802. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9803. auto se = detail::scope_exit([&] {
  9804. svr.stop();
  9805. listen_thread.join();
  9806. ASSERT_FALSE(svr.is_running());
  9807. });
  9808. svr.wait_until_ready();
  9809. Client cli("localhost", PORT);
  9810. svr.set_mount_point("/mount2", "./www2");
  9811. auto res = cli.Get("/");
  9812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9813. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9814. res = cli.Get("/mount2/dir/test.html");
  9815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9816. EXPECT_EQ(StatusCode::OK_200, res->status);
  9817. svr.set_mount_point("/", "./www");
  9818. res = cli.Get("/dir/");
  9819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9820. EXPECT_EQ(StatusCode::OK_200, res->status);
  9821. svr.remove_mount_point("/");
  9822. res = cli.Get("/dir/");
  9823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9824. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9825. svr.remove_mount_point("/mount2");
  9826. res = cli.Get("/mount2/dir/test.html");
  9827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9828. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9829. }
  9830. TEST(MountTest, PathSegmentBoundary) {
  9831. Server svr;
  9832. svr.set_mount_point("/mount2", "./www2");
  9833. svr.set_mount_point("/", "./www");
  9834. auto port = svr.bind_to_any_port(HOST);
  9835. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9836. auto se = detail::scope_exit([&] {
  9837. svr.stop();
  9838. listen_thread.join();
  9839. ASSERT_FALSE(svr.is_running());
  9840. });
  9841. svr.wait_until_ready();
  9842. Client cli(HOST, port);
  9843. auto res = cli.Get("/mount2/dir/test.html");
  9844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9845. EXPECT_EQ(StatusCode::OK_200, res->status);
  9846. // "/mount2" must not match part-way through a path segment.
  9847. res = cli.Get("/mount2dir/test.html");
  9848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9849. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9850. // A mount point ending in '/' keeps matching every path below it.
  9851. res = cli.Get("/dir/test.html");
  9852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9853. EXPECT_EQ(StatusCode::OK_200, res->status);
  9854. }
  9855. TEST(MountTest, Redicect) {
  9856. Server svr;
  9857. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9858. auto se = detail::scope_exit([&] {
  9859. svr.stop();
  9860. listen_thread.join();
  9861. ASSERT_FALSE(svr.is_running());
  9862. });
  9863. svr.set_mount_point("/", "./www");
  9864. svr.wait_until_ready();
  9865. Client cli("localhost", PORT);
  9866. auto res = cli.Get("/dir/");
  9867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9868. EXPECT_EQ(StatusCode::OK_200, res->status);
  9869. res = cli.Get("/dir");
  9870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9871. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9872. res = cli.Get("/file");
  9873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9874. EXPECT_EQ(StatusCode::OK_200, res->status);
  9875. res = cli.Get("/file/");
  9876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9877. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9878. cli.set_follow_location(true);
  9879. res = cli.Get("/dir");
  9880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9881. EXPECT_EQ(StatusCode::OK_200, res->status);
  9882. }
  9883. TEST(MountTest, MultibytesPathName) {
  9884. Server svr;
  9885. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9886. auto se = detail::scope_exit([&] {
  9887. svr.stop();
  9888. listen_thread.join();
  9889. ASSERT_FALSE(svr.is_running());
  9890. });
  9891. svr.set_mount_point("/", "./www");
  9892. svr.wait_until_ready();
  9893. Client cli("localhost", PORT);
  9894. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9896. EXPECT_EQ(StatusCode::OK_200, res->status);
  9897. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9898. }
  9899. #ifdef _WIN32
  9900. // Issue #2435: mmap::open() must succeed even when another handle holds
  9901. // the file open for writing (e.g. an active log file).
  9902. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9903. const char *path = "mmap_concurrent_writer_test.txt";
  9904. const char *content = "hello";
  9905. {
  9906. std::ofstream f(path, std::ios::binary);
  9907. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9908. }
  9909. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9910. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9911. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9912. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9913. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9914. detail::mmap m(path);
  9915. ASSERT_TRUE(m.is_open());
  9916. EXPECT_EQ(strlen(content), m.size());
  9917. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9918. }
  9919. #endif
  9920. #ifndef _WIN32
  9921. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9922. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9923. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9924. TEST(MmapTest, FailedMappingIsNotOpen) {
  9925. const char *path = "./mmap_failed_mapping_test_dir";
  9926. ASSERT_EQ(0, ::mkdir(path, 0755));
  9927. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9928. detail::mmap m(path);
  9929. EXPECT_FALSE(m.is_open());
  9930. EXPECT_EQ(0U, m.size());
  9931. EXPECT_NE(static_cast<const void *>(m.data()),
  9932. static_cast<const void *>(MAP_FAILED));
  9933. }
  9934. #endif
  9935. TEST(KeepAliveTest, ReadTimeout) {
  9936. Server svr;
  9937. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9938. std::this_thread::sleep_for(std::chrono::seconds(2));
  9939. res.set_content("a", "text/plain");
  9940. });
  9941. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9942. res.set_content("b", "text/plain");
  9943. });
  9944. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9945. auto se = detail::scope_exit([&] {
  9946. svr.stop();
  9947. listen_thread.join();
  9948. ASSERT_FALSE(svr.is_running());
  9949. });
  9950. svr.wait_until_ready();
  9951. Client cli("localhost", PORT);
  9952. cli.set_keep_alive(true);
  9953. cli.set_read_timeout(std::chrono::seconds(1));
  9954. auto resa = cli.Get("/a");
  9955. ASSERT_FALSE(resa);
  9956. EXPECT_EQ(Error::Read, resa.error());
  9957. auto resb = cli.Get("/b");
  9958. ASSERT_TRUE(resb);
  9959. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9960. EXPECT_EQ("b", resb->body);
  9961. }
  9962. TEST(KeepAliveTest, MaxCount) {
  9963. size_t keep_alive_max_count = 3;
  9964. Server svr;
  9965. svr.set_keep_alive_max_count(keep_alive_max_count);
  9966. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9967. res.set_content("Hello World!", "text/plain");
  9968. });
  9969. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9970. auto se = detail::scope_exit([&] {
  9971. svr.stop();
  9972. listen_thread.join();
  9973. ASSERT_FALSE(svr.is_running());
  9974. });
  9975. svr.wait_until_ready();
  9976. Client cli(HOST, PORT);
  9977. cli.set_keep_alive(true);
  9978. for (size_t i = 0; i < 5; i++) {
  9979. auto result = cli.Get("/hi");
  9980. ASSERT_TRUE(result);
  9981. EXPECT_EQ(StatusCode::OK_200, result->status);
  9982. if (i == keep_alive_max_count - 1) {
  9983. EXPECT_EQ("close", result->get_header_value("Connection"));
  9984. } else {
  9985. EXPECT_FALSE(result->has_header("Connection"));
  9986. }
  9987. }
  9988. }
  9989. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  9990. // can pull the next one into the server's buffer. The server must serve it
  9991. // without waiting for the socket to become readable again. The keep-alive
  9992. // timeout outlasts the client's read timeout, so a request left waiting for it
  9993. // shows up as a missing response.
  9994. static void serve_pipelining_routes(Server &svr,
  9995. const std::function<void(int)> &client) {
  9996. svr.set_keep_alive_timeout(5);
  9997. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  9998. res.set_content("hi " + req.matches[1].str(), "text/plain");
  9999. });
  10000. svr.Post("/echo", [](const Request &req, Response &res) {
  10001. res.set_content("echo " + req.body, "text/plain");
  10002. });
  10003. auto port = svr.bind_to_any_port(HOST);
  10004. thread t = thread([&] { svr.listen_after_bind(); });
  10005. auto se = detail::scope_exit([&] {
  10006. svr.stop();
  10007. t.join();
  10008. });
  10009. svr.wait_until_ready();
  10010. client(port);
  10011. }
  10012. static std::string
  10013. send_pipelined_requests(const std::vector<std::string> &parts) {
  10014. Server svr;
  10015. std::string res;
  10016. serve_pipelining_routes(svr, [&](int port) {
  10017. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10018. });
  10019. return res;
  10020. }
  10021. static void expect_in_order(const std::string &res,
  10022. const std::vector<std::string> &bodies) {
  10023. size_t pos = 0;
  10024. for (const auto &body : bodies) {
  10025. pos = res.find(body, pos);
  10026. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10027. pos += body.size();
  10028. }
  10029. }
  10030. TEST(KeepAliveTest, PipelinedRequests) {
  10031. auto res = send_pipelined_requests(
  10032. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10033. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10034. "Content-Length: 4\r\n\r\nbody"
  10035. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10036. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10037. }
  10038. // The second request starts in the server's buffer and ends on the socket.
  10039. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10040. auto res =
  10041. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10042. "GET /hi/2 HTTP/1.1\r\nHo",
  10043. "st: localhost\r\nConnection: close\r\n\r\n"});
  10044. expect_in_order(res, {"hi 1", "hi 2"});
  10045. }
  10046. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10047. // CRLF after a body does not turn into a 400 for the next request.
  10048. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10049. auto res = send_pipelined_requests(
  10050. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10051. "Content-Length: 4\r\n\r\nbody\r\n"
  10052. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10053. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10054. expect_in_order(res, {"echo body", "hi 2"});
  10055. }
  10056. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10057. // must not be served as the next request.
  10058. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10059. auto res = send_pipelined_requests(
  10060. {"INVALID REQUEST LINE\r\n\r\n"
  10061. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10062. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10063. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10064. }
  10065. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10066. // Over TLS, the next request is held by the TLS library as already decrypted
  10067. // data rather than on the socket.
  10068. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10069. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10070. std::string res;
  10071. serve_pipelining_routes(svr, [&](int port) {
  10072. auto error = Error::Success;
  10073. auto sock = detail::create_client_socket(
  10074. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10075. /*connection_timeout_sec=*/5, 0,
  10076. /*read_timeout_sec=*/2, 0,
  10077. /*write_timeout_sec=*/5, 0, std::string(), error);
  10078. ASSERT_NE(INVALID_SOCKET, sock);
  10079. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  10080. auto ctx = SSL_CTX_new(TLS_client_method());
  10081. auto ssl = SSL_new(ctx);
  10082. auto ssl_se = detail::scope_exit([&] {
  10083. SSL_free(ssl);
  10084. SSL_CTX_free(ctx);
  10085. });
  10086. SSL_set_fd(ssl, static_cast<int>(sock));
  10087. ASSERT_EQ(1, SSL_connect(ssl));
  10088. // One write, so all three requests arrive in one TLS record
  10089. const std::string req =
  10090. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10091. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10092. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  10093. ASSERT_EQ(static_cast<int>(req.size()),
  10094. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  10095. char buf[512];
  10096. int n;
  10097. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10098. res.append(buf, static_cast<size_t>(n));
  10099. }
  10100. });
  10101. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10102. }
  10103. #endif
  10104. TEST(KeepAliveTest, Issue1041) {
  10105. Server svr;
  10106. svr.set_keep_alive_timeout(3);
  10107. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10108. res.set_content("Hello World!", "text/plain");
  10109. });
  10110. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10111. auto se = detail::scope_exit([&] {
  10112. svr.stop();
  10113. listen_thread.join();
  10114. ASSERT_FALSE(svr.is_running());
  10115. });
  10116. svr.wait_until_ready();
  10117. Client cli(HOST, PORT);
  10118. cli.set_keep_alive(true);
  10119. auto result = cli.Get("/hi");
  10120. ASSERT_TRUE(result);
  10121. EXPECT_EQ(StatusCode::OK_200, result->status);
  10122. std::this_thread::sleep_for(std::chrono::seconds(5));
  10123. result = cli.Get("/hi");
  10124. ASSERT_TRUE(result);
  10125. EXPECT_EQ(StatusCode::OK_200, result->status);
  10126. }
  10127. TEST(KeepAliveTest, Issue1959) {
  10128. Server svr;
  10129. svr.set_keep_alive_timeout(5);
  10130. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10131. res.set_content("a", "text/plain");
  10132. });
  10133. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10134. auto se = detail::scope_exit([&] {
  10135. if (!svr.is_running()) return;
  10136. svr.stop();
  10137. listen_thread.join();
  10138. ASSERT_FALSE(svr.is_running());
  10139. });
  10140. svr.wait_until_ready();
  10141. Client cli("localhost", PORT);
  10142. cli.set_keep_alive(true);
  10143. using namespace std::chrono;
  10144. auto start = steady_clock::now();
  10145. cli.Get("/a");
  10146. svr.stop();
  10147. listen_thread.join();
  10148. auto end = steady_clock::now();
  10149. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10150. EXPECT_LT(elapsed, 5000);
  10151. }
  10152. #ifdef CPPHTTPLIB_SSL_ENABLED
  10153. TEST(KeepAliveTest, SSLClientReconnection) {
  10154. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10155. ASSERT_TRUE(svr.is_valid());
  10156. svr.set_keep_alive_timeout(1);
  10157. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10158. res.set_content("Hello World!", "text/plain");
  10159. });
  10160. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10161. auto se = detail::scope_exit([&] {
  10162. svr.stop();
  10163. listen_thread.join();
  10164. ASSERT_FALSE(svr.is_running());
  10165. });
  10166. svr.wait_until_ready();
  10167. SSLClient cli(HOST, PORT);
  10168. cli.enable_server_certificate_verification(false);
  10169. cli.set_keep_alive(true);
  10170. auto result = cli.Get("/hi");
  10171. ASSERT_TRUE(result);
  10172. EXPECT_EQ(StatusCode::OK_200, result->status);
  10173. result = cli.Get("/hi");
  10174. ASSERT_TRUE(result);
  10175. EXPECT_EQ(StatusCode::OK_200, result->status);
  10176. std::this_thread::sleep_for(std::chrono::seconds(2));
  10177. // Recoonect
  10178. result = cli.Get("/hi");
  10179. ASSERT_TRUE(result);
  10180. EXPECT_EQ(StatusCode::OK_200, result->status);
  10181. result = cli.Get("/hi");
  10182. ASSERT_TRUE(result);
  10183. EXPECT_EQ(StatusCode::OK_200, result->status);
  10184. }
  10185. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10186. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10187. ASSERT_TRUE(svr.is_valid());
  10188. svr.set_keep_alive_timeout(1);
  10189. std::string content = "reconnect";
  10190. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10191. res.set_content("Hello World!", "text/plain");
  10192. });
  10193. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10194. auto se = detail::scope_exit([&] {
  10195. svr.stop();
  10196. listen_thread.join();
  10197. ASSERT_FALSE(svr.is_running());
  10198. });
  10199. svr.wait_until_ready();
  10200. SSLClient cli(HOST, PORT);
  10201. cli.enable_server_certificate_verification(false);
  10202. cli.set_keep_alive(true);
  10203. auto result = cli.Post(
  10204. "/hi", content.size(),
  10205. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10206. sink.write(content.c_str(), content.size());
  10207. return true;
  10208. },
  10209. "text/plain");
  10210. ASSERT_TRUE(result);
  10211. EXPECT_EQ(200, result->status);
  10212. std::this_thread::sleep_for(std::chrono::seconds(2));
  10213. // Recoonect
  10214. result = cli.Post(
  10215. "/hi", content.size(),
  10216. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10217. sink.write(content.c_str(), content.size());
  10218. return true;
  10219. },
  10220. "text/plain");
  10221. ASSERT_TRUE(result);
  10222. EXPECT_EQ(200, result->status);
  10223. result = cli.Post(
  10224. "/hi", content.size(),
  10225. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10226. sink.write(content.c_str(), content.size());
  10227. return true;
  10228. },
  10229. "text/plain");
  10230. ASSERT_TRUE(result);
  10231. EXPECT_EQ(200, result->status);
  10232. }
  10233. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10234. using namespace httplib::tls;
  10235. {
  10236. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10237. ASSERT_TRUE(svr.is_valid());
  10238. svr.Get("/sni", [&](const Request &req, Response &res) {
  10239. std::string expected = req.sni();
  10240. EXPECT_EQ(expected, req.get_param_value("expected"));
  10241. res.set_content("ok", "text/plain");
  10242. });
  10243. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10244. auto se = detail::scope_exit([&] {
  10245. svr.stop();
  10246. listen_thread.join();
  10247. ASSERT_FALSE(svr.is_running());
  10248. });
  10249. svr.wait_until_ready();
  10250. {
  10251. SSLClient cli("localhost", PORT);
  10252. cli.enable_server_certificate_verification(false);
  10253. auto res = cli.Get("/sni?expected=localhost");
  10254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10255. }
  10256. {
  10257. SSLClient cli("::1", PORT);
  10258. cli.enable_server_certificate_verification(false);
  10259. auto res = cli.Get("/sni?expected=");
  10260. // NOTE: This may fail if the server is listening on IPv4 only
  10261. // (e.g., when localhost resolves to 127.0.0.1 only)
  10262. if (res) {
  10263. EXPECT_EQ(StatusCode::OK_200, res->status);
  10264. } else {
  10265. EXPECT_EQ(Error::Connection, res.error());
  10266. }
  10267. }
  10268. }
  10269. }
  10270. #endif
  10271. TEST(ClientProblemDetectionTest, ContentProvider) {
  10272. Server svr;
  10273. size_t content_length = 1024 * 1024;
  10274. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10275. res.set_content_provider(
  10276. content_length, "text/plain",
  10277. [&](size_t offset, size_t length, DataSink &sink) {
  10278. auto out_len = std::min(length, static_cast<size_t>(1024));
  10279. std::string out(out_len, '@');
  10280. sink.write(out.data(), out_len);
  10281. return offset < 4096;
  10282. },
  10283. [](bool success) { ASSERT_FALSE(success); });
  10284. });
  10285. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10286. res.set_content_provider(
  10287. 0, "text/plain",
  10288. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10289. EXPECT_TRUE(false);
  10290. return true;
  10291. },
  10292. [](bool success) { ASSERT_FALSE(success); });
  10293. });
  10294. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10295. auto se = detail::scope_exit([&] {
  10296. svr.stop();
  10297. listen_thread.join();
  10298. ASSERT_FALSE(svr.is_running());
  10299. });
  10300. svr.wait_until_ready();
  10301. Client cli("localhost", PORT);
  10302. {
  10303. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10304. size_t /*data_length*/) { return false; });
  10305. ASSERT_FALSE(res);
  10306. }
  10307. {
  10308. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10309. size_t /*data_length*/) { return false; });
  10310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10311. }
  10312. }
  10313. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10314. // A provider that reports success without writing anything and without
  10315. // calling done() used to be handed the same offset and length again on every
  10316. // pass, so it spun for as long as the peer stayed connected.
  10317. Server svr;
  10318. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10319. res.set_content("ok", "text/plain");
  10320. });
  10321. auto port = svr.bind_to_any_port(HOST);
  10322. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10323. auto se = detail::scope_exit([&] {
  10324. svr.stop();
  10325. listen_thread.join();
  10326. ASSERT_FALSE(svr.is_running());
  10327. });
  10328. svr.wait_until_ready();
  10329. std::atomic<int> call_count{0};
  10330. Client cli(HOST, port);
  10331. auto res = cli.Post(
  10332. "/", 1024,
  10333. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10334. // Give up after enough passes to show the spin, so that losing the
  10335. // check below fails this test instead of hanging it.
  10336. return ++call_count < 100;
  10337. },
  10338. "text/plain");
  10339. ASSERT_FALSE(res);
  10340. EXPECT_EQ(Error::Write, res.error());
  10341. EXPECT_EQ(1, call_count.load());
  10342. }
  10343. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10344. // A writer only has to assign `write`. The other three used to be left as
  10345. // empty std::functions, so a provider calling one threw
  10346. // std::bad_function_call out of the thread running it and took the whole
  10347. // process down.
  10348. DataSink sink;
  10349. std::string written;
  10350. sink.write = [&](const char *data, size_t data_len) {
  10351. written.append(data, data_len);
  10352. return true;
  10353. };
  10354. EXPECT_TRUE(sink.is_writable());
  10355. sink.done();
  10356. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10357. EXPECT_TRUE(written.empty());
  10358. }
  10359. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10360. // A sink that cannot carry trailers still has to finish.
  10361. DataSink sink;
  10362. auto done_count = 0;
  10363. sink.done = [&]() { done_count++; };
  10364. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10365. EXPECT_EQ(1, done_count);
  10366. }
  10367. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10368. Server svr;
  10369. const std::string body(4096, 'x');
  10370. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10371. res.set_content_provider(body.size(), "text/plain",
  10372. [&](size_t offset, size_t length, DataSink &sink) {
  10373. sink.write(body.data() + offset, length);
  10374. sink.done();
  10375. return true;
  10376. });
  10377. });
  10378. auto port = svr.bind_to_any_port(HOST);
  10379. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10380. auto se = detail::scope_exit([&] {
  10381. svr.stop();
  10382. listen_thread.join();
  10383. ASSERT_FALSE(svr.is_running());
  10384. });
  10385. svr.wait_until_ready();
  10386. Client cli(HOST, port);
  10387. auto res = cli.Get("/");
  10388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10389. EXPECT_EQ(StatusCode::OK_200, res->status);
  10390. EXPECT_EQ(body, res->body);
  10391. }
  10392. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10393. Server svr;
  10394. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10395. res.set_content_provider(
  10396. 1024, "text/plain",
  10397. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10398. sink.write("hello", 5);
  10399. sink.done(); // short of the 1024 bytes the response promised
  10400. return true;
  10401. });
  10402. });
  10403. auto port = svr.bind_to_any_port(HOST);
  10404. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10405. auto se = detail::scope_exit([&] {
  10406. svr.stop();
  10407. listen_thread.join();
  10408. ASSERT_FALSE(svr.is_running());
  10409. });
  10410. svr.wait_until_ready();
  10411. Client cli(HOST, port);
  10412. cli.set_read_timeout(5, 0);
  10413. // The response is short of its Content-Length, so the client cannot read a
  10414. // complete body. What matters is that this returns at all: a no-op done()
  10415. // would leave the writer looping over a provider that never makes progress.
  10416. auto res = cli.Get("/");
  10417. EXPECT_FALSE(res);
  10418. }
  10419. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10420. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10421. // The compressed path builds the whole body before connecting, so this
  10422. // fails client-side and never reaches a server.
  10423. Client cli(HOST, PORT);
  10424. cli.set_compress(true);
  10425. auto res = cli.Post(
  10426. "/", 1024,
  10427. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10428. sink.write("hello", 5);
  10429. sink.done(); // short of the 1024 bytes the request announced
  10430. return true;
  10431. },
  10432. "text/plain");
  10433. ASSERT_FALSE(res);
  10434. EXPECT_EQ(Error::Write, res.error());
  10435. }
  10436. #endif
  10437. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10438. Server svr;
  10439. svr.set_error_handler([](Request const &, Response &res) -> void {
  10440. res.set_chunked_content_provider(
  10441. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10442. sink.os << "hello";
  10443. sink.os << "world";
  10444. sink.done();
  10445. return true;
  10446. });
  10447. });
  10448. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10449. auto se = detail::scope_exit([&] {
  10450. svr.stop();
  10451. listen_thread.join();
  10452. ASSERT_FALSE(svr.is_running());
  10453. });
  10454. svr.wait_until_ready();
  10455. Client cli("localhost", PORT);
  10456. auto res = cli.Get("/");
  10457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10458. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10459. EXPECT_EQ("helloworld", res->body);
  10460. }
  10461. // A body set after a content provider must replace it, not be sent through it.
  10462. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  10463. Server svr;
  10464. svr.set_mount_point("/", "./www");
  10465. svr.set_file_request_handler([](const Request &req, Response &res) {
  10466. if (req.path == "/dir/test.html") {
  10467. res.status = StatusCode::Forbidden_403;
  10468. res.set_content(std::string(5000, 'D'), "text/plain");
  10469. } else if (req.path == "/file") {
  10470. res.status = StatusCode::Forbidden_403;
  10471. res.body = "Denied";
  10472. }
  10473. });
  10474. auto port = svr.bind_to_any_port(HOST);
  10475. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10476. auto se = detail::scope_exit([&] {
  10477. svr.stop();
  10478. t.join();
  10479. ASSERT_FALSE(svr.is_running());
  10480. });
  10481. svr.wait_until_ready();
  10482. Client cli(HOST, port);
  10483. {
  10484. auto res = cli.Get("/dir/test.html");
  10485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10486. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10487. EXPECT_EQ(std::string(5000, 'D'), res->body);
  10488. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  10489. }
  10490. {
  10491. auto res = cli.Get("/file");
  10492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10493. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10494. EXPECT_EQ("Denied", res->body);
  10495. }
  10496. {
  10497. auto res = cli.Get("/dir/index.html");
  10498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10499. EXPECT_EQ(StatusCode::OK_200, res->status);
  10500. EXPECT_EQ(0U, res->body.find("<html>"));
  10501. }
  10502. }
  10503. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  10504. Server svr;
  10505. std::vector<bool> released;
  10506. std::mutex released_mutex;
  10507. auto releaser = [&](bool success) {
  10508. std::lock_guard<std::mutex> guard(released_mutex);
  10509. released.push_back(success);
  10510. };
  10511. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  10512. return sink.write(&"hello"[offset], length);
  10513. };
  10514. svr.Get("/sized", [&](const Request &, Response &res) {
  10515. res.status = StatusCode::NotFound_404;
  10516. res.set_content_provider(5, "text/plain", provider, releaser);
  10517. });
  10518. svr.Get("/chunked", [&](const Request &, Response &res) {
  10519. res.status = StatusCode::ServiceUnavailable_503;
  10520. res.set_chunked_content_provider(
  10521. "text/plain",
  10522. [](size_t, DataSink &sink) {
  10523. sink.os << "chunk";
  10524. sink.done();
  10525. return true;
  10526. },
  10527. releaser);
  10528. });
  10529. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  10530. res.set_content_provider(5, "text/plain", provider, releaser);
  10531. throw std::runtime_error("after the provider");
  10532. });
  10533. svr.set_error_handler([](const Request &req, Response &res) {
  10534. // Leave the exception handler's content to it.
  10535. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  10536. res.set_content(std::string(1000, 'E'), "text/html");
  10537. return Server::HandlerResponse::Handled;
  10538. });
  10539. svr.set_exception_handler(
  10540. [](const Request &, Response &res, std::exception_ptr) {
  10541. res.status = StatusCode::InternalServerError_500;
  10542. res.set_content(std::string(1000, 'X'), "text/html");
  10543. });
  10544. auto port = svr.bind_to_any_port(HOST);
  10545. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10546. auto se = detail::scope_exit([&] {
  10547. svr.stop();
  10548. t.join();
  10549. ASSERT_FALSE(svr.is_running());
  10550. });
  10551. svr.wait_until_ready();
  10552. Client cli(HOST, port);
  10553. {
  10554. auto res = cli.Get("/sized");
  10555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10556. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10557. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10558. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  10559. }
  10560. {
  10561. auto res = cli.Get("/chunked");
  10562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10563. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  10564. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10565. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  10566. }
  10567. {
  10568. auto res = cli.Get("/throw");
  10569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10570. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  10571. EXPECT_EQ(std::string(1000, 'X'), res->body);
  10572. }
  10573. std::lock_guard<std::mutex> guard(released_mutex);
  10574. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  10575. }
  10576. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  10577. Server svr;
  10578. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  10579. return sink.write(&"abc"[offset], length);
  10580. };
  10581. svr.Get("/file-then-body", [](const Request &, Response &res) {
  10582. res.set_file_content("./www/dir/test.html");
  10583. res.set_content("body", "text/plain");
  10584. });
  10585. svr.Get("/body-then-file", [](const Request &, Response &res) {
  10586. res.set_content(std::string(100, 'B'), "text/plain");
  10587. res.set_file_content("./www/dir/test.html");
  10588. });
  10589. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  10590. res.set_content(std::string(100, 'B'), "text/plain");
  10591. res.set_content_provider(3, "text/plain", abc);
  10592. });
  10593. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  10594. res.set_content_provider(3, "text/plain", abc);
  10595. res.set_content(std::string(100, 'B'), "text/plain");
  10596. });
  10597. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  10598. res.set_content_provider(3, "text/plain", abc);
  10599. res.body = "direct";
  10600. });
  10601. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  10602. res.set_file_content("./www/dir/test.html");
  10603. res.body = "direct";
  10604. });
  10605. auto port = svr.bind_to_any_port(HOST);
  10606. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10607. auto se = detail::scope_exit([&] {
  10608. svr.stop();
  10609. t.join();
  10610. ASSERT_FALSE(svr.is_running());
  10611. });
  10612. svr.wait_until_ready();
  10613. Client cli(HOST, port);
  10614. auto expect_body = [&](const char *path, const std::string &body) {
  10615. // Uncompressed, so Content-Length can be compared with the body.
  10616. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  10617. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  10618. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10619. EXPECT_EQ(body, res->body) << path;
  10620. EXPECT_EQ(std::to_string(body.size()),
  10621. res->get_header_value("Content-Length"))
  10622. << path;
  10623. };
  10624. expect_body("/file-then-body", "body");
  10625. expect_body("/body-then-file", "test.html");
  10626. expect_body("/body-then-provider", "abc");
  10627. expect_body("/provider-then-body", std::string(100, 'B'));
  10628. expect_body("/provider-then-direct-body", "direct");
  10629. expect_body("/file-then-direct-body", "direct");
  10630. // Ranges are checked against the body, not the dropped provider.
  10631. {
  10632. auto res = cli.Get("/provider-then-direct-body",
  10633. Headers{{make_range_header({{1, 2}})}});
  10634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10635. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10636. EXPECT_EQ("ir", res->body);
  10637. }
  10638. {
  10639. auto res = cli.Get("/file-then-direct-body",
  10640. Headers{{make_range_header({{7, 8}})}});
  10641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10642. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  10643. }
  10644. }
  10645. // Forward declaration (see the base64_encode note).
  10646. namespace httplib {
  10647. namespace detail {
  10648. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  10649. const std::string &content_type,
  10650. EncodingType encoding);
  10651. } // namespace detail
  10652. } // namespace httplib
  10653. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  10654. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  10655. ASSERT_TRUE(mm->is_open());
  10656. Response res;
  10657. detail::set_file_content_provider(res, mm, "text/html",
  10658. detail::EncodingType::None);
  10659. std::string out;
  10660. DataSink sink;
  10661. sink.write = [&](const char *d, size_t l) {
  10662. out.append(d, l);
  10663. return true;
  10664. };
  10665. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  10666. EXPECT_EQ("test.html", out);
  10667. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  10668. EXPECT_EQ("test.html", out);
  10669. }
  10670. TEST(LongPollingTest, ClientCloseDetection) {
  10671. Server svr;
  10672. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10673. res.set_chunked_content_provider(
  10674. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10675. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10676. sink.os << "hello";
  10677. auto count = 10;
  10678. while (count > 0 && sink.is_writable()) {
  10679. this_thread::sleep_for(chrono::milliseconds(10));
  10680. count--;
  10681. }
  10682. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10683. return true;
  10684. });
  10685. });
  10686. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10687. auto se = detail::scope_exit([&] {
  10688. svr.stop();
  10689. listen_thread.join();
  10690. ASSERT_FALSE(svr.is_running());
  10691. });
  10692. svr.wait_until_ready();
  10693. Client cli("localhost", PORT);
  10694. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10695. EXPECT_EQ("hello", string(data, data_length));
  10696. return false; // close the socket immediately.
  10697. });
  10698. ASSERT_FALSE(res);
  10699. }
  10700. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10701. Server svr;
  10702. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10703. res.set_chunked_content_provider(
  10704. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10705. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10706. sink.os << "hello";
  10707. EXPECT_TRUE(sink.os.good());
  10708. // Wait for the client to close the connection
  10709. auto count = 10;
  10710. while (count > 0 && sink.is_writable()) {
  10711. this_thread::sleep_for(chrono::milliseconds(10));
  10712. count--;
  10713. }
  10714. // After client disconnect, write repeatedly until the socket
  10715. // write actually fails (small writes may be absorbed by the
  10716. // kernel buffer)
  10717. std::string chunk(1024, 'x');
  10718. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10719. sink.os << chunk;
  10720. }
  10721. EXPECT_TRUE(sink.os.fail());
  10722. return true;
  10723. });
  10724. });
  10725. auto port = svr.bind_to_any_port("localhost");
  10726. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10727. auto se = detail::scope_exit([&] {
  10728. svr.stop();
  10729. listen_thread.join();
  10730. ASSERT_FALSE(svr.is_running());
  10731. });
  10732. svr.wait_until_ready();
  10733. Client cli("localhost", port);
  10734. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10735. EXPECT_EQ("hello", string(data, data_length));
  10736. return false; // close the socket immediately.
  10737. });
  10738. ASSERT_FALSE(res);
  10739. }
  10740. TEST(GetWithParametersTest, GetWithParameters) {
  10741. Server svr;
  10742. svr.Get("/", [&](const Request &req, Response &) {
  10743. EXPECT_EQ("world", req.get_param_value("hello"));
  10744. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10745. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10746. });
  10747. svr.Get("/params", [&](const Request &req, Response &) {
  10748. EXPECT_EQ("world", req.get_param_value("hello"));
  10749. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10750. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10751. });
  10752. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10753. EXPECT_EQ("resource-id", req.matches[1]);
  10754. EXPECT_EQ("foo", req.get_param_value("param1"));
  10755. EXPECT_EQ("bar", req.get_param_value("param2"));
  10756. });
  10757. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10758. EXPECT_EQ("user-id", req.path_params.at("id"));
  10759. EXPECT_EQ("foo", req.get_param_value("param1"));
  10760. EXPECT_EQ("bar", req.get_param_value("param2"));
  10761. });
  10762. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10763. auto se = detail::scope_exit([&] {
  10764. svr.stop();
  10765. listen_thread.join();
  10766. ASSERT_FALSE(svr.is_running());
  10767. });
  10768. svr.wait_until_ready();
  10769. {
  10770. Client cli(HOST, PORT);
  10771. Params params;
  10772. params.emplace("hello", "world");
  10773. params.emplace("hello2", "world2");
  10774. params.emplace("hello3", "world3");
  10775. auto res = cli.Get("/", params, Headers{});
  10776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10777. EXPECT_EQ(StatusCode::OK_200, res->status);
  10778. }
  10779. {
  10780. Client cli(HOST, PORT);
  10781. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10783. EXPECT_EQ(StatusCode::OK_200, res->status);
  10784. }
  10785. {
  10786. Client cli(HOST, PORT);
  10787. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10789. EXPECT_EQ(StatusCode::OK_200, res->status);
  10790. }
  10791. {
  10792. Client cli(HOST, PORT);
  10793. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10795. EXPECT_EQ(StatusCode::OK_200, res->status);
  10796. }
  10797. }
  10798. TEST(GetWithParametersTest, GetWithParameters2) {
  10799. Server svr;
  10800. svr.Get("/", [&](const Request &req, Response &res) {
  10801. auto text = req.get_param_value("hello");
  10802. res.set_content(text, "text/plain");
  10803. });
  10804. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10805. auto se = detail::scope_exit([&] {
  10806. svr.stop();
  10807. listen_thread.join();
  10808. ASSERT_FALSE(svr.is_running());
  10809. });
  10810. svr.wait_until_ready();
  10811. Client cli("localhost", PORT);
  10812. Params params;
  10813. params.emplace("hello", "world");
  10814. std::string body;
  10815. auto res = cli.Get("/", params, Headers{},
  10816. [&](const char *data, size_t data_length) {
  10817. body.append(data, data_length);
  10818. return true;
  10819. });
  10820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10821. EXPECT_EQ(StatusCode::OK_200, res->status);
  10822. EXPECT_EQ("world", body);
  10823. }
  10824. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10825. Server svr;
  10826. svr.Get("/search", [&](const Request &req, Response &res) {
  10827. auto q = req.get_param_value("q");
  10828. res.set_content(q, "text/plain");
  10829. });
  10830. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10831. auto se = detail::scope_exit([&] {
  10832. svr.stop();
  10833. listen_thread.join();
  10834. ASSERT_FALSE(svr.is_running());
  10835. });
  10836. svr.wait_until_ready();
  10837. Client cli("localhost", PORT);
  10838. // Verify that Get(path, params) works without requiring Headers argument
  10839. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10841. EXPECT_EQ(StatusCode::OK_200, res->status);
  10842. EXPECT_EQ("cpp-httplib", res->body);
  10843. }
  10844. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10845. auto host = "httpbingo.org";
  10846. auto path = std::string{"/range/32"};
  10847. #ifdef CPPHTTPLIB_SSL_ENABLED
  10848. SSLClient cli(host);
  10849. #else
  10850. Client cli(host);
  10851. #endif
  10852. cli.set_default_headers({make_range_header({{1, 10}})});
  10853. cli.set_connection_timeout(5);
  10854. {
  10855. auto res = cli.Get(path);
  10856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10857. EXPECT_EQ("bcdefghijk", res->body);
  10858. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10859. }
  10860. {
  10861. auto res = cli.Get(path);
  10862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10863. EXPECT_EQ("bcdefghijk", res->body);
  10864. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10865. }
  10866. }
  10867. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10868. Server svr;
  10869. svr.set_default_headers({{"Hello", "World"}});
  10870. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10871. res.set_content("ok", "text/plain");
  10872. });
  10873. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10874. auto se = detail::scope_exit([&] {
  10875. svr.stop();
  10876. listen_thread.join();
  10877. ASSERT_FALSE(svr.is_running());
  10878. });
  10879. svr.wait_until_ready();
  10880. Client cli("localhost", PORT);
  10881. auto res = cli.Get("/");
  10882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10883. EXPECT_EQ(StatusCode::OK_200, res->status);
  10884. EXPECT_EQ("ok", res->body);
  10885. EXPECT_EQ("World", res->get_header_value("Hello"));
  10886. }
  10887. #ifdef CPPHTTPLIB_SSL_ENABLED
  10888. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10889. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10890. ASSERT_TRUE(svr.is_valid());
  10891. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10892. std::this_thread::sleep_for(std::chrono::seconds(2));
  10893. res.set_content("a", "text/plain");
  10894. });
  10895. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10896. res.set_content("b", "text/plain");
  10897. });
  10898. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10899. auto se = detail::scope_exit([&] {
  10900. svr.stop();
  10901. listen_thread.join();
  10902. ASSERT_FALSE(svr.is_running());
  10903. });
  10904. svr.wait_until_ready();
  10905. SSLClient cli("localhost", PORT);
  10906. cli.enable_server_certificate_verification(false);
  10907. cli.set_keep_alive(true);
  10908. cli.set_read_timeout(std::chrono::seconds(1));
  10909. auto resa = cli.Get("/a");
  10910. ASSERT_TRUE(!resa);
  10911. EXPECT_EQ(Error::Read, resa.error());
  10912. auto resb = cli.Get("/b");
  10913. ASSERT_TRUE(resb);
  10914. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10915. EXPECT_EQ("b", resb->body);
  10916. }
  10917. // Closing an idle keep-alive connection sends close_notify and returns. The
  10918. // server must not wait for the client's close_notify: an idle client never
  10919. // sends one, so the worker would be held until the read timeout expires, and
  10920. // stop() would wait for it.
  10921. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10922. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10923. ASSERT_TRUE(svr.is_valid());
  10924. svr.set_keep_alive_timeout(1);
  10925. svr.set_read_timeout(10, 0);
  10926. svr.Get("/", [](const Request &, Response &res) {
  10927. res.set_content("ok", "text/plain");
  10928. });
  10929. auto port = svr.bind_to_any_port(HOST);
  10930. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10931. auto se = detail::scope_exit([&] {
  10932. if (listen_thread.joinable()) {
  10933. svr.stop();
  10934. listen_thread.join();
  10935. }
  10936. });
  10937. svr.wait_until_ready();
  10938. SSLClient cli(HOST, port);
  10939. cli.enable_server_certificate_verification(false);
  10940. cli.set_keep_alive(true);
  10941. auto res = cli.Get("/");
  10942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10943. EXPECT_EQ(StatusCode::OK_200, res->status);
  10944. // Stay idle past the keep-alive timeout so the server closes the connection.
  10945. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10946. auto start = std::chrono::steady_clock::now();
  10947. svr.stop();
  10948. listen_thread.join();
  10949. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10950. std::chrono::steady_clock::now() - start)
  10951. .count();
  10952. EXPECT_LT(elapsed, 3000);
  10953. }
  10954. #endif
  10955. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10956. protected:
  10957. ServerTestWithAI_PASSIVE()
  10958. : cli_(HOST, PORT)
  10959. #ifdef CPPHTTPLIB_SSL_ENABLED
  10960. ,
  10961. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10962. #endif
  10963. {
  10964. #ifdef CPPHTTPLIB_SSL_ENABLED
  10965. cli_.enable_server_certificate_verification(false);
  10966. #endif
  10967. }
  10968. virtual void SetUp() {
  10969. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10970. res.set_content("Hello World!", "text/plain");
  10971. });
  10972. t_ = thread(
  10973. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10974. svr_.wait_until_ready();
  10975. }
  10976. virtual void TearDown() {
  10977. svr_.stop();
  10978. t_.join();
  10979. }
  10980. #ifdef CPPHTTPLIB_SSL_ENABLED
  10981. SSLClient cli_;
  10982. SSLServer svr_;
  10983. #else
  10984. Client cli_;
  10985. Server svr_;
  10986. #endif
  10987. thread t_;
  10988. };
  10989. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10990. auto res = cli_.Get("/hi");
  10991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10992. EXPECT_EQ(StatusCode::OK_200, res->status);
  10993. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10994. EXPECT_EQ("Hello World!", res->body);
  10995. }
  10996. class ServerUpDownTest : public ::testing::Test {
  10997. protected:
  10998. ServerUpDownTest() : cli_(HOST, PORT) {}
  10999. virtual void SetUp() {
  11000. t_ = thread([&]() {
  11001. svr_.bind_to_any_port(HOST);
  11002. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11003. ASSERT_TRUE(svr_.listen_after_bind());
  11004. });
  11005. svr_.wait_until_ready();
  11006. }
  11007. virtual void TearDown() {
  11008. svr_.stop();
  11009. t_.join();
  11010. }
  11011. Client cli_;
  11012. Server svr_;
  11013. thread t_;
  11014. };
  11015. TEST_F(ServerUpDownTest, QuickStartStop) {
  11016. // Should not crash, especially when run with
  11017. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11018. }
  11019. class PayloadMaxLengthTest : public ::testing::Test {
  11020. protected:
  11021. PayloadMaxLengthTest()
  11022. : cli_(HOST, PORT)
  11023. #ifdef CPPHTTPLIB_SSL_ENABLED
  11024. ,
  11025. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11026. #endif
  11027. {
  11028. #ifdef CPPHTTPLIB_SSL_ENABLED
  11029. cli_.enable_server_certificate_verification(false);
  11030. #endif
  11031. }
  11032. virtual void SetUp() {
  11033. svr_.set_payload_max_length(8);
  11034. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11035. res.set_content("test", "text/plain");
  11036. });
  11037. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11038. svr_.wait_until_ready();
  11039. }
  11040. virtual void TearDown() {
  11041. svr_.stop();
  11042. t_.join();
  11043. }
  11044. #ifdef CPPHTTPLIB_SSL_ENABLED
  11045. SSLClient cli_;
  11046. SSLServer svr_;
  11047. #else
  11048. Client cli_;
  11049. Server svr_;
  11050. #endif
  11051. thread t_;
  11052. };
  11053. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11054. auto res = cli_.Post("/test", "123456789", "text/plain");
  11055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11056. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11057. res = cli_.Post("/test", "12345678", "text/plain");
  11058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11059. EXPECT_EQ(StatusCode::OK_200, res->status);
  11060. }
  11061. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11062. // Test chunked encoding with payload exceeding the 8-byte limit
  11063. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11064. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11066. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11067. }
  11068. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11069. // Test chunked encoding with payload within the 8-byte limit
  11070. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11071. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11073. EXPECT_EQ(StatusCode::OK_200, res->status);
  11074. }
  11075. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11076. // Test using send_request to send chunked data exceeding payload limit
  11077. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11078. "Host: " +
  11079. std::string(HOST) + ":" + std::to_string(PORT) +
  11080. "\r\n"
  11081. "Transfer-Encoding: chunked\r\n"
  11082. "Connection: close\r\n"
  11083. "\r\n"
  11084. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11085. "0123456789\r\n"
  11086. "0\r\n" // End chunk
  11087. "\r\n";
  11088. std::string response;
  11089. bool result = send_request(1, chunked_request, &response);
  11090. if (!result) {
  11091. // If send_request fails, it might be because the server closed the
  11092. // connection due to payload limit enforcement, which is acceptable
  11093. SUCCEED()
  11094. << "Server rejected oversized chunked request (connection closed)";
  11095. } else {
  11096. // If we got a response, check if it's an error response or connection was
  11097. // closed early Short response length indicates connection was closed due to
  11098. // payload limit
  11099. if (response.length() <= 10) {
  11100. SUCCEED() << "Server closed connection for oversized chunked request";
  11101. } else {
  11102. // Check for error status codes
  11103. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11104. response.find("Payload Too Large") != std::string::npos ||
  11105. response.find("400") != std::string::npos);
  11106. }
  11107. }
  11108. }
  11109. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11110. // Test request without Content-Length header exceeding payload limit
  11111. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11112. "Host: " +
  11113. std::string(HOST) + ":" +
  11114. std::to_string(PORT) +
  11115. "\r\n"
  11116. "Connection: close\r\n"
  11117. "\r\n";
  11118. // Add payload exceeding the 8-byte limit
  11119. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11120. request_without_content_length += large_payload;
  11121. std::string response;
  11122. bool result = send_request(1, request_without_content_length, &response);
  11123. if (!result) {
  11124. // If send_request fails, server likely closed connection due to payload
  11125. // limit
  11126. SUCCEED() << "Server rejected oversized request without Content-Length "
  11127. "(connection closed)";
  11128. } else {
  11129. // Check if server responded with error or closed connection early
  11130. if (response.length() <= 10) {
  11131. SUCCEED() << "Server closed connection for oversized request without "
  11132. "Content-Length";
  11133. } else {
  11134. // Check for error status codes
  11135. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11136. response.find("Payload Too Large") != std::string::npos ||
  11137. response.find("400") != std::string::npos);
  11138. }
  11139. }
  11140. }
  11141. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11142. // Test request without Content-Length header within payload limit
  11143. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11144. "Host: " +
  11145. std::string(HOST) + ":" +
  11146. std::to_string(PORT) +
  11147. "\r\n"
  11148. "Connection: close\r\n"
  11149. "\r\n";
  11150. // Add payload within the 8-byte limit
  11151. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11152. request_without_content_length += small_payload;
  11153. std::string response;
  11154. bool result = send_request(1, request_without_content_length, &response);
  11155. // For requests without Content-Length, the server may have different behavior
  11156. // The key is that it should not reject due to payload limit for small
  11157. // payloads
  11158. if (result) {
  11159. // Check for any HTTP response (success or error, but not connection closed)
  11160. if (response.length() > 10) {
  11161. SUCCEED()
  11162. << "Server processed request without Content-Length within limit";
  11163. } else {
  11164. // Short response might indicate connection closed, which is acceptable
  11165. SUCCEED() << "Server closed connection for request without "
  11166. "Content-Length (acceptable behavior)";
  11167. }
  11168. } else {
  11169. // Connection failure might be due to protocol requirements
  11170. SUCCEED() << "Connection issue with request without Content-Length "
  11171. "(environment-specific)";
  11172. }
  11173. }
  11174. class LargePayloadMaxLengthTest : public ::testing::Test {
  11175. protected:
  11176. LargePayloadMaxLengthTest()
  11177. : cli_(HOST, PORT)
  11178. #ifdef CPPHTTPLIB_SSL_ENABLED
  11179. ,
  11180. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11181. #endif
  11182. {
  11183. #ifdef CPPHTTPLIB_SSL_ENABLED
  11184. cli_.enable_server_certificate_verification(false);
  11185. #endif
  11186. }
  11187. virtual void SetUp() {
  11188. // Set 10MB payload limit
  11189. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11190. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11191. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11192. res.set_content("Large payload test", "text/plain");
  11193. });
  11194. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11195. svr_.wait_until_ready();
  11196. }
  11197. virtual void TearDown() {
  11198. svr_.stop();
  11199. t_.join();
  11200. }
  11201. #ifdef CPPHTTPLIB_SSL_ENABLED
  11202. SSLClient cli_;
  11203. SSLServer svr_;
  11204. #else
  11205. Client cli_;
  11206. Server svr_;
  11207. #endif
  11208. thread t_;
  11209. };
  11210. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11211. // Test chunked encoding with payload within 10MB limit
  11212. std::string medium_payload(5 * 1024 * 1024,
  11213. 'A'); // 5MB payload, within 10MB limit
  11214. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11216. EXPECT_EQ(StatusCode::OK_200, res->status);
  11217. }
  11218. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11219. // Test chunked encoding with payload exceeding 10MB limit
  11220. std::string large_payload(12 * 1024 * 1024,
  11221. 'B'); // 12MB payload, exceeds 10MB limit
  11222. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11223. // Server may either return 413 or close the connection
  11224. if (res) {
  11225. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11226. } else {
  11227. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11228. }
  11229. }
  11230. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11231. // Test request without Content-Length header within 10MB limit
  11232. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11233. "Host: " +
  11234. std::string(HOST) + ":" +
  11235. std::to_string(PORT) +
  11236. "\r\n"
  11237. "Connection: close\r\n"
  11238. "\r\n";
  11239. // Add 1MB payload (within 10MB limit)
  11240. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11241. request_without_content_length += medium_payload;
  11242. std::string response;
  11243. bool result = send_request(5, request_without_content_length, &response);
  11244. if (result) {
  11245. // Should get a proper HTTP response for payloads within limit
  11246. if (response.length() > 10) {
  11247. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11248. "10MB limit";
  11249. } else {
  11250. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11251. "Content-Length)";
  11252. }
  11253. } else {
  11254. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11255. }
  11256. }
  11257. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11258. // Test request without Content-Length header exceeding 10MB limit
  11259. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11260. "Host: " +
  11261. std::string(HOST) + ":" +
  11262. std::to_string(PORT) +
  11263. "\r\n"
  11264. "Connection: close\r\n"
  11265. "\r\n";
  11266. // Add 12MB payload (exceeds 10MB limit)
  11267. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11268. request_without_content_length += large_payload;
  11269. std::string response;
  11270. bool result = send_request(10, request_without_content_length, &response);
  11271. if (!result) {
  11272. // Server should close connection due to payload limit
  11273. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11274. "(connection closed)";
  11275. } else {
  11276. // Check for error response
  11277. if (response.length() <= 10) {
  11278. SUCCEED()
  11279. << "Server closed connection for 12MB request exceeding 10MB limit";
  11280. } else {
  11281. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11282. response.find("Payload Too Large") != std::string::npos ||
  11283. response.find("400") != std::string::npos);
  11284. }
  11285. }
  11286. }
  11287. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  11288. Server svr;
  11289. svr.Get("/", [](const Request &, Response &res) {
  11290. // Claims far more than it sends, then drops the connection.
  11291. res.set_content_provider(size_t(1) << 41, "text/plain",
  11292. [](size_t, size_t, DataSink &sink) {
  11293. sink.write("abc", 3);
  11294. return false;
  11295. });
  11296. });
  11297. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11298. auto se = detail::scope_exit([&] {
  11299. svr.stop();
  11300. thread.join();
  11301. ASSERT_FALSE(svr.is_running());
  11302. });
  11303. svr.wait_until_ready();
  11304. Client cli(HOST, PORT);
  11305. cli.set_payload_max_length(0);
  11306. EXPECT_FALSE(cli.Get("/"));
  11307. }
  11308. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11309. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11310. // path.
  11311. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11312. Server svr;
  11313. const size_t LIMIT = 64 * 1024; // 64KB
  11314. svr.set_payload_max_length(LIMIT);
  11315. size_t total = 0;
  11316. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11317. const ContentReader &content_reader) {
  11318. content_reader([&](const char * /*data*/, size_t len) {
  11319. total += len;
  11320. return true;
  11321. });
  11322. res.status = 200;
  11323. res.set_content("stream_ok", "text/plain");
  11324. });
  11325. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11326. auto se = detail::scope_exit([&] {
  11327. svr.stop();
  11328. thread.join();
  11329. ASSERT_FALSE(svr.is_running());
  11330. });
  11331. svr.wait_until_ready();
  11332. // Prepare 256KB raw data and gzip-compress it
  11333. std::string raw(256 * 1024, 'A');
  11334. std::string gz;
  11335. {
  11336. z_stream zs{};
  11337. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11338. Z_DEFAULT_STRATEGY);
  11339. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11340. zs.avail_in = static_cast<uInt>(raw.size());
  11341. char outbuf[4096];
  11342. int ret;
  11343. do {
  11344. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11345. zs.avail_out = sizeof(outbuf);
  11346. ret = deflate(&zs, Z_FINISH);
  11347. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11348. } while (ret != Z_STREAM_END);
  11349. deflateEnd(&zs);
  11350. }
  11351. Client cli(HOST, PORT);
  11352. cli.set_connection_timeout(std::chrono::seconds(5));
  11353. Headers headers = {{"Content-Encoding", "gzip"}};
  11354. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11355. "application/octet-stream");
  11356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11357. // Server must reject oversized decompressed payloads with 413.
  11358. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11359. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11360. EXPECT_LE(total, LIMIT);
  11361. }
  11362. #ifndef CPPHTTPLIB_SSL_ENABLED
  11363. // For a request with neither Content-Length nor Transfer-Encoding, the
  11364. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11365. // compressed wire bytes straight to the ContentReader without ever routing
  11366. // them through the decompressor, so payload_max_length_ only bounded the
  11367. // compressed size on the wire, not the decompressed size.
  11368. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11369. Server svr;
  11370. const size_t LIMIT = 64 * 1024; // 64KB
  11371. svr.set_payload_max_length(LIMIT);
  11372. size_t total = 0;
  11373. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11374. const ContentReader &content_reader) {
  11375. content_reader([&](const char * /*data*/, size_t len) {
  11376. total += len;
  11377. return true;
  11378. });
  11379. res.status = 200;
  11380. res.set_content("stream_ok", "text/plain");
  11381. });
  11382. auto port = svr.bind_to_any_port(HOST);
  11383. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11384. auto se = detail::scope_exit([&] {
  11385. svr.stop();
  11386. thread.join();
  11387. ASSERT_FALSE(svr.is_running());
  11388. });
  11389. svr.wait_until_ready();
  11390. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11391. // StreamingGzipDecompression test above.
  11392. std::string raw(256 * 1024, 'A');
  11393. std::string gz;
  11394. {
  11395. httplib::detail::gzip_compressor compressor;
  11396. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11397. [&](const char *chunk, size_t len) {
  11398. gz.append(chunk, len);
  11399. return true;
  11400. });
  11401. ASSERT_TRUE(result);
  11402. }
  11403. // Send the gzip body over raw TCP with neither Content-Length nor
  11404. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11405. // kicks in.
  11406. std::string req = "POST /stream HTTP/1.1\r\n"
  11407. "Host: " +
  11408. std::string(HOST) + ":" + std::to_string(port) +
  11409. "\r\n"
  11410. "Content-Encoding: gzip\r\n"
  11411. "Connection: close\r\n"
  11412. "\r\n" +
  11413. gz;
  11414. std::string response;
  11415. ASSERT_TRUE(send_request(5, req, &response, port));
  11416. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11417. EXPECT_LE(total, LIMIT);
  11418. }
  11419. #endif
  11420. #endif
  11421. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11422. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11423. // the payload must be passed through untouched instead of being rejected.
  11424. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11425. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11426. Server svr;
  11427. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11428. res.set_content(body, "image/jpeg");
  11429. res.set_header("Content-Encoding", "UTF-8");
  11430. });
  11431. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  11432. res.set_content(body, "image/jpeg");
  11433. res.set_header("Content-Encoding", "identity");
  11434. });
  11435. svr.Post("/echo", [](const Request &req, Response &res) {
  11436. res.set_content(req.body, "image/jpeg");
  11437. });
  11438. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11439. auto se = detail::scope_exit([&] {
  11440. svr.stop();
  11441. t.join();
  11442. ASSERT_FALSE(svr.is_running());
  11443. });
  11444. svr.wait_until_ready();
  11445. Client cli(HOST, PORT);
  11446. {
  11447. auto res = cli.Get("/image");
  11448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11449. EXPECT_EQ(StatusCode::OK_200, res->status);
  11450. EXPECT_EQ(body, res->body);
  11451. }
  11452. {
  11453. auto res = cli.Get("/identity");
  11454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11455. EXPECT_EQ(StatusCode::OK_200, res->status);
  11456. EXPECT_EQ(body, res->body);
  11457. }
  11458. {
  11459. // The same applies to a request body reaching the server.
  11460. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11461. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11463. EXPECT_EQ(StatusCode::OK_200, res->status);
  11464. EXPECT_EQ(body, res->body);
  11465. }
  11466. }
  11467. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11468. // gzip-encoded response even when the build has no zlib support.
  11469. static const char GZIPPED_HELLO_WORLD[] = {
  11470. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11471. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11472. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11473. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11474. // A content coding is a whole token, not something the field value merely
  11475. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11476. // as "fibre" look like Brotli, and turned a multi-coding value like
  11477. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11478. // it was never meant to see.
  11479. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11480. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11481. Server svr;
  11482. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11483. res.set_content(body, "image/jpeg");
  11484. res.set_header("Content-Encoding", "fibre");
  11485. });
  11486. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11487. res.set_content(body, "image/jpeg");
  11488. res.set_header("Content-Encoding", "gzip, br");
  11489. });
  11490. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11491. res.set_content(body, "image/jpeg");
  11492. res.set_header("Content-Encoding", "x-zstd-ish");
  11493. });
  11494. auto port = svr.bind_to_any_port(HOST);
  11495. thread t = thread([&]() { svr.listen_after_bind(); });
  11496. auto se = detail::scope_exit([&] {
  11497. svr.stop();
  11498. t.join();
  11499. ASSERT_FALSE(svr.is_running());
  11500. });
  11501. svr.wait_until_ready();
  11502. Client cli(HOST, port);
  11503. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11504. auto res = cli.Get(path);
  11505. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11506. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11507. // Not a coding we recognize, so the payload comes back untouched
  11508. EXPECT_EQ(body, res->body) << path;
  11509. }
  11510. }
  11511. // A content coding cpp-httplib recognizes but was not built with must be
  11512. // reported as such. Handing the still-compressed payload back to the caller
  11513. // would silently corrupt it.
  11514. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11515. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11516. Server svr;
  11517. // "image/jpeg" keeps the server from applying a content coding of its own,
  11518. // so the hand-crafted Content-Encoding below survives.
  11519. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11520. res.set_content(gzipped, "image/jpeg");
  11521. res.set_header("Content-Encoding", "gzip");
  11522. });
  11523. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11524. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11525. res.set_content(gzipped, "image/jpeg");
  11526. res.set_header("Content-Encoding", "GZIP");
  11527. });
  11528. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11529. auto se = detail::scope_exit([&] {
  11530. svr.stop();
  11531. t.join();
  11532. ASSERT_FALSE(svr.is_running());
  11533. });
  11534. svr.wait_until_ready();
  11535. Client cli(HOST, PORT);
  11536. {
  11537. auto res = cli.Get("/gzipped");
  11538. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11540. EXPECT_EQ("Hello World!", res->body);
  11541. #else
  11542. ASSERT_FALSE(res);
  11543. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11544. #endif
  11545. }
  11546. {
  11547. // open_stream() must behave the same way.
  11548. auto handle = cli.open_stream("GET", "/gzipped");
  11549. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11550. ASSERT_TRUE(handle.is_valid());
  11551. std::string received;
  11552. char buf[256];
  11553. ssize_t n;
  11554. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11555. received.append(buf, static_cast<size_t>(n));
  11556. }
  11557. EXPECT_EQ("Hello World!", received);
  11558. #else
  11559. EXPECT_FALSE(handle.is_valid());
  11560. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11561. #endif
  11562. }
  11563. {
  11564. // A differently-cased coding must not be mistaken for an unknown one, or
  11565. // the body would be handed back still compressed.
  11566. auto res = cli.Get("/gzipped-uppercase");
  11567. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11569. EXPECT_EQ("Hello World!", res->body);
  11570. #else
  11571. ASSERT_FALSE(res);
  11572. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11573. #endif
  11574. }
  11575. }
  11576. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11577. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11578. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11579. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11580. // body a second time and appending a second Content-Encoding field line, so
  11581. // clients that decode one coding per listed value handed back raw gzip bytes.
  11582. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11583. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11584. Server svr;
  11585. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11586. // keeps the server from applying a coding of its own.
  11587. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11588. res.set_content(gzipped, "text/plain");
  11589. res.set_header("Content-Encoding", "gzip");
  11590. });
  11591. auto port = svr.bind_to_any_port(HOST);
  11592. thread t = thread([&]() { svr.listen_after_bind(); });
  11593. auto se = detail::scope_exit([&] {
  11594. svr.stop();
  11595. t.join();
  11596. ASSERT_FALSE(svr.is_running());
  11597. });
  11598. svr.wait_until_ready();
  11599. Client cli(HOST, port);
  11600. Headers headers = {{"Accept-Encoding", "gzip"}};
  11601. auto res = cli.Get("/pre-gzipped", headers);
  11602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11603. EXPECT_EQ(StatusCode::OK_200, res->status);
  11604. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11605. EXPECT_EQ("Hello World!", res->body);
  11606. }
  11607. // A chunked provider settles its coding where the headers are written and
  11608. // reuses it at write time. Both ends of that have to hold: a handler's own
  11609. // Content-Encoding suppresses the coding, and a response without one is still
  11610. // compressed as it always was.
  11611. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11612. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11613. const std::string plain = "Hello World! Hello World! Hello World!";
  11614. Server svr;
  11615. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11616. res.set_header("Content-Encoding", "gzip");
  11617. res.set_chunked_content_provider(
  11618. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11619. sink.write(gzipped.data(), gzipped.size());
  11620. sink.done();
  11621. return true;
  11622. });
  11623. });
  11624. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11625. res.set_chunked_content_provider(
  11626. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11627. sink.write(plain.data(), plain.size());
  11628. sink.done();
  11629. return true;
  11630. });
  11631. });
  11632. auto port = svr.bind_to_any_port(HOST);
  11633. thread t = thread([&]() { svr.listen_after_bind(); });
  11634. auto se = detail::scope_exit([&] {
  11635. svr.stop();
  11636. t.join();
  11637. ASSERT_FALSE(svr.is_running());
  11638. });
  11639. svr.wait_until_ready();
  11640. Client cli(HOST, port);
  11641. Headers headers = {{"Accept-Encoding", "gzip"}};
  11642. {
  11643. auto res = cli.Get("/pre-gzipped", headers);
  11644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11645. EXPECT_EQ(StatusCode::OK_200, res->status);
  11646. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11647. EXPECT_EQ("Hello World!", res->body);
  11648. }
  11649. {
  11650. auto res = cli.Get("/negotiated", headers);
  11651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11652. EXPECT_EQ(StatusCode::OK_200, res->status);
  11653. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11654. EXPECT_EQ(plain, res->body);
  11655. }
  11656. }
  11657. #endif
  11658. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11659. // the same message as the comma-joined one, so both have to be read the same
  11660. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11661. // single gzip coding, and a body the sender says was encoded twice was handed
  11662. // back after one pass, still compressed but presented as decoded.
  11663. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11664. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11665. Server svr;
  11666. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11667. res.set_content(body, "image/jpeg");
  11668. res.headers.emplace("Content-Encoding", "gzip");
  11669. res.headers.emplace("Content-Encoding", "gzip");
  11670. });
  11671. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11672. res.set_content(body, "image/jpeg");
  11673. res.set_header("Content-Encoding", "gzip, gzip");
  11674. });
  11675. auto port = svr.bind_to_any_port(HOST);
  11676. thread t = thread([&]() { svr.listen_after_bind(); });
  11677. auto se = detail::scope_exit([&] {
  11678. svr.stop();
  11679. t.join();
  11680. ASSERT_FALSE(svr.is_running());
  11681. });
  11682. svr.wait_until_ready();
  11683. Client cli(HOST, port);
  11684. // Two codings is not something cpp-httplib decodes, so both representations
  11685. // take the pass-through path rather than one of them being gunzipped once.
  11686. for (const char *path : {"/split", "/joined"}) {
  11687. auto res = cli.Get(path);
  11688. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11689. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11690. EXPECT_EQ(body, res->body) << path;
  11691. }
  11692. }
  11693. // Regression test for DoS vulnerability: a malicious server sending a response
  11694. // without Content-Length header must not cause unbounded memory consumption on
  11695. // the client side. The client should stop reading after a reasonable limit,
  11696. // similar to the server-side set_payload_max_length protection.
  11697. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11698. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11699. #ifndef _WIN32
  11700. signal(SIGPIPE, SIG_IGN);
  11701. #endif
  11702. auto server_thread = std::thread([] {
  11703. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11704. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11705. default_socket_options(srv);
  11706. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11707. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11708. sockaddr_in addr{};
  11709. addr.sin_family = AF_INET;
  11710. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11711. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11712. int opt = 1;
  11713. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11714. #ifdef _WIN32
  11715. reinterpret_cast<const char *>(&opt),
  11716. #else
  11717. &opt,
  11718. #endif
  11719. sizeof(opt));
  11720. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11721. ::listen(srv, 1);
  11722. sockaddr_in cli_addr{};
  11723. socklen_t cli_len = sizeof(cli_addr);
  11724. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11725. if (cli != INVALID_SOCKET) {
  11726. char buf[4096];
  11727. ::recv(cli, buf, sizeof(buf), 0);
  11728. // Malicious response: no Content-Length, no chunked encoding
  11729. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11730. "Connection: close\r\n"
  11731. "\r\n";
  11732. ::send(cli,
  11733. #ifdef _WIN32
  11734. static_cast<const char *>(response_header.c_str()),
  11735. static_cast<int>(response_header.size()),
  11736. #else
  11737. response_header.c_str(), response_header.size(),
  11738. #endif
  11739. 0);
  11740. // Send 10MB of data
  11741. std::string chunk(64 * 1024, 'A');
  11742. size_t total_sent = 0;
  11743. while (total_sent < MALICIOUS_DATA_SIZE) {
  11744. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11745. auto sent = ::send(cli,
  11746. #ifdef _WIN32
  11747. static_cast<const char *>(chunk.c_str()),
  11748. static_cast<int>(to_send),
  11749. #else
  11750. chunk.c_str(), to_send,
  11751. #endif
  11752. 0);
  11753. if (sent <= 0) break;
  11754. total_sent += static_cast<size_t>(sent);
  11755. }
  11756. detail::close_socket(cli);
  11757. }
  11758. detail::close_socket(srv);
  11759. });
  11760. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11761. size_t total_read = 0;
  11762. {
  11763. Client cli("127.0.0.1", PORT + 2);
  11764. cli.set_read_timeout(5, 0);
  11765. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11766. auto stream = cli.open_stream("GET", "/malicious");
  11767. ASSERT_TRUE(stream.is_valid());
  11768. char buffer[64 * 1024];
  11769. ssize_t n;
  11770. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11771. total_read += static_cast<size_t>(n);
  11772. }
  11773. } // StreamHandle and Client destroyed here, closing the socket
  11774. server_thread.join();
  11775. // With set_payload_max_length, the client must stop reading before consuming
  11776. // all 10MB. The read loop should be cut off at or near the configured limit.
  11777. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11778. << "Client read " << total_read << " bytes, exceeding the configured "
  11779. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11780. }
  11781. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11782. // the entire response body without truncation.
  11783. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11784. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11785. #ifndef _WIN32
  11786. signal(SIGPIPE, SIG_IGN);
  11787. #endif
  11788. auto server_thread = std::thread([] {
  11789. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11790. default_socket_options(srv);
  11791. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11792. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11793. sockaddr_in addr{};
  11794. addr.sin_family = AF_INET;
  11795. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11796. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11797. int opt = 1;
  11798. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11799. #ifdef _WIN32
  11800. reinterpret_cast<const char *>(&opt),
  11801. #else
  11802. &opt,
  11803. #endif
  11804. sizeof(opt));
  11805. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11806. ::listen(srv, 1);
  11807. sockaddr_in cli_addr{};
  11808. socklen_t cli_len = sizeof(cli_addr);
  11809. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11810. if (cli != INVALID_SOCKET) {
  11811. char buf[4096];
  11812. ::recv(cli, buf, sizeof(buf), 0);
  11813. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11814. "Connection: close\r\n"
  11815. "\r\n";
  11816. ::send(cli,
  11817. #ifdef _WIN32
  11818. static_cast<const char *>(response_header.c_str()),
  11819. static_cast<int>(response_header.size()),
  11820. #else
  11821. response_header.c_str(), response_header.size(),
  11822. #endif
  11823. 0);
  11824. std::string chunk(64 * 1024, 'A');
  11825. size_t total_sent = 0;
  11826. while (total_sent < DATA_SIZE) {
  11827. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11828. auto sent = ::send(cli,
  11829. #ifdef _WIN32
  11830. static_cast<const char *>(chunk.c_str()),
  11831. static_cast<int>(to_send),
  11832. #else
  11833. chunk.c_str(), to_send,
  11834. #endif
  11835. 0);
  11836. if (sent <= 0) break;
  11837. total_sent += static_cast<size_t>(sent);
  11838. }
  11839. #ifdef _WIN32
  11840. ::shutdown(cli, SD_SEND);
  11841. #else
  11842. ::shutdown(cli, SHUT_WR);
  11843. #endif
  11844. // Drain until the client closes its end, ensuring all data is delivered
  11845. char drain[1024];
  11846. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11847. detail::close_socket(cli);
  11848. }
  11849. detail::close_socket(srv);
  11850. });
  11851. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11852. size_t total_read = 0;
  11853. {
  11854. Client cli("127.0.0.1", PORT + 2);
  11855. cli.set_read_timeout(5, 0);
  11856. cli.set_payload_max_length(0); // 0 means no limit
  11857. auto stream = cli.open_stream("GET", "/data");
  11858. ASSERT_TRUE(stream.is_valid());
  11859. char buffer[64 * 1024];
  11860. ssize_t n;
  11861. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11862. total_read += static_cast<size_t>(n);
  11863. }
  11864. }
  11865. server_thread.join();
  11866. EXPECT_EQ(total_read, DATA_SIZE)
  11867. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11868. << " bytes without truncation, but only read " << total_read << " bytes.";
  11869. }
  11870. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11871. // enormous Content-Length must not cause the client to pre-allocate a huge
  11872. // response body buffer. The reservation is capped at payload_max_length_, and
  11873. // the read itself fails when the body exceeds the limit.
  11874. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11875. #ifndef _WIN32
  11876. signal(SIGPIPE, SIG_IGN);
  11877. #endif
  11878. auto server_thread = std::thread([] {
  11879. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11880. default_socket_options(srv);
  11881. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11882. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11883. sockaddr_in addr{};
  11884. addr.sin_family = AF_INET;
  11885. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11886. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11887. int opt = 1;
  11888. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11889. #ifdef _WIN32
  11890. reinterpret_cast<const char *>(&opt),
  11891. #else
  11892. &opt,
  11893. #endif
  11894. sizeof(opt));
  11895. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11896. ::listen(srv, 1);
  11897. sockaddr_in cli_addr{};
  11898. socklen_t cli_len = sizeof(cli_addr);
  11899. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11900. if (cli != INVALID_SOCKET) {
  11901. char buf[4096];
  11902. ::recv(cli, buf, sizeof(buf), 0);
  11903. // Malicious response: claim a 20GB body but send only a tiny payload.
  11904. std::string response = "HTTP/1.1 200 OK\r\n"
  11905. "Content-Length: 20000000000\r\n"
  11906. "\r\n"
  11907. "abc";
  11908. ::send(cli,
  11909. #ifdef _WIN32
  11910. static_cast<const char *>(response.c_str()),
  11911. static_cast<int>(response.size()),
  11912. #else
  11913. response.c_str(), response.size(),
  11914. #endif
  11915. 0);
  11916. detail::close_socket(cli);
  11917. }
  11918. detail::close_socket(srv);
  11919. });
  11920. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11921. {
  11922. Client cli("127.0.0.1", PORT + 2);
  11923. cli.set_read_timeout(5, 0);
  11924. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11925. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11926. // (server claims more bytes than payload_max_length permits), but it must
  11927. // not exhaust memory before getting there.
  11928. auto res = cli.Get("/malicious");
  11929. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11930. }
  11931. server_thread.join();
  11932. }
  11933. // Verify that content_receiver bypasses the default payload_max_length,
  11934. // allowing streaming downloads larger than 100MB without requiring an explicit
  11935. // set_payload_max_length call.
  11936. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11937. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11938. #ifndef _WIN32
  11939. signal(SIGPIPE, SIG_IGN);
  11940. #endif
  11941. auto server_thread = std::thread([] {
  11942. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11943. default_socket_options(srv);
  11944. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11945. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11946. sockaddr_in addr{};
  11947. addr.sin_family = AF_INET;
  11948. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11949. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11950. int opt = 1;
  11951. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11952. #ifdef _WIN32
  11953. reinterpret_cast<const char *>(&opt),
  11954. #else
  11955. &opt,
  11956. #endif
  11957. sizeof(opt));
  11958. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11959. ::listen(srv, 1);
  11960. sockaddr_in cli_addr{};
  11961. socklen_t cli_len = sizeof(cli_addr);
  11962. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11963. if (cli != INVALID_SOCKET) {
  11964. char buf[4096];
  11965. ::recv(cli, buf, sizeof(buf), 0);
  11966. // Response with Content-Length larger than default 100MB limit
  11967. auto content_length = std::to_string(DATA_SIZE);
  11968. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11969. "Content-Length: " +
  11970. content_length +
  11971. "\r\n"
  11972. "Connection: close\r\n"
  11973. "\r\n";
  11974. ::send(cli,
  11975. #ifdef _WIN32
  11976. static_cast<const char *>(response_header.c_str()),
  11977. static_cast<int>(response_header.size()),
  11978. #else
  11979. response_header.c_str(), response_header.size(),
  11980. #endif
  11981. 0);
  11982. std::string chunk(64 * 1024, 'A');
  11983. size_t total_sent = 0;
  11984. while (total_sent < DATA_SIZE) {
  11985. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11986. auto sent = ::send(cli,
  11987. #ifdef _WIN32
  11988. static_cast<const char *>(chunk.c_str()),
  11989. static_cast<int>(to_send),
  11990. #else
  11991. chunk.c_str(), to_send,
  11992. #endif
  11993. 0);
  11994. if (sent <= 0) break;
  11995. total_sent += static_cast<size_t>(sent);
  11996. }
  11997. detail::close_socket(cli);
  11998. }
  11999. detail::close_socket(srv);
  12000. });
  12001. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12002. size_t total_received = 0;
  12003. {
  12004. Client cli("127.0.0.1", PORT + 2);
  12005. cli.set_read_timeout(10, 0);
  12006. // Do NOT call set_payload_max_length — use the default 100MB limit
  12007. auto res =
  12008. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12009. total_received += data_length;
  12010. return true;
  12011. });
  12012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12013. EXPECT_EQ(StatusCode::OK_200, res->status);
  12014. }
  12015. server_thread.join();
  12016. EXPECT_EQ(total_received, DATA_SIZE)
  12017. << "With content_receiver, the client should read all " << DATA_SIZE
  12018. << " bytes despite the default 100MB payload_max_length, but only read "
  12019. << total_received << " bytes.";
  12020. }
  12021. // Verify that an explicit set_payload_max_length smaller than the response is
  12022. // enforced even when a content_receiver is used.
  12023. TEST(ClientVulnerabilityTest,
  12024. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12025. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12026. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12027. #ifndef _WIN32
  12028. signal(SIGPIPE, SIG_IGN);
  12029. #endif
  12030. auto server_thread = std::thread([] {
  12031. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12032. default_socket_options(srv);
  12033. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12034. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12035. sockaddr_in addr{};
  12036. addr.sin_family = AF_INET;
  12037. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12038. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12039. int opt = 1;
  12040. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12041. #ifdef _WIN32
  12042. reinterpret_cast<const char *>(&opt),
  12043. #else
  12044. &opt,
  12045. #endif
  12046. sizeof(opt));
  12047. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12048. ::listen(srv, 1);
  12049. sockaddr_in cli_addr{};
  12050. socklen_t cli_len = sizeof(cli_addr);
  12051. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12052. if (cli != INVALID_SOCKET) {
  12053. char buf[4096];
  12054. ::recv(cli, buf, sizeof(buf), 0);
  12055. auto content_length = std::to_string(DATA_SIZE);
  12056. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12057. "Content-Length: " +
  12058. content_length +
  12059. "\r\n"
  12060. "Connection: close\r\n"
  12061. "\r\n";
  12062. ::send(cli,
  12063. #ifdef _WIN32
  12064. static_cast<const char *>(response_header.c_str()),
  12065. static_cast<int>(response_header.size()),
  12066. #else
  12067. response_header.c_str(), response_header.size(),
  12068. #endif
  12069. 0);
  12070. std::string chunk(64 * 1024, 'A');
  12071. size_t total_sent = 0;
  12072. while (total_sent < DATA_SIZE) {
  12073. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12074. auto sent = ::send(cli,
  12075. #ifdef _WIN32
  12076. static_cast<const char *>(chunk.c_str()),
  12077. static_cast<int>(to_send),
  12078. #else
  12079. chunk.c_str(), to_send,
  12080. #endif
  12081. 0);
  12082. if (sent <= 0) break;
  12083. total_sent += static_cast<size_t>(sent);
  12084. }
  12085. detail::close_socket(cli);
  12086. }
  12087. detail::close_socket(srv);
  12088. });
  12089. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12090. size_t total_received = 0;
  12091. {
  12092. Client cli("127.0.0.1", PORT + 2);
  12093. cli.set_read_timeout(10, 0);
  12094. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12095. auto res =
  12096. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12097. total_received += data_length;
  12098. return true;
  12099. });
  12100. // Should fail because 200MB exceeds the explicit 150MB limit
  12101. EXPECT_FALSE(res);
  12102. }
  12103. server_thread.join();
  12104. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12105. << "Client with content_receiver should respect the explicit "
  12106. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12107. << total_received << " bytes.";
  12108. }
  12109. // Verify that an explicit set_payload_max_length larger than the response
  12110. // allows the content_receiver to read all data successfully.
  12111. TEST(ClientVulnerabilityTest,
  12112. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12113. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12114. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12115. #ifndef _WIN32
  12116. signal(SIGPIPE, SIG_IGN);
  12117. #endif
  12118. auto server_thread = std::thread([] {
  12119. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12120. default_socket_options(srv);
  12121. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12122. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12123. sockaddr_in addr{};
  12124. addr.sin_family = AF_INET;
  12125. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12126. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12127. int opt = 1;
  12128. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12129. #ifdef _WIN32
  12130. reinterpret_cast<const char *>(&opt),
  12131. #else
  12132. &opt,
  12133. #endif
  12134. sizeof(opt));
  12135. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12136. ::listen(srv, 1);
  12137. sockaddr_in cli_addr{};
  12138. socklen_t cli_len = sizeof(cli_addr);
  12139. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12140. if (cli != INVALID_SOCKET) {
  12141. char buf[4096];
  12142. ::recv(cli, buf, sizeof(buf), 0);
  12143. auto content_length = std::to_string(DATA_SIZE);
  12144. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12145. "Content-Length: " +
  12146. content_length +
  12147. "\r\n"
  12148. "Connection: close\r\n"
  12149. "\r\n";
  12150. ::send(cli,
  12151. #ifdef _WIN32
  12152. static_cast<const char *>(response_header.c_str()),
  12153. static_cast<int>(response_header.size()),
  12154. #else
  12155. response_header.c_str(), response_header.size(),
  12156. #endif
  12157. 0);
  12158. std::string chunk(64 * 1024, 'A');
  12159. size_t total_sent = 0;
  12160. while (total_sent < DATA_SIZE) {
  12161. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12162. auto sent = ::send(cli,
  12163. #ifdef _WIN32
  12164. static_cast<const char *>(chunk.c_str()),
  12165. static_cast<int>(to_send),
  12166. #else
  12167. chunk.c_str(), to_send,
  12168. #endif
  12169. 0);
  12170. if (sent <= 0) break;
  12171. total_sent += static_cast<size_t>(sent);
  12172. }
  12173. #ifdef _WIN32
  12174. ::shutdown(cli, SD_SEND);
  12175. #else
  12176. ::shutdown(cli, SHUT_WR);
  12177. #endif
  12178. char drain[1024];
  12179. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12180. detail::close_socket(cli);
  12181. }
  12182. detail::close_socket(srv);
  12183. });
  12184. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12185. size_t total_received = 0;
  12186. {
  12187. Client cli("127.0.0.1", PORT + 2);
  12188. cli.set_read_timeout(10, 0);
  12189. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12190. auto res =
  12191. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12192. total_received += data_length;
  12193. return true;
  12194. });
  12195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12196. EXPECT_EQ(StatusCode::OK_200, res->status);
  12197. }
  12198. server_thread.join();
  12199. EXPECT_EQ(total_received, DATA_SIZE)
  12200. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12201. << " bytes (larger than " << DATA_SIZE
  12202. << " bytes response), content_receiver should read all data, but only "
  12203. "read "
  12204. << total_received << " bytes.";
  12205. }
  12206. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12207. // Regression test for "zip bomb" attack on the client side: a malicious server
  12208. // sends a small gzip-compressed response that decompresses to a huge payload.
  12209. // The client must enforce payload_max_length on the decompressed size.
  12210. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12211. constexpr size_t DECOMPRESSED_SIZE =
  12212. 10 * 1024 * 1024; // 10MB after decompression
  12213. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12214. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12215. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12216. std::string compressed;
  12217. {
  12218. httplib::detail::gzip_compressor compressor;
  12219. bool ok =
  12220. compressor.compress(uncompressed.data(), uncompressed.size(),
  12221. /*last=*/true, [&](const char *buf, size_t len) {
  12222. compressed.append(buf, len);
  12223. return true;
  12224. });
  12225. ASSERT_TRUE(ok);
  12226. }
  12227. // Sanity: compressed data should be much smaller than the decompressed size
  12228. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12229. #ifndef _WIN32
  12230. signal(SIGPIPE, SIG_IGN);
  12231. #endif
  12232. // Set up the listening socket in the main thread so the server is guaranteed
  12233. // to be ready before the client connects (eliminates race condition).
  12234. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12235. default_socket_options(srv);
  12236. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12237. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12238. sockaddr_in addr{};
  12239. addr.sin_family = AF_INET;
  12240. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12241. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12242. int opt = 1;
  12243. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12244. #ifdef _WIN32
  12245. reinterpret_cast<const char *>(&opt),
  12246. #else
  12247. &opt,
  12248. #endif
  12249. sizeof(opt));
  12250. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12251. ASSERT_EQ(0, ::listen(srv, 1));
  12252. auto server_thread = std::thread([&compressed, srv] {
  12253. sockaddr_in cli_addr{};
  12254. socklen_t cli_len = sizeof(cli_addr);
  12255. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12256. if (cli != INVALID_SOCKET) {
  12257. // Read the full HTTP request (until \r\n\r\n)
  12258. char buf[4096];
  12259. size_t total = 0;
  12260. while (total < sizeof(buf)) {
  12261. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12262. if (n <= 0) break;
  12263. total += static_cast<size_t>(n);
  12264. // Check for end of headers
  12265. if (total >= 4) {
  12266. std::string req(buf, total);
  12267. if (req.find("\r\n\r\n") != std::string::npos) break;
  12268. }
  12269. }
  12270. // Malicious response: gzip-compressed body, no Content-Length
  12271. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12272. "Content-Encoding: gzip\r\n"
  12273. "Connection: close\r\n"
  12274. "\r\n";
  12275. ::send(cli,
  12276. #ifdef _WIN32
  12277. static_cast<const char *>(response_header.c_str()),
  12278. static_cast<int>(response_header.size()),
  12279. #else
  12280. response_header.c_str(), response_header.size(),
  12281. #endif
  12282. 0);
  12283. // Send the compressed payload (small on the wire, huge when decompressed)
  12284. size_t total_sent = 0;
  12285. while (total_sent < compressed.size()) {
  12286. auto to_send = std::min(compressed.size() - total_sent,
  12287. static_cast<size_t>(64 * 1024));
  12288. auto sent =
  12289. ::send(cli,
  12290. #ifdef _WIN32
  12291. static_cast<const char *>(compressed.c_str() + total_sent),
  12292. static_cast<int>(to_send),
  12293. #else
  12294. compressed.c_str() + total_sent, to_send,
  12295. #endif
  12296. 0);
  12297. if (sent <= 0) break;
  12298. total_sent += static_cast<size_t>(sent);
  12299. }
  12300. detail::close_socket(cli);
  12301. }
  12302. });
  12303. auto se = detail::scope_exit([&] {
  12304. detail::close_socket(srv);
  12305. server_thread.join();
  12306. });
  12307. size_t total_decompressed = 0;
  12308. {
  12309. Client cli("127.0.0.1", PORT + 3);
  12310. cli.set_read_timeout(5, 0);
  12311. cli.set_decompress(true);
  12312. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12313. auto stream = cli.open_stream("GET", "/zipbomb");
  12314. ASSERT_TRUE(stream.is_valid());
  12315. char buffer[64 * 1024];
  12316. ssize_t n;
  12317. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12318. total_decompressed += static_cast<size_t>(n);
  12319. }
  12320. }
  12321. // The decompressed size must be capped by payload_max_length. Without
  12322. // protection, the client would decompress the full 10MB from a tiny
  12323. // compressed payload, enabling a zip bomb DoS attack.
  12324. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12325. << "Client decompressed " << total_decompressed
  12326. << " bytes from a gzip response. The decompressed size should be "
  12327. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12328. }
  12329. #endif
  12330. TEST(HostAndPortPropertiesTest, NoSSL) {
  12331. httplib::Client cli("www.google.com", 1234);
  12332. ASSERT_EQ("www.google.com", cli.host());
  12333. ASSERT_EQ(1234, cli.port());
  12334. }
  12335. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12336. httplib::Client cli("www.google.com:1234");
  12337. ASSERT_EQ("www.google.com", cli.host());
  12338. ASSERT_EQ(1234, cli.port());
  12339. }
  12340. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12341. // Port number that overflows int — should not crash, client becomes invalid
  12342. httplib::Client cli("http://www.google.com:99999999999999999999");
  12343. ASSERT_FALSE(cli.is_valid());
  12344. }
  12345. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12346. // Port 99999 exceeds valid range (1-65535) — should not crash
  12347. httplib::Client cli("http://www.google.com:99999");
  12348. ASSERT_FALSE(cli.is_valid());
  12349. auto res = cli.Get("/");
  12350. EXPECT_FALSE(res);
  12351. EXPECT_EQ(Error::Connection, res.error());
  12352. }
  12353. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12354. httplib::Client cli("http://www.google.com:80abc");
  12355. ASSERT_FALSE(cli.is_valid());
  12356. }
  12357. #ifdef CPPHTTPLIB_SSL_ENABLED
  12358. TEST(HostAndPortPropertiesTest, SSL) {
  12359. httplib::SSLClient cli("www.google.com");
  12360. ASSERT_EQ("www.google.com", cli.host());
  12361. ASSERT_EQ(443, cli.port());
  12362. }
  12363. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12364. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12365. std::string cert;
  12366. read_file(CA_CERT_FILE, cert);
  12367. httplib::SSLClient httplib_client("www.google.com");
  12368. // Load CA store first time
  12369. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12370. // Load CA store second time (update)
  12371. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12372. // Verify client is still valid and can make connections
  12373. httplib_client.enable_server_certificate_verification(true);
  12374. auto res = httplib_client.Get("/");
  12375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12376. // Google may return 200 or 301 depending on various factors
  12377. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12378. res->status == StatusCode::MovedPermanently_301);
  12379. }
  12380. TEST(SSLClientTest, ServerNameIndication_Online) {
  12381. auto host = "httpbingo.org";
  12382. auto path = std::string{"/get"};
  12383. SSLClient cli(host, 443);
  12384. auto res = cli.Get(path);
  12385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12386. ASSERT_EQ(StatusCode::OK_200, res->status);
  12387. }
  12388. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12389. // Use a site that will cause SSL verification failure due to self-signed cert
  12390. SSLClient cli("self-signed.badssl.com", 443);
  12391. cli.enable_server_certificate_verification(true);
  12392. auto res = cli.Get("/");
  12393. ASSERT_TRUE(!res);
  12394. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12395. // Verify backend error is captured for SSLServerVerification
  12396. // This occurs when certificate verification fails
  12397. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12398. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12399. EXPECT_NE(0UL, res.ssl_backend_error());
  12400. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12401. // For OpenSSL, ssl_error is 0 for verification errors
  12402. EXPECT_EQ(0, res.ssl_error());
  12403. #if !defined(_WIN32) || \
  12404. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12405. // On non-Windows or when Windows Schannel is disabled, the error comes
  12406. // from OpenSSL's verification
  12407. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12408. res.ssl_backend_error());
  12409. #endif
  12410. #endif
  12411. }
  12412. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12413. // Use a site where hostname doesn't match the certificate
  12414. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12415. SSLClient cli("wrong.host.badssl.com", 443);
  12416. cli.enable_server_certificate_verification(true);
  12417. cli.enable_server_hostname_verification(true);
  12418. auto res = cli.Get("/");
  12419. ASSERT_TRUE(!res);
  12420. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12421. // Verify backend error is captured for hostname verification failure
  12422. EXPECT_NE(0UL, res.ssl_backend_error());
  12423. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12424. // For OpenSSL, ssl_error is 0 for verification errors
  12425. EXPECT_EQ(0, res.ssl_error());
  12426. #if !defined(_WIN32) || \
  12427. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12428. // On non-Windows or when Windows Schannel is disabled, the error comes
  12429. // from OpenSSL's hostname verification
  12430. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12431. res.ssl_backend_error());
  12432. #endif
  12433. #endif
  12434. }
  12435. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12436. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12437. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12438. SSLClient cli("www.google.com", 443);
  12439. cli.enable_server_certificate_verification(true);
  12440. auto res = cli.Get("/");
  12441. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12442. }
  12443. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12444. SSLClient cli("www.google.com", 443);
  12445. cli.enable_server_certificate_verification(true);
  12446. cli.enable_windows_certificate_verification(false);
  12447. auto res = cli.Get("/");
  12448. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12449. }
  12450. // The server sends an intermediate cross-signed by a root Windows trusts,
  12451. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12452. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12453. SSLClient cli("accounts.spotify.com", 443);
  12454. auto res = cli.Get("/");
  12455. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12456. << " ssl_backend_error=" << res.ssl_backend_error();
  12457. }
  12458. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12459. // policy status, which no backend reports for a self-signed certificate.
  12460. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12461. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12462. ASSERT_TRUE(svr.is_valid());
  12463. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12464. auto se = detail::scope_exit([&] {
  12465. svr.stop();
  12466. t.join();
  12467. ASSERT_FALSE(svr.is_running());
  12468. });
  12469. svr.wait_until_ready();
  12470. SSLClient cli("127.0.0.1", PORT);
  12471. cli.set_connection_timeout(30);
  12472. auto res = cli.Get("/");
  12473. ASSERT_FALSE(res);
  12474. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12475. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12476. }
  12477. #endif
  12478. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12479. Client cli("https://google.com");
  12480. auto res = cli.Get("/");
  12481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12482. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12483. }
  12484. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12485. SSLClient cli("google.com");
  12486. cli.set_ca_cert_path(CA_CERT_FILE);
  12487. auto res = cli.Get("/");
  12488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12489. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12490. }
  12491. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12492. SSLClient cli("google.com");
  12493. cli.enable_server_certificate_verification(true);
  12494. cli.set_ca_cert_path("hello");
  12495. auto res = cli.Get("/");
  12496. ASSERT_TRUE(!res);
  12497. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12498. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12499. // should be set
  12500. EXPECT_EQ(0, res.ssl_error());
  12501. // Verify backend error is captured for SSLLoadingCerts
  12502. // This error occurs when loading CA certificates fails
  12503. EXPECT_NE(0UL, res.ssl_backend_error());
  12504. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12505. // OpenSSL specific error codes:
  12506. // > openssl errstr 0x80000002
  12507. // error:80000002:system library::No such file or directory
  12508. // > openssl errstr 0xA000126
  12509. // error:0A000126:SSL routines::unexpected eof while reading
  12510. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12511. res.ssl_backend_error() == 0xA000126);
  12512. #endif
  12513. }
  12514. TEST(SSLClientTest, ServerCertificateVerification4) {
  12515. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12516. ASSERT_TRUE(svr.is_valid());
  12517. svr.Get("/test", [&](const Request &, Response &res) {
  12518. res.set_content("test", "text/plain");
  12519. svr.stop();
  12520. ASSERT_TRUE(true);
  12521. });
  12522. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12523. auto se = detail::scope_exit([&] {
  12524. t.join();
  12525. ASSERT_FALSE(svr.is_running());
  12526. });
  12527. svr.wait_until_ready();
  12528. SSLClient cli("127.0.0.1", PORT);
  12529. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12530. cli.enable_server_certificate_verification(true);
  12531. cli.set_connection_timeout(30);
  12532. auto res = cli.Get("/test");
  12533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12534. ASSERT_EQ(StatusCode::OK_200, res->status);
  12535. }
  12536. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12537. std::string cert;
  12538. read_file(CA_CERT_FILE, cert);
  12539. SSLClient cli("google.com");
  12540. cli.load_ca_cert_store(cert.data(), cert.size());
  12541. const auto res = cli.Get("/");
  12542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12543. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12544. }
  12545. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12546. // clang-format off
  12547. static constexpr char cert[] =
  12548. "GlobalSign Root CA\n"
  12549. "==================\n"
  12550. "-----BEGIN CERTIFICATE-----\n"
  12551. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12552. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12553. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12554. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12555. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12556. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12557. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12558. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12559. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12560. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12561. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12562. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12563. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12564. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12565. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12566. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12567. "-----END CERTIFICATE-----\n";
  12568. // clang-format on
  12569. SSLClient cli("google.com");
  12570. cli.load_ca_cert_store(cert, sizeof(cert));
  12571. const auto res = cli.Get("/");
  12572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12573. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12574. }
  12575. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12576. SSLClient cli("www.youtube.com");
  12577. cli.set_ca_cert_path(CA_CERT_FILE);
  12578. cli.enable_server_certificate_verification(true);
  12579. cli.set_follow_location(true);
  12580. auto res = cli.Get("/");
  12581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12582. ASSERT_EQ(StatusCode::OK_200, res->status);
  12583. }
  12584. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12585. SSLClient cli("wWw.YouTube.Com");
  12586. cli.set_ca_cert_path(CA_CERT_FILE);
  12587. cli.enable_server_certificate_verification(true);
  12588. cli.enable_server_hostname_verification(true);
  12589. cli.set_follow_location(true);
  12590. auto res = cli.Get("/");
  12591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12592. ASSERT_EQ(StatusCode::OK_200, res->status);
  12593. }
  12594. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12595. SSLClient cli("gOoGlE.COm");
  12596. cli.enable_server_certificate_verification(true);
  12597. cli.enable_server_hostname_verification(true);
  12598. cli.set_follow_location(true);
  12599. auto res = cli.Get("/");
  12600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12601. ASSERT_EQ(StatusCode::OK_200, res->status);
  12602. }
  12603. TEST(SSLClientTest, Issue2004_Online) {
  12604. Client client("https://google.com");
  12605. client.set_follow_location(true);
  12606. auto res = client.Get("/");
  12607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12608. ASSERT_EQ(StatusCode::OK_200, res->status);
  12609. auto body = res->body;
  12610. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12611. }
  12612. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12613. // Create SSLClient with invalid cert/key to make is_valid() return false
  12614. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12615. "nonexistent_key.pem");
  12616. // is_valid() should be false due to cert loading failure
  12617. ASSERT_FALSE(cli.is_valid());
  12618. auto res = cli.Get("/");
  12619. ASSERT_FALSE(res);
  12620. EXPECT_EQ(Error::SSLConnection, res.error());
  12621. }
  12622. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12623. // Test for Issue #2251: SSL error not properly reported when client cert
  12624. // and key paths are swapped or mismatched
  12625. // This simulates the scenario where user accidentally swaps the cert and key
  12626. // files
  12627. // Using client cert file as private key and vice versa (completely wrong)
  12628. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12629. // Should fail validation due to cert/key mismatch
  12630. ASSERT_FALSE(cli.is_valid());
  12631. // Attempt to make a request should fail with proper error
  12632. auto res = cli.Get("/");
  12633. ASSERT_FALSE(res);
  12634. EXPECT_EQ(Error::SSLConnection, res.error());
  12635. // SSL error should be recorded in the Result object (this is the key fix for
  12636. // Issue #2251)
  12637. auto backend_error = res.ssl_backend_error();
  12638. EXPECT_NE(0u, backend_error);
  12639. }
  12640. // Tests cert/key mismatch detection at the TLS context level
  12641. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12642. // Test that using mismatched cert/key causes connection failure.
  12643. // We verify this at the SSLClient level rather than through internal
  12644. // TLS API functions.
  12645. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12646. cli.enable_server_certificate_verification(false);
  12647. cli.set_connection_timeout(2);
  12648. // The mismatch should cause a connection or handshake error
  12649. auto res = cli.Get("/test");
  12650. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12651. // Either way, the request should fail
  12652. EXPECT_FALSE(res);
  12653. }
  12654. #endif
  12655. #if 0
  12656. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12657. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12658. ASSERT_TRUE(cli != nullptr);
  12659. cli->set_address_family(AF_INET6);
  12660. cli->set_interface("en0");
  12661. auto res = cli->Get("/get");
  12662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12663. ASSERT_EQ(StatusCode::OK_200, res->status);
  12664. }
  12665. #endif
  12666. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12667. #ifdef CPPHTTPLIB_SSL_ENABLED
  12668. void ClientCertPresent(
  12669. const std::string &client_cert_file,
  12670. const std::string &client_private_key_file,
  12671. const std::string &client_encrypted_private_key_pass = std::string()) {
  12672. using namespace httplib::tls;
  12673. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12674. CLIENT_CA_CERT_DIR);
  12675. ASSERT_TRUE(svr.is_valid());
  12676. svr.Get("/test", [&](const Request &req, Response &res) {
  12677. res.set_content("test", "text/plain");
  12678. auto cert = req.peer_cert();
  12679. ASSERT_TRUE(static_cast<bool>(cert));
  12680. std::string common_name = cert.subject_cn();
  12681. EXPECT_EQ("Common Name", common_name);
  12682. });
  12683. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12684. auto se = detail::scope_exit([&] {
  12685. svr.stop();
  12686. t.join();
  12687. ASSERT_FALSE(svr.is_running());
  12688. });
  12689. svr.wait_until_ready();
  12690. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12691. client_encrypted_private_key_pass);
  12692. cli.enable_server_certificate_verification(false);
  12693. cli.set_connection_timeout(30);
  12694. auto res = cli.Get("/test");
  12695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12696. ASSERT_EQ(StatusCode::OK_200, res->status);
  12697. }
  12698. TEST(SSLClientServerTest, ClientCertPresent) {
  12699. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12700. }
  12701. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12702. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12703. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12704. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12705. }
  12706. // PEM memory-based constructor tests (works with all TLS backends)
  12707. void PemMemoryClientCertPresent(
  12708. const std::string &client_cert_file,
  12709. const std::string &client_private_key_file,
  12710. const std::string &client_encrypted_private_key_pass = std::string()) {
  12711. // Read PEM files into memory
  12712. std::string server_cert_pem, server_key_pem;
  12713. std::string client_ca_pem;
  12714. std::string client_cert_pem, client_key_pem;
  12715. read_file(SERVER_CERT_FILE, server_cert_pem);
  12716. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12717. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12718. read_file(client_cert_file, client_cert_pem);
  12719. read_file(client_private_key_file, client_key_pem);
  12720. // Create server with PEM memory
  12721. SSLServer::PemMemory server_pem = {
  12722. server_cert_pem.c_str(),
  12723. server_cert_pem.size(),
  12724. server_key_pem.c_str(),
  12725. server_key_pem.size(),
  12726. client_ca_pem.c_str(),
  12727. client_ca_pem.size(),
  12728. nullptr // no password for server key
  12729. };
  12730. SSLServer svr(server_pem);
  12731. ASSERT_TRUE(svr.is_valid());
  12732. svr.Get("/test", [&](const Request &, Response &res) {
  12733. res.set_content("test", "text/plain");
  12734. });
  12735. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12736. auto se = detail::scope_exit([&] {
  12737. svr.stop();
  12738. t.join();
  12739. ASSERT_FALSE(svr.is_running());
  12740. });
  12741. svr.wait_until_ready();
  12742. // Create client with PEM memory
  12743. const char *password = client_encrypted_private_key_pass.empty()
  12744. ? nullptr
  12745. : client_encrypted_private_key_pass.c_str();
  12746. SSLClient::PemMemory client_pem = {
  12747. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12748. client_key_pem.size(), password};
  12749. SSLClient cli(HOST, PORT, client_pem);
  12750. cli.enable_server_certificate_verification(false);
  12751. cli.set_connection_timeout(30);
  12752. auto res = cli.Get("/test");
  12753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12754. ASSERT_EQ(StatusCode::OK_200, res->status);
  12755. }
  12756. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12757. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12758. }
  12759. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12760. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12761. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12762. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12763. }
  12764. TEST(SSLClientServerTest, ClientCertMissing) {
  12765. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12766. CLIENT_CA_CERT_DIR);
  12767. ASSERT_TRUE(svr.is_valid());
  12768. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12769. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12770. auto se = detail::scope_exit([&] {
  12771. svr.stop();
  12772. t.join();
  12773. ASSERT_FALSE(svr.is_running());
  12774. });
  12775. svr.wait_until_ready();
  12776. SSLClient cli(HOST, PORT);
  12777. cli.set_connection_timeout(30);
  12778. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12779. // the chain check on Windows, so the result does not depend on the order.
  12780. cli.enable_server_hostname_verification(false);
  12781. auto res = cli.Get("/test");
  12782. ASSERT_TRUE(!res);
  12783. // When client cert is missing and server requires it, connection fails
  12784. // Error type depends on backend implementation
  12785. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12786. res.error() == Error::SSLConnection);
  12787. // Verify backend error is captured
  12788. // Note: This test may have different error codes depending on the exact
  12789. // verification failure
  12790. EXPECT_NE(0UL, res.ssl_backend_error());
  12791. }
  12792. TEST(SSLClientServerTest, TrustDirOptional) {
  12793. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12794. ASSERT_TRUE(svr.is_valid());
  12795. svr.Get("/test", [&](const Request &, Response &res) {
  12796. res.set_content("test", "text/plain");
  12797. });
  12798. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12799. auto se = detail::scope_exit([&] {
  12800. svr.stop();
  12801. t.join();
  12802. ASSERT_FALSE(svr.is_running());
  12803. });
  12804. svr.wait_until_ready();
  12805. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12806. cli.enable_server_certificate_verification(false);
  12807. cli.set_connection_timeout(30);
  12808. auto res = cli.Get("/test");
  12809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12810. ASSERT_EQ(StatusCode::OK_200, res->status);
  12811. }
  12812. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12813. class NoListenSSLServer : public SSLServer {
  12814. public:
  12815. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12816. const char *client_ca_cert_file_path,
  12817. const char *client_ca_cert_dir_path = nullptr)
  12818. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12819. client_ca_cert_dir_path),
  12820. stop_(false) {}
  12821. std::atomic_bool stop_;
  12822. private:
  12823. bool process_and_close_socket(socket_t /*sock*/) override {
  12824. // Don't create SSL context
  12825. while (!stop_.load()) {
  12826. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12827. }
  12828. return true;
  12829. }
  12830. };
  12831. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12832. CLIENT_CA_CERT_FILE);
  12833. ASSERT_TRUE(svr.is_valid());
  12834. svr.Get("/test", [&](const Request &, Response &res) {
  12835. res.set_content("test", "text/plain");
  12836. });
  12837. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12838. auto se = detail::scope_exit([&] {
  12839. svr.stop_ = true;
  12840. svr.stop();
  12841. t.join();
  12842. ASSERT_FALSE(svr.is_running());
  12843. });
  12844. svr.wait_until_ready();
  12845. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12846. cli.enable_server_certificate_verification(false);
  12847. cli.set_connection_timeout(1);
  12848. auto res = cli.Get("/test");
  12849. ASSERT_TRUE(!res);
  12850. EXPECT_EQ(Error::SSLConnection, res.error());
  12851. // Timeout results in WantRead error code (maps to backend-specific value)
  12852. EXPECT_NE(0, res.ssl_error());
  12853. }
  12854. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12855. // Test SSLServer with client certificate verification using the standard
  12856. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12857. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12858. CLIENT_CA_CERT_DIR);
  12859. ASSERT_TRUE(svr.is_valid());
  12860. svr.Get("/test", [&](const Request &req, Response &res) {
  12861. res.set_content("test", "text/plain");
  12862. auto cert = req.peer_cert();
  12863. ASSERT_TRUE(static_cast<bool>(cert));
  12864. auto common_name = cert.subject_cn();
  12865. EXPECT_EQ("Common Name", common_name);
  12866. });
  12867. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12868. auto se = detail::scope_exit([&] {
  12869. svr.stop();
  12870. t.join();
  12871. ASSERT_FALSE(svr.is_running());
  12872. });
  12873. svr.wait_until_ready();
  12874. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12875. cli.enable_server_certificate_verification(false);
  12876. cli.set_connection_timeout(30);
  12877. auto res = cli.Get("/test");
  12878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12879. ASSERT_EQ(StatusCode::OK_200, res->status);
  12880. }
  12881. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12882. // Verifies that wildcard matching and exact matching work consistently
  12883. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12884. using namespace httplib::tls;
  12885. // We need a running server to test against
  12886. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12887. ASSERT_TRUE(svr.is_valid());
  12888. svr.Get("/test", [](const Request &, Response &res) {
  12889. res.set_content("ok", "text/plain");
  12890. });
  12891. thread t([&]() { svr.listen(HOST, PORT); });
  12892. auto se = detail::scope_exit([&] {
  12893. svr.stop();
  12894. t.join();
  12895. });
  12896. svr.wait_until_ready();
  12897. bool verify_callback_called = false;
  12898. bool verify_result_wrong = false;
  12899. SSLClient cli(HOST, PORT);
  12900. cli.enable_server_certificate_verification(true);
  12901. cli.set_ca_cert_path(CA_CERT_FILE);
  12902. cli.set_connection_timeout(5);
  12903. // Note: Test certificate has CN="Common Name", not "localhost"
  12904. bool verify_result_cn = false;
  12905. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12906. verify_callback_called = true;
  12907. if (!ctx.cert) return false;
  12908. // Test 1: "Common Name" should match (our test server cert CN)
  12909. verify_result_cn = ctx.check_hostname("Common Name");
  12910. // Test 2: wrong hostname should not match
  12911. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12912. return true; // Accept for the purpose of this test
  12913. });
  12914. auto res = cli.Get("/test");
  12915. // The request may succeed or fail depending on cert configuration
  12916. // but the callback should have been called
  12917. ASSERT_TRUE(verify_callback_called)
  12918. << "Verify callback should have been called";
  12919. // CN="Common Name" should match our test certificate
  12920. //
  12921. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12922. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12923. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12924. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12925. // <openssl/base.h>, which is included transitively when
  12926. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12927. #if defined(OPENSSL_IS_BORINGSSL)
  12928. EXPECT_FALSE(verify_result_cn)
  12929. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12930. #else
  12931. EXPECT_TRUE(verify_result_cn)
  12932. << "verify_hostname should match 'Common Name' (certificate CN)";
  12933. #endif
  12934. // Wrong hostname should not match
  12935. EXPECT_FALSE(verify_result_wrong)
  12936. << "verify_hostname should not match 'wronghost.example.com'";
  12937. }
  12938. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12939. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12940. // X509_check_ip behavior and must hold for every backend.
  12941. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12942. using namespace httplib::tls;
  12943. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12944. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12945. ASSERT_TRUE(svr.is_valid());
  12946. svr.Get("/test", [](const Request &, Response &res) {
  12947. res.set_content("ok", "text/plain");
  12948. });
  12949. thread t([&]() { svr.listen(HOST, PORT); });
  12950. auto se = detail::scope_exit([&] {
  12951. svr.stop();
  12952. t.join();
  12953. });
  12954. svr.wait_until_ready();
  12955. bool verify_callback_called = false;
  12956. bool ip_matched_via_cn = true;
  12957. SSLClient cli(HOST, PORT);
  12958. cli.enable_server_certificate_verification(true);
  12959. cli.set_ca_cert_path(CA_CERT_FILE);
  12960. cli.set_connection_timeout(5);
  12961. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12962. verify_callback_called = true;
  12963. if (!ctx.cert) return false;
  12964. // The IP appears only in the CN, so it must NOT be accepted.
  12965. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12966. return true; // Accept for the purpose of this test
  12967. });
  12968. cli.Get("/test");
  12969. ASSERT_TRUE(verify_callback_called)
  12970. << "Verify callback should have been called";
  12971. EXPECT_FALSE(ip_matched_via_cn)
  12972. << "An IP host must not be authenticated via the certificate CN";
  12973. }
  12974. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12975. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12976. using namespace httplib::tls;
  12977. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12978. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12979. ASSERT_TRUE(svr.is_valid());
  12980. svr.Get("/test", [](const Request &, Response &res) {
  12981. res.set_content("ok", "text/plain");
  12982. });
  12983. thread t([&]() { svr.listen(HOST, PORT); });
  12984. auto se = detail::scope_exit([&] {
  12985. svr.stop();
  12986. t.join();
  12987. });
  12988. svr.wait_until_ready();
  12989. bool verify_callback_called = false;
  12990. bool san_matched = false;
  12991. bool wrong_ipv6_matched = true;
  12992. bool cn_ipv6_matched = true;
  12993. SSLClient cli(HOST, PORT);
  12994. cli.enable_server_certificate_verification(true);
  12995. cli.set_ca_cert_path(CA_CERT_FILE);
  12996. cli.set_connection_timeout(5);
  12997. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12998. verify_callback_called = true;
  12999. if (!ctx.cert) return false;
  13000. // Matches the IPv6 iPAddress SAN.
  13001. san_matched = ctx.check_hostname("2001:db8::1");
  13002. // A different IPv6 address must not match.
  13003. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13004. // "::1" lives only in the CN, so it must not be accepted.
  13005. cn_ipv6_matched = ctx.check_hostname("::1");
  13006. return true; // Accept for the purpose of this test
  13007. });
  13008. cli.Get("/test");
  13009. ASSERT_TRUE(verify_callback_called)
  13010. << "Verify callback should have been called";
  13011. EXPECT_TRUE(san_matched)
  13012. << "verify_hostname should match an IPv6 iPAddress SAN";
  13013. EXPECT_FALSE(wrong_ipv6_matched)
  13014. << "verify_hostname should not match a non-matching IPv6 address";
  13015. EXPECT_FALSE(cn_ipv6_matched)
  13016. << "An IPv6 host must not be authenticated via the certificate CN";
  13017. }
  13018. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13019. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13020. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13021. using namespace httplib::tls;
  13022. // SANs: DNS:a.zz, IP:42.46.122.122
  13023. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13024. ASSERT_TRUE(svr.is_valid());
  13025. svr.Get("/test", [](const Request &, Response &res) {
  13026. res.set_content("ok", "text/plain");
  13027. });
  13028. auto port = svr.bind_to_any_port(HOST);
  13029. thread t([&]() { svr.listen_after_bind(); });
  13030. auto se = detail::scope_exit([&] {
  13031. svr.stop();
  13032. t.join();
  13033. });
  13034. svr.wait_until_ready();
  13035. bool verify_callback_called = false;
  13036. bool dns_san_matched = false;
  13037. bool ip_san_matched = false;
  13038. bool ip_matched_via_dns_san = true;
  13039. bool dns_matched_via_ip_san = true;
  13040. SSLClient cli(HOST, port);
  13041. cli.enable_server_certificate_verification(true);
  13042. cli.set_ca_cert_path(CA_CERT_FILE);
  13043. cli.set_connection_timeout(5);
  13044. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13045. verify_callback_called = true;
  13046. if (!ctx.cert) return false;
  13047. dns_san_matched = ctx.check_hostname("a.zz");
  13048. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13049. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13050. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13051. return true; // Accept for the purpose of this test
  13052. });
  13053. cli.Get("/test");
  13054. ASSERT_TRUE(verify_callback_called)
  13055. << "Verify callback should have been called";
  13056. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13057. EXPECT_TRUE(ip_san_matched)
  13058. << "verify_hostname should match an iPAddress SAN";
  13059. EXPECT_FALSE(ip_matched_via_dns_san)
  13060. << "An IP host must not be authenticated via a dNSName SAN";
  13061. EXPECT_FALSE(dns_matched_via_ip_san)
  13062. << "A DNS host must not be authenticated via an iPAddress SAN";
  13063. }
  13064. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13065. // "www.*.example.test" names one host and not every host under example.test.
  13066. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13067. using namespace httplib::tls;
  13068. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13069. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13070. ASSERT_TRUE(svr.is_valid());
  13071. svr.Get("/test", [](const Request &, Response &res) {
  13072. res.set_content("ok", "text/plain");
  13073. });
  13074. auto port = svr.bind_to_any_port(HOST);
  13075. thread t([&]() { svr.listen_after_bind(); });
  13076. auto se = detail::scope_exit([&] {
  13077. svr.stop();
  13078. t.join();
  13079. });
  13080. svr.wait_until_ready();
  13081. bool verify_callback_called = false;
  13082. bool leftmost_wildcard_matched = false;
  13083. bool wildcard_spanned_labels = true;
  13084. bool inner_wildcard_matched = true;
  13085. SSLClient cli(HOST, port);
  13086. cli.enable_server_certificate_verification(true);
  13087. cli.set_ca_cert_path(CA_CERT_FILE);
  13088. cli.set_connection_timeout(5);
  13089. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13090. verify_callback_called = true;
  13091. if (!ctx.cert) return false;
  13092. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13093. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13094. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13095. return true; // Accept for the purpose of this test
  13096. });
  13097. cli.Get("/test");
  13098. ASSERT_TRUE(verify_callback_called)
  13099. << "Verify callback should have been called";
  13100. EXPECT_TRUE(leftmost_wildcard_matched)
  13101. << "A leftmost wildcard should match a single label";
  13102. EXPECT_FALSE(wildcard_spanned_labels)
  13103. << "A wildcard label must not match more than one label";
  13104. EXPECT_FALSE(inner_wildcard_matched)
  13105. << "A wildcard outside the leftmost label must not be honoured";
  13106. }
  13107. // sans() must report each SAN entry under its own type.
  13108. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13109. using namespace httplib::tls;
  13110. // SANs: DNS:a.zz, IP:42.46.122.122
  13111. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13112. ASSERT_TRUE(svr.is_valid());
  13113. svr.Get("/test", [](const Request &, Response &res) {
  13114. res.set_content("ok", "text/plain");
  13115. });
  13116. auto port = svr.bind_to_any_port(HOST);
  13117. thread t([&]() { svr.listen_after_bind(); });
  13118. auto se = detail::scope_exit([&] {
  13119. svr.stop();
  13120. t.join();
  13121. });
  13122. svr.wait_until_ready();
  13123. bool verify_callback_called = false;
  13124. std::vector<SanEntry> sans;
  13125. SSLClient cli(HOST, port);
  13126. cli.enable_server_certificate_verification(true);
  13127. cli.set_ca_cert_path(CA_CERT_FILE);
  13128. cli.set_connection_timeout(5);
  13129. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13130. verify_callback_called = true;
  13131. if (!ctx.cert) return false;
  13132. sans = ctx.sans();
  13133. return true; // Accept for the purpose of this test
  13134. });
  13135. cli.Get("/test");
  13136. ASSERT_TRUE(verify_callback_called)
  13137. << "Verify callback should have been called";
  13138. auto has_san = [&](SanType type, const std::string &value) {
  13139. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13140. return san.type == type && san.value == value;
  13141. });
  13142. };
  13143. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13144. << "sans() should report the dNSName SAN";
  13145. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13146. << "sans() should report the iPAddress SAN";
  13147. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13148. << "sans() must not report the dNSName SAN as an address";
  13149. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13150. << "sans() must not report the iPAddress SAN as a DNS name";
  13151. }
  13152. #endif
  13153. // mbedTLS-specific callback constructor test
  13154. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13155. #ifdef CPPHTTPLIB_SSL_ENABLED
  13156. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13157. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13158. ASSERT_TRUE(svr.is_valid());
  13159. // Set up a handler to verify client certificate is present
  13160. bool client_cert_verified = false;
  13161. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13162. // Verify that client certificate was provided
  13163. client_cert_verified = true;
  13164. res.set_content("success", "text/plain");
  13165. });
  13166. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13167. auto se = detail::scope_exit([&] {
  13168. svr.stop();
  13169. t.join();
  13170. ASSERT_FALSE(svr.is_running());
  13171. });
  13172. svr.wait_until_ready();
  13173. // Client with certificate
  13174. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13175. cli.enable_server_certificate_verification(false);
  13176. cli.set_connection_timeout(30);
  13177. auto res = cli.Get("/test");
  13178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13179. ASSERT_EQ(StatusCode::OK_200, res->status);
  13180. ASSERT_TRUE(client_cert_verified);
  13181. EXPECT_EQ("success", res->body);
  13182. }
  13183. #endif
  13184. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13185. // backends
  13186. #ifdef CPPHTTPLIB_SSL_ENABLED
  13187. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13188. using namespace httplib::tls;
  13189. // Test that when client CA cert file is provided,
  13190. // the server properly requests and validates client certificates
  13191. // Create a server with client authentication
  13192. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13193. ASSERT_TRUE(svr.is_valid());
  13194. bool handler_called = false;
  13195. svr.Get("/test", [&](const Request &req, Response &res) {
  13196. handler_called = true;
  13197. // Verify that a client certificate was provided
  13198. auto cert = req.peer_cert();
  13199. ASSERT_TRUE(static_cast<bool>(cert));
  13200. // Get the issuer name
  13201. std::string issuer_str = cert.issuer_name();
  13202. ASSERT_FALSE(issuer_str.empty());
  13203. // The client certificate should be issued by our test CA
  13204. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13205. res.set_content("authenticated", "text/plain");
  13206. });
  13207. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13208. auto se = detail::scope_exit([&] {
  13209. svr.stop();
  13210. t.join();
  13211. ASSERT_FALSE(svr.is_running());
  13212. });
  13213. svr.wait_until_ready();
  13214. // Connect with a client certificate issued by the CA
  13215. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13216. cli.enable_server_certificate_verification(false);
  13217. cli.set_connection_timeout(30);
  13218. auto res = cli.Get("/test");
  13219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13220. ASSERT_EQ(StatusCode::OK_200, res->status);
  13221. ASSERT_TRUE(handler_called);
  13222. EXPECT_EQ("authenticated", res->body);
  13223. }
  13224. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13225. using namespace httplib::tls;
  13226. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13227. ASSERT_TRUE(svr.is_valid());
  13228. svr.Get("/test", [](const Request &, Response &res) {
  13229. res.set_content("ok", "text/plain");
  13230. });
  13231. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13232. auto se = detail::scope_exit([&] {
  13233. svr.stop();
  13234. t.join();
  13235. });
  13236. svr.wait_until_ready();
  13237. SSLClient cli(HOST, PORT);
  13238. cli.enable_server_certificate_verification(false);
  13239. cli.set_connection_timeout(30);
  13240. bool cert_checked = false;
  13241. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13242. if (ctx.cert) {
  13243. auto sans = ctx.sans();
  13244. // Test certificate may or may not have SANs - just verify the API
  13245. // works If SANs exist, verify the types are valid
  13246. for (const auto &san : sans) {
  13247. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13248. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13249. san.type == SanType::OTHER);
  13250. EXPECT_FALSE(san.value.empty());
  13251. }
  13252. cert_checked = true;
  13253. }
  13254. return true;
  13255. });
  13256. auto res = cli.Get("/test");
  13257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13258. EXPECT_TRUE(cert_checked);
  13259. }
  13260. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13261. using namespace httplib::tls;
  13262. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13263. ASSERT_TRUE(svr.is_valid());
  13264. svr.Get("/test", [](const Request &, Response &res) {
  13265. res.set_content("ok", "text/plain");
  13266. });
  13267. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13268. auto se = detail::scope_exit([&] {
  13269. svr.stop();
  13270. t.join();
  13271. });
  13272. svr.wait_until_ready();
  13273. SSLClient cli(HOST, PORT);
  13274. cli.enable_server_certificate_verification(false);
  13275. cli.set_connection_timeout(30);
  13276. bool validity_checked = false;
  13277. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13278. if (ctx.cert) {
  13279. time_t not_before = 0, not_after = 0;
  13280. bool result = ctx.validity(not_before, not_after);
  13281. EXPECT_TRUE(result);
  13282. // Verify that not_before < now < not_after for a valid cert
  13283. time_t now = time(nullptr);
  13284. EXPECT_LT(not_before, now);
  13285. EXPECT_GT(not_after, now);
  13286. validity_checked = true;
  13287. }
  13288. return true;
  13289. });
  13290. auto res = cli.Get("/test");
  13291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13292. EXPECT_TRUE(validity_checked);
  13293. }
  13294. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13295. using namespace httplib::tls;
  13296. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13297. ASSERT_TRUE(svr.is_valid());
  13298. svr.Get("/test", [](const Request &, Response &res) {
  13299. res.set_content("ok", "text/plain");
  13300. });
  13301. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13302. auto se = detail::scope_exit([&] {
  13303. svr.stop();
  13304. t.join();
  13305. });
  13306. svr.wait_until_ready();
  13307. SSLClient cli(HOST, PORT);
  13308. cli.enable_server_certificate_verification(false);
  13309. cli.set_connection_timeout(30);
  13310. bool serial_checked = false;
  13311. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13312. if (ctx.cert) {
  13313. std::string serial = ctx.serial();
  13314. EXPECT_FALSE(serial.empty());
  13315. // Serial should be a hex string
  13316. for (char c : serial) {
  13317. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13318. (c >= 'a' && c <= 'f'));
  13319. }
  13320. serial_checked = true;
  13321. }
  13322. return true;
  13323. });
  13324. auto res = cli.Get("/test");
  13325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13326. EXPECT_TRUE(serial_checked);
  13327. }
  13328. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13329. // Test 1: Valid CA file - no error should be recorded
  13330. {
  13331. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13332. CLIENT_CA_CERT_FILE);
  13333. ASSERT_TRUE(svr.is_valid());
  13334. // With valid setup, last_ssl_error should be 0
  13335. EXPECT_EQ(0, svr.ssl_last_error());
  13336. }
  13337. // Test 2: Invalid CA file content
  13338. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13339. {
  13340. // Create a temporary file with completely invalid content
  13341. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13342. {
  13343. std::ofstream ofs(temp_invalid_ca);
  13344. ofs << "This is not a certificate file at all\n";
  13345. ofs << "Just plain text content\n";
  13346. }
  13347. // Create server with invalid CA file
  13348. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13349. // Clean up temporary file
  13350. std::remove(temp_invalid_ca);
  13351. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13352. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13353. // Note: SSL_CTX_load_verify_locations typically fails first,
  13354. // but our error handling code path is still exercised
  13355. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13356. }
  13357. }
  13358. TEST(VerifyCallbackTest, VerifyContextFields) {
  13359. using namespace httplib::tls;
  13360. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13361. ASSERT_TRUE(svr.is_valid());
  13362. svr.Get("/test", [](const Request &, Response &res) {
  13363. res.set_content("ok", "text/plain");
  13364. });
  13365. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13366. auto se = detail::scope_exit([&] {
  13367. svr.stop();
  13368. t.join();
  13369. });
  13370. svr.wait_until_ready();
  13371. SSLClient cli(HOST, PORT);
  13372. cli.enable_server_certificate_verification(false);
  13373. cli.set_connection_timeout(30);
  13374. int callback_count = 0;
  13375. bool saw_leaf_cert = false;
  13376. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13377. if (ctx.cert) {
  13378. callback_count++;
  13379. // We should see at least one certificate (the leaf)
  13380. std::string cn = ctx.subject_cn();
  13381. if (!cn.empty()) { saw_leaf_cert = true; }
  13382. // Verify context fields are populated
  13383. EXPECT_NE(ctx.session, nullptr);
  13384. EXPECT_GE(ctx.depth, 0);
  13385. }
  13386. return true;
  13387. });
  13388. auto res = cli.Get("/test");
  13389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13390. EXPECT_GT(callback_count, 0);
  13391. EXPECT_TRUE(saw_leaf_cert);
  13392. }
  13393. // A verifier belongs to the client that set it, not to the thread that set it.
  13394. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13395. using namespace httplib::tls;
  13396. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13397. ASSERT_TRUE(svr.is_valid());
  13398. svr.Get("/test", [](const Request &, Response &res) {
  13399. res.set_content("ok", "text/plain");
  13400. });
  13401. auto port = svr.bind_to_any_port(HOST);
  13402. thread t([&]() { svr.listen_after_bind(); });
  13403. auto se = detail::scope_exit([&] {
  13404. svr.stop();
  13405. t.join();
  13406. });
  13407. svr.wait_until_ready();
  13408. auto rejecting_calls = 0;
  13409. SSLClient rejecting(HOST, port);
  13410. rejecting.enable_server_certificate_verification(false);
  13411. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13412. rejecting_calls++;
  13413. return false;
  13414. });
  13415. auto accepting_calls = 0;
  13416. SSLClient accepting(HOST, port);
  13417. accepting.enable_server_certificate_verification(false);
  13418. // Set on another thread than the requests below.
  13419. thread([&]() {
  13420. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13421. accepting_calls++;
  13422. return true;
  13423. });
  13424. }).join();
  13425. // Requested on another thread than the verifier was set on.
  13426. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13427. EXPECT_GT(rejecting_calls, 0);
  13428. auto res = accepting.Get("/test");
  13429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13430. EXPECT_GT(accepting_calls, 0);
  13431. }
  13432. // VerifyContext::session is the same handle the other tls:: functions take.
  13433. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13434. using namespace httplib::tls;
  13435. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13436. ASSERT_TRUE(svr.is_valid());
  13437. svr.Get("/test", [](const Request &, Response &res) {
  13438. res.set_content("ok", "text/plain");
  13439. });
  13440. auto port = svr.bind_to_any_port(HOST);
  13441. thread t([&]() { svr.listen_after_bind(); });
  13442. auto se = detail::scope_exit([&] {
  13443. svr.stop();
  13444. t.join();
  13445. });
  13446. svr.wait_until_ready();
  13447. SSLClient cli(HOST, port);
  13448. cli.enable_server_certificate_verification(false);
  13449. session_t verifier_session = nullptr;
  13450. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  13451. verifier_session = ctx.session;
  13452. return true;
  13453. });
  13454. session_t session_verifier_session = nullptr;
  13455. cli.set_session_verifier([&](session_t session) {
  13456. session_verifier_session = session;
  13457. return SSLVerifierResponse::NoDecisionMade;
  13458. });
  13459. auto res = cli.Get("/test");
  13460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13461. EXPECT_NE(nullptr, verifier_session);
  13462. EXPECT_EQ(session_verifier_session, verifier_session);
  13463. }
  13464. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13465. using httplib::tls::TlsError;
  13466. // Test that verify_error_to_string returns empty for success
  13467. std::string success_str = TlsError::verify_error_to_string(0);
  13468. EXPECT_TRUE(success_str.empty());
  13469. // Test that verify_error_to_string returns non-empty for error codes
  13470. // Using a common error code (certificate expired)
  13471. std::string error_str =
  13472. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13473. EXPECT_FALSE(error_str.empty());
  13474. }
  13475. TEST(SessionVerifierTest, CertificateAccepted) {
  13476. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13477. ASSERT_TRUE(svr.is_valid());
  13478. svr.Get("/test", [](const Request &, Response &res) {
  13479. res.set_content("ok", "text/plain");
  13480. });
  13481. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13482. auto se = detail::scope_exit([&] {
  13483. svr.stop();
  13484. t.join();
  13485. });
  13486. svr.wait_until_ready();
  13487. SSLClient cli(HOST, PORT);
  13488. cli.enable_server_certificate_verification(false);
  13489. cli.set_connection_timeout(30);
  13490. bool callback_called = false;
  13491. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13492. EXPECT_NE(session, nullptr);
  13493. callback_called = true;
  13494. return SSLVerifierResponse::CertificateAccepted;
  13495. });
  13496. auto res = cli.Get("/test");
  13497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13498. EXPECT_EQ(200, res->status);
  13499. EXPECT_TRUE(callback_called);
  13500. }
  13501. TEST(SessionVerifierTest, CertificateRejected) {
  13502. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13503. ASSERT_TRUE(svr.is_valid());
  13504. svr.Get("/test", [](const Request &, Response &res) {
  13505. res.set_content("ok", "text/plain");
  13506. });
  13507. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13508. auto se = detail::scope_exit([&] {
  13509. svr.stop();
  13510. t.join();
  13511. });
  13512. svr.wait_until_ready();
  13513. SSLClient cli(HOST, PORT);
  13514. cli.enable_server_certificate_verification(false);
  13515. cli.set_connection_timeout(30);
  13516. bool callback_called = false;
  13517. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13518. EXPECT_NE(session, nullptr);
  13519. callback_called = true;
  13520. return SSLVerifierResponse::CertificateRejected;
  13521. });
  13522. auto res = cli.Get("/test");
  13523. EXPECT_FALSE(res);
  13524. EXPECT_TRUE(callback_called);
  13525. }
  13526. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13527. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13528. ASSERT_TRUE(svr.is_valid());
  13529. svr.Get("/test", [](const Request &, Response &res) {
  13530. res.set_content("ok", "text/plain");
  13531. });
  13532. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13533. auto se = detail::scope_exit([&] {
  13534. svr.stop();
  13535. t.join();
  13536. });
  13537. svr.wait_until_ready();
  13538. // NoDecisionMade with verification disabled should succeed (no default check)
  13539. SSLClient cli(HOST, PORT);
  13540. cli.enable_server_certificate_verification(false);
  13541. cli.set_connection_timeout(30);
  13542. bool callback_called = false;
  13543. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13544. EXPECT_NE(session, nullptr);
  13545. callback_called = true;
  13546. return SSLVerifierResponse::NoDecisionMade;
  13547. });
  13548. auto res = cli.Get("/test");
  13549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13550. EXPECT_EQ(200, res->status);
  13551. EXPECT_TRUE(callback_called);
  13552. }
  13553. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  13554. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13555. ASSERT_TRUE(svr.is_valid());
  13556. svr.Get("/test", [](const Request &, Response &res) {
  13557. res.set_content("ok", "text/plain");
  13558. });
  13559. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13560. auto se = detail::scope_exit([&] {
  13561. svr.stop();
  13562. t.join();
  13563. });
  13564. svr.wait_until_ready();
  13565. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13566. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13567. // so we only check that the request fails, not whether the callback was
  13568. // called.
  13569. SSLClient cli(HOST, PORT);
  13570. cli.enable_server_certificate_verification(true);
  13571. cli.set_connection_timeout(30);
  13572. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13573. EXPECT_NE(session, nullptr);
  13574. return SSLVerifierResponse::NoDecisionMade;
  13575. });
  13576. auto res = cli.Get("/test");
  13577. EXPECT_FALSE(res);
  13578. }
  13579. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13580. // Test SSL server using PemMemory constructor with client CA certificates
  13581. // Read PEM files
  13582. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13583. read_file(SERVER_CERT_FILE, server_cert_pem);
  13584. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13585. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13586. // Create SSLServer with PemMemory constructor including client CA
  13587. SSLServer::PemMemory server_pem = {
  13588. server_cert_pem.c_str(),
  13589. server_cert_pem.size(),
  13590. server_key_pem.c_str(),
  13591. server_key_pem.size(),
  13592. client_ca_pem.c_str(),
  13593. client_ca_pem.size(),
  13594. nullptr // no password for server key
  13595. };
  13596. SSLServer svr(server_pem);
  13597. ASSERT_TRUE(svr.is_valid());
  13598. // No SSL error should be recorded for valid setup
  13599. EXPECT_EQ(0, svr.ssl_last_error());
  13600. // Set up server endpoints
  13601. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13602. res.set_content("ok", "text/plain");
  13603. });
  13604. // Start server in a thread
  13605. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13606. svr.wait_until_ready();
  13607. // Connect with client certificate (using constructor with paths)
  13608. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13609. cli.enable_server_certificate_verification(false);
  13610. auto res = cli.Get("/test-pem-ca");
  13611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13612. EXPECT_EQ(200, res->status);
  13613. EXPECT_EQ("ok", res->body);
  13614. svr.stop();
  13615. server_thread.join();
  13616. }
  13617. #endif
  13618. #ifdef _WIN32
  13619. TEST(CleanupTest, WSACleanup) {
  13620. int ret = WSACleanup();
  13621. ASSERT_EQ(0, ret);
  13622. }
  13623. #endif
  13624. #ifndef CPPHTTPLIB_SSL_ENABLED
  13625. TEST(NoSSLSupport, SimpleInterface) {
  13626. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13627. }
  13628. #endif
  13629. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13630. TEST(InvalidScheme, SimpleInterface) {
  13631. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13632. }
  13633. #endif
  13634. TEST(NoScheme, SimpleInterface) {
  13635. Client cli("yahoo.com:80");
  13636. ASSERT_TRUE(cli.is_valid());
  13637. }
  13638. TEST(SendAPI, SimpleInterface_Online) {
  13639. Client cli("http://yahoo.com");
  13640. Request req;
  13641. req.method = "GET";
  13642. req.path = "/";
  13643. auto res = cli.send(req);
  13644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13645. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13646. }
  13647. TEST(SendAPI, WithParamsInRequest) {
  13648. Server svr;
  13649. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13650. EXPECT_TRUE(req.has_param("test"));
  13651. EXPECT_EQ("test_value", req.get_param_value("test"));
  13652. });
  13653. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13654. auto se = detail::scope_exit([&] {
  13655. svr.stop();
  13656. t.join();
  13657. ASSERT_FALSE(svr.is_running());
  13658. });
  13659. svr.wait_until_ready();
  13660. Client cli(HOST, PORT);
  13661. {
  13662. Request req;
  13663. req.method = "GET";
  13664. req.path = "/";
  13665. req.params.emplace("test", "test_value");
  13666. auto res = cli.send(req);
  13667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13668. }
  13669. {
  13670. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13672. }
  13673. }
  13674. TEST(ClientImplMethods, GetSocketTest) {
  13675. httplib::Server svr;
  13676. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13677. res.status = StatusCode::OK_200;
  13678. });
  13679. auto port = svr.bind_to_any_port("127.0.0.1");
  13680. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13681. auto se = detail::scope_exit([&] {
  13682. svr.stop();
  13683. thread.join();
  13684. ASSERT_FALSE(svr.is_running());
  13685. });
  13686. svr.wait_until_ready();
  13687. {
  13688. httplib::Client cli("127.0.0.1", port);
  13689. cli.set_keep_alive(true);
  13690. // Use the behavior of cpp-httplib of opening the connection
  13691. // only when the first request happens. If that changes,
  13692. // this test would be obsolete.
  13693. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13694. // This also implicitly tests the server. But other tests would fail much
  13695. // earlier than this one to be considered.
  13696. auto res = cli.Get("/");
  13697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13698. EXPECT_EQ(StatusCode::OK_200, res->status);
  13699. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13700. }
  13701. }
  13702. #ifdef CPPHTTPLIB_SSL_ENABLED
  13703. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13704. Client cli("http://yahoo.com");
  13705. auto res = cli.Get("/");
  13706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13707. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13708. cli.set_follow_location(true);
  13709. res = cli.Get("/");
  13710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13711. EXPECT_EQ(StatusCode::OK_200, res->status);
  13712. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13713. }
  13714. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13715. Client cli("https://yahoo.com");
  13716. auto res = cli.Get("/");
  13717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13718. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13719. cli.set_follow_location(true);
  13720. res = cli.Get("/");
  13721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13722. EXPECT_EQ(StatusCode::OK_200, res->status);
  13723. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13724. }
  13725. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13726. Client cli("https://yahoo.com");
  13727. auto res = cli.Get("/");
  13728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13729. ASSERT_FALSE(!res);
  13730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13731. ASSERT_FALSE(res == nullptr);
  13732. ASSERT_TRUE(res != nullptr);
  13733. EXPECT_EQ(Error::Success, res.error());
  13734. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13735. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13736. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13737. cli.set_follow_location(true);
  13738. res = cli.Get("/");
  13739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13740. EXPECT_EQ(Error::Success, res.error());
  13741. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13742. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13743. EXPECT_EQ(StatusCode::OK_200, res->status);
  13744. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13745. }
  13746. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13747. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13748. Client cli("https://cdnjs.cloudflare.com");
  13749. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13750. Headers{{"Accept-Encoding", "br"}});
  13751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13752. EXPECT_EQ(StatusCode::OK_200, res->status);
  13753. EXPECT_EQ(287630U, res->body.size());
  13754. EXPECT_EQ("application/javascript; charset=utf-8",
  13755. res->get_header_value("Content-Type"));
  13756. }
  13757. #endif
  13758. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13759. #undef REDIR_HOST // Silence compiler warning
  13760. #define REDIR_HOST "https://httpbingo.org"
  13761. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13762. Client cli(REDIR_HOST);
  13763. cli.set_follow_location(true);
  13764. auto res =
  13765. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13767. EXPECT_EQ(StatusCode::OK_200, res->status);
  13768. }
  13769. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13770. Client cli(REDIR_HOST);
  13771. cli.set_follow_location(true);
  13772. Params params;
  13773. params.emplace("url", "http://example.com");
  13774. params.emplace("status_code", "302");
  13775. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13777. EXPECT_EQ(StatusCode::OK_200, res->status);
  13778. }
  13779. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13780. Client cli(REDIR_HOST);
  13781. cli.set_follow_location(true);
  13782. Params params;
  13783. params.emplace("url", "http://example.com");
  13784. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13786. EXPECT_EQ(StatusCode::OK_200, res->status);
  13787. }
  13788. TEST(HttpToHttpsRedirectTest, CertFile) {
  13789. auto ssl_port = PORT + 1;
  13790. Server svr;
  13791. ASSERT_TRUE(svr.is_valid());
  13792. svr.Get("/index", [&](const Request &, Response &res) {
  13793. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13794. "/index");
  13795. svr.stop();
  13796. });
  13797. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13798. ASSERT_TRUE(ssl_svr.is_valid());
  13799. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13800. res.set_content("test", "text/plain");
  13801. ssl_svr.stop();
  13802. });
  13803. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13804. thread t2 =
  13805. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13806. auto se = detail::scope_exit([&] {
  13807. t2.join();
  13808. t.join();
  13809. ASSERT_FALSE(svr.is_running());
  13810. });
  13811. svr.wait_until_ready();
  13812. ssl_svr.wait_until_ready();
  13813. Client cli("127.0.0.1", PORT);
  13814. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13815. cli.enable_server_certificate_verification(true);
  13816. cli.set_follow_location(true);
  13817. cli.set_connection_timeout(30);
  13818. auto res = cli.Get("/index");
  13819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13820. ASSERT_EQ(StatusCode::OK_200, res->status);
  13821. }
  13822. TEST(SSLClientRedirectTest, CertFile) {
  13823. auto ssl_port = PORT + 1;
  13824. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13825. ASSERT_TRUE(ssl_svr1.is_valid());
  13826. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13827. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13828. "/index");
  13829. ssl_svr1.stop();
  13830. });
  13831. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13832. ASSERT_TRUE(ssl_svr2.is_valid());
  13833. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13834. res.set_content("test", "text/plain");
  13835. ssl_svr2.stop();
  13836. });
  13837. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13838. thread t2 =
  13839. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13840. auto se = detail::scope_exit([&] {
  13841. t2.join();
  13842. t.join();
  13843. ASSERT_FALSE(ssl_svr1.is_running());
  13844. });
  13845. ssl_svr1.wait_until_ready();
  13846. ssl_svr2.wait_until_ready();
  13847. SSLClient cli("127.0.0.1", PORT);
  13848. std::string cert;
  13849. read_file(SERVER_CERT2_FILE, cert);
  13850. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13851. cli.enable_server_certificate_verification(true);
  13852. cli.set_follow_location(true);
  13853. cli.set_connection_timeout(30);
  13854. auto res = cli.Get("/index");
  13855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13856. ASSERT_EQ(StatusCode::OK_200, res->status);
  13857. }
  13858. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  13859. // another port, so the client follows it with a new client.
  13860. static Result GetThroughTlsRedirectToDifferentPort(
  13861. const std::function<void(SSLClient &)> &setup,
  13862. const char *target_cert = SERVER_CERT2_FILE) {
  13863. auto ssl_port = PORT + 1;
  13864. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13865. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13866. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13867. "/index");
  13868. });
  13869. SSLServer ssl_svr2(target_cert, SERVER_PRIVATE_KEY_FILE);
  13870. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13871. res.set_content("test", "text/plain");
  13872. });
  13873. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  13874. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  13875. auto se = detail::scope_exit([&] {
  13876. ssl_svr2.stop();
  13877. ssl_svr1.stop();
  13878. t2.join();
  13879. t.join();
  13880. });
  13881. ssl_svr1.wait_until_ready();
  13882. ssl_svr2.wait_until_ready();
  13883. SSLClient cli("127.0.0.1", PORT);
  13884. cli.set_follow_location(true);
  13885. cli.set_connection_timeout(30);
  13886. setup(cli);
  13887. return cli.Get("/index");
  13888. }
  13889. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  13890. auto calls = 0;
  13891. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  13892. cli.enable_server_certificate_verification(false);
  13893. // Accept the first server only.
  13894. cli.set_session_verifier([&](tls::session_t) {
  13895. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  13896. : SSLVerifierResponse::CertificateRejected;
  13897. });
  13898. });
  13899. EXPECT_FALSE(res);
  13900. EXPECT_EQ(2, calls);
  13901. }
  13902. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  13903. std::string pinned;
  13904. auto res = GetThroughTlsRedirectToDifferentPort(
  13905. [&](SSLClient &cli) {
  13906. cli.enable_server_certificate_verification(false);
  13907. // Pin the first certificate seen.
  13908. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  13909. if (pinned.empty()) { pinned = ctx.serial(); }
  13910. return ctx.serial() == pinned;
  13911. });
  13912. },
  13913. // A certificate other than the first server's.
  13914. SERVER_CERT_FILE);
  13915. EXPECT_FALSE(res);
  13916. EXPECT_FALSE(pinned.empty());
  13917. }
  13918. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  13919. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  13920. std::string cert;
  13921. read_file(SERVER_CERT2_FILE, cert);
  13922. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13923. });
  13924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13925. EXPECT_EQ(StatusCode::OK_200, res->status);
  13926. }
  13927. #endif
  13928. #ifdef CPPHTTPLIB_SSL_ENABLED
  13929. // Test that set_ca_cert_store() skips system certs (consistent with
  13930. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13931. // should be trusted - system certs should NOT be loaded.
  13932. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  13933. // Load a specific cert that is NOT a system CA cert
  13934. std::string cert;
  13935. read_file(SERVER_CERT2_FILE, cert);
  13936. SSLClient cli("google.com");
  13937. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13938. cli.enable_server_certificate_verification(true);
  13939. // This should FAIL because:
  13940. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  13941. // 2. System certs should NOT be loaded when custom store is set
  13942. // If system certs WERE loaded, this would succeed
  13943. auto res = cli.Get("/");
  13944. ASSERT_FALSE(res);
  13945. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13946. }
  13947. // Same as above, but through the native store handle path. Regression test:
  13948. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  13949. // merged system certs into the user-provided store.
  13950. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  13951. std::string cert;
  13952. read_file(SERVER_CERT2_FILE, cert);
  13953. SSLClient cli("google.com");
  13954. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13955. cli.enable_server_certificate_verification(true);
  13956. auto res = cli.Get("/");
  13957. ASSERT_FALSE(res);
  13958. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13959. }
  13960. // A custom store set via the native handle must still verify a server whose
  13961. // cert it does contain.
  13962. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  13963. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13964. ASSERT_TRUE(svr.is_valid());
  13965. svr.Get("/test", [&](const Request &, Response &res) {
  13966. res.set_content("test", "text/plain");
  13967. });
  13968. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13969. auto se = detail::scope_exit([&] {
  13970. svr.stop();
  13971. t.join();
  13972. ASSERT_FALSE(svr.is_running());
  13973. });
  13974. svr.wait_until_ready();
  13975. SSLClient cli("127.0.0.1", PORT);
  13976. std::string cert;
  13977. read_file(SERVER_CERT2_FILE, cert);
  13978. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13979. cli.enable_server_certificate_verification(true);
  13980. cli.set_connection_timeout(30);
  13981. auto res = cli.Get("/test");
  13982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13983. ASSERT_EQ(StatusCode::OK_200, res->status);
  13984. }
  13985. // CA certs loaded through the universal Client must be transferred to the
  13986. // client created internally for following an HTTPS redirect. Regression test:
  13987. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  13988. // the CA data for redirect transfer.
  13989. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  13990. auto ssl_port = PORT + 1;
  13991. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13992. ASSERT_TRUE(ssl_svr1.is_valid());
  13993. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13994. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13995. "/index");
  13996. });
  13997. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13998. ASSERT_TRUE(ssl_svr2.is_valid());
  13999. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14000. res.set_content("test", "text/plain");
  14001. });
  14002. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14003. thread t2 =
  14004. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14005. auto se = detail::scope_exit([&] {
  14006. ssl_svr2.stop();
  14007. ssl_svr1.stop();
  14008. t2.join();
  14009. t.join();
  14010. ASSERT_FALSE(ssl_svr1.is_running());
  14011. });
  14012. ssl_svr1.wait_until_ready();
  14013. ssl_svr2.wait_until_ready();
  14014. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14015. std::string cert;
  14016. read_file(SERVER_CERT2_FILE, cert);
  14017. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14018. cli.enable_server_certificate_verification(true);
  14019. cli.set_follow_location(true);
  14020. cli.set_connection_timeout(30);
  14021. auto res = cli.Get("/index");
  14022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14023. ASSERT_EQ(StatusCode::OK_200, res->status);
  14024. }
  14025. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14026. // so a host signed by a system CA verifies even though a custom CA is set
  14027. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14028. std::string cert;
  14029. read_file(SERVER_CERT2_FILE, cert);
  14030. SSLClient cli("google.com");
  14031. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14032. cli.enable_system_ca(true);
  14033. cli.enable_server_certificate_verification(true);
  14034. auto res = cli.Get("/");
  14035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14036. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14037. }
  14038. // The custom CA remains effective when combined with the system CA
  14039. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14040. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14041. ASSERT_TRUE(svr.is_valid());
  14042. svr.Get("/test", [&](const Request &, Response &res) {
  14043. res.set_content("test", "text/plain");
  14044. });
  14045. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14046. auto se = detail::scope_exit([&] {
  14047. svr.stop();
  14048. t.join();
  14049. ASSERT_FALSE(svr.is_running());
  14050. });
  14051. svr.wait_until_ready();
  14052. SSLClient cli("127.0.0.1", PORT);
  14053. std::string cert;
  14054. read_file(SERVER_CERT2_FILE, cert);
  14055. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14056. cli.enable_system_ca(true);
  14057. cli.enable_server_certificate_verification(true);
  14058. cli.set_connection_timeout(30);
  14059. auto res = cli.Get("/test");
  14060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14061. ASSERT_EQ(StatusCode::OK_200, res->status);
  14062. }
  14063. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14064. // skip chain verification entirely (only the certificate identity was
  14065. // checked), so a server presenting an untrusted certificate with a matching
  14066. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14067. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14068. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14069. ASSERT_TRUE(svr.is_valid());
  14070. svr.Get("/test", [&](const Request &, Response &res) {
  14071. res.set_content("test", "text/plain");
  14072. });
  14073. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14074. auto se = detail::scope_exit([&] {
  14075. svr.stop();
  14076. t.join();
  14077. ASSERT_FALSE(svr.is_running());
  14078. });
  14079. svr.wait_until_ready();
  14080. SSLClient cli("127.0.0.1", PORT);
  14081. std::string cert;
  14082. // A trusted CA that did not sign the server certificate. The server cert
  14083. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14084. // this connection.
  14085. read_file(CLIENT_CA_CERT_FILE, cert);
  14086. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14087. cli.enable_server_certificate_verification(true);
  14088. cli.set_connection_timeout(30);
  14089. auto res = cli.Get("/test");
  14090. ASSERT_FALSE(res);
  14091. }
  14092. // enable_system_ca(false) prevents system CA loading entirely
  14093. TEST(SSLClientTest, DisableSystemCa_Online) {
  14094. SSLClient cli("google.com");
  14095. cli.enable_system_ca(false);
  14096. cli.enable_server_certificate_verification(true);
  14097. auto res = cli.Get("/");
  14098. ASSERT_FALSE(res);
  14099. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14100. // itself when the CA chain is empty
  14101. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14102. res.error() == Error::SSLConnection);
  14103. }
  14104. // The universal Client forwards enable_system_ca()
  14105. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14106. std::string cert;
  14107. read_file(SERVER_CERT2_FILE, cert);
  14108. Client cli("https://google.com");
  14109. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14110. cli.enable_system_ca(true);
  14111. cli.enable_server_certificate_verification(true);
  14112. auto res = cli.Get("/");
  14113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14114. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14115. }
  14116. // The system CA policy must carry over to the client created internally for
  14117. // following a cross-host HTTPS redirect
  14118. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14119. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14120. ASSERT_TRUE(svr.is_valid());
  14121. svr.Get("/index", [&](const Request &, Response &res) {
  14122. res.set_redirect("https://www.google.com/");
  14123. });
  14124. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14125. auto se = detail::scope_exit([&] {
  14126. svr.stop();
  14127. t.join();
  14128. ASSERT_FALSE(svr.is_running());
  14129. });
  14130. svr.wait_until_ready();
  14131. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14132. std::string cert;
  14133. read_file(SERVER_CERT2_FILE, cert);
  14134. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14135. cli.enable_system_ca(true);
  14136. cli.enable_server_certificate_verification(true);
  14137. cli.set_follow_location(true);
  14138. cli.set_connection_timeout(30);
  14139. // Receiving any response proves the redirect client completed the TLS
  14140. // handshake with a system-CA-signed host
  14141. auto res = cli.Get("/index");
  14142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14143. }
  14144. TEST(MultipartFormDataTest, LargeData) {
  14145. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14146. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14147. const ContentReader &content_reader) {
  14148. if (req.is_multipart_form_data()) {
  14149. std::vector<FormData> items;
  14150. content_reader(
  14151. [&](const FormData &file) {
  14152. items.push_back(file);
  14153. return true;
  14154. },
  14155. [&](const char *data, size_t data_length) {
  14156. items.back().content.append(data, data_length);
  14157. return true;
  14158. });
  14159. EXPECT_TRUE(std::string(items[0].name) == "document");
  14160. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14161. EXPECT_TRUE(items[0].filename == "2MB_data");
  14162. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14163. EXPECT_TRUE(items[1].name == "hello");
  14164. EXPECT_TRUE(items[1].content == "world");
  14165. EXPECT_TRUE(items[1].filename == "");
  14166. EXPECT_TRUE(items[1].content_type == "");
  14167. } else {
  14168. std::string body;
  14169. content_reader([&](const char *data, size_t data_length) {
  14170. body.append(data, data_length);
  14171. return true;
  14172. });
  14173. }
  14174. });
  14175. auto port = svr.bind_to_any_port(HOST);
  14176. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14177. auto se = detail::scope_exit([&] {
  14178. svr.stop();
  14179. t.join();
  14180. ASSERT_FALSE(svr.is_running());
  14181. });
  14182. svr.wait_until_ready();
  14183. {
  14184. std::string data(1024 * 1024 * 2, '.');
  14185. std::stringstream buffer;
  14186. buffer << data;
  14187. SSLClient cli(HOST, port);
  14188. cli.enable_server_certificate_verification(false);
  14189. UploadFormDataItems items{
  14190. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14191. {"hello", "world", "", ""},
  14192. };
  14193. auto res = cli.Post("/post", items);
  14194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14195. ASSERT_EQ(StatusCode::OK_200, res->status);
  14196. }
  14197. }
  14198. TEST(MultipartFormDataTest, DataProviderItems) {
  14199. std::random_device seed_gen;
  14200. std::mt19937 random(seed_gen());
  14201. std::string rand1;
  14202. rand1.resize(1000);
  14203. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14204. std::string rand2;
  14205. rand2.resize(3000);
  14206. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14207. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14208. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14209. const ContentReader &content_reader) {
  14210. ASSERT_FALSE(req.is_multipart_form_data());
  14211. std::string body;
  14212. content_reader([&](const char *data, size_t data_length) {
  14213. body.append(data, data_length);
  14214. return true;
  14215. });
  14216. EXPECT_EQ(body, "");
  14217. });
  14218. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14219. const ContentReader &content_reader) {
  14220. ASSERT_TRUE(req.is_multipart_form_data());
  14221. std::vector<FormData> items;
  14222. content_reader(
  14223. [&](const FormData &file) {
  14224. items.push_back(file);
  14225. return true;
  14226. },
  14227. [&](const char *data, size_t data_length) {
  14228. items.back().content.append(data, data_length);
  14229. return true;
  14230. });
  14231. ASSERT_TRUE(items.size() == 2);
  14232. EXPECT_EQ(std::string(items[0].name), "name1");
  14233. EXPECT_EQ(items[0].content, "Testing123");
  14234. EXPECT_EQ(items[0].filename, "filename1");
  14235. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14236. EXPECT_EQ(items[1].name, "name2");
  14237. EXPECT_EQ(items[1].content, "Testing456");
  14238. EXPECT_EQ(items[1].filename, "");
  14239. EXPECT_EQ(items[1].content_type, "");
  14240. });
  14241. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14242. const ContentReader &content_reader) {
  14243. ASSERT_TRUE(req.is_multipart_form_data());
  14244. std::vector<FormData> items;
  14245. content_reader(
  14246. [&](const FormData &file) {
  14247. items.push_back(file);
  14248. return true;
  14249. },
  14250. [&](const char *data, size_t data_length) {
  14251. items.back().content.append(data, data_length);
  14252. return true;
  14253. });
  14254. ASSERT_TRUE(items.size() == 2);
  14255. EXPECT_EQ(items[0].name, "name3");
  14256. EXPECT_EQ(items[0].content, rand1);
  14257. EXPECT_EQ(items[0].filename, "filename3");
  14258. EXPECT_EQ(items[0].content_type, "");
  14259. EXPECT_EQ(items[1].name, "name4");
  14260. EXPECT_EQ(items[1].content, rand2);
  14261. EXPECT_EQ(items[1].filename, "filename4");
  14262. EXPECT_EQ(items[1].content_type, "");
  14263. });
  14264. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14265. const ContentReader &content_reader) {
  14266. ASSERT_TRUE(req.is_multipart_form_data());
  14267. std::vector<FormData> items;
  14268. content_reader(
  14269. [&](const FormData &file) {
  14270. items.push_back(file);
  14271. return true;
  14272. },
  14273. [&](const char *data, size_t data_length) {
  14274. items.back().content.append(data, data_length);
  14275. return true;
  14276. });
  14277. ASSERT_TRUE(items.size() == 4);
  14278. EXPECT_EQ(std::string(items[0].name), "name1");
  14279. EXPECT_EQ(items[0].content, "Testing123");
  14280. EXPECT_EQ(items[0].filename, "filename1");
  14281. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14282. EXPECT_EQ(items[1].name, "name2");
  14283. EXPECT_EQ(items[1].content, "Testing456");
  14284. EXPECT_EQ(items[1].filename, "");
  14285. EXPECT_EQ(items[1].content_type, "");
  14286. EXPECT_EQ(items[2].name, "name3");
  14287. EXPECT_EQ(items[2].content, rand1);
  14288. EXPECT_EQ(items[2].filename, "filename3");
  14289. EXPECT_EQ(items[2].content_type, "");
  14290. EXPECT_EQ(items[3].name, "name4");
  14291. EXPECT_EQ(items[3].content, rand2);
  14292. EXPECT_EQ(items[3].filename, "filename4");
  14293. EXPECT_EQ(items[3].content_type, "");
  14294. });
  14295. auto port = svr.bind_to_any_port("localhost");
  14296. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14297. auto se = detail::scope_exit([&] {
  14298. svr.stop();
  14299. t.join();
  14300. ASSERT_FALSE(svr.is_running());
  14301. });
  14302. svr.wait_until_ready();
  14303. {
  14304. SSLClient cli("localhost", port);
  14305. cli.enable_server_certificate_verification(false);
  14306. UploadFormDataItems items{
  14307. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14308. {"name2", "Testing456", "", ""}, // not a file
  14309. };
  14310. {
  14311. auto res = cli.Post("/post-none", {}, {}, {});
  14312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14313. ASSERT_EQ(StatusCode::OK_200, res->status);
  14314. }
  14315. FormDataProviderItems providers;
  14316. {
  14317. auto res =
  14318. cli.Post("/post-items", {}, items, providers); // empty providers
  14319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14320. ASSERT_EQ(StatusCode::OK_200, res->status);
  14321. }
  14322. providers.push_back({"name3",
  14323. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14324. // test the offset is given correctly at each step
  14325. if (!offset)
  14326. sink.os.write(rand1.data(), 30);
  14327. else if (offset == 30)
  14328. sink.os.write(rand1.data() + 30, 300);
  14329. else if (offset == 330)
  14330. sink.os.write(rand1.data() + 330, 670);
  14331. else if (offset == rand1.size())
  14332. sink.done();
  14333. return true;
  14334. },
  14335. "filename3",
  14336. {}});
  14337. providers.push_back({"name4",
  14338. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14339. // test the offset is given correctly at each step
  14340. if (!offset)
  14341. sink.os.write(rand2.data(), 2000);
  14342. else if (offset == 2000)
  14343. sink.os.write(rand2.data() + 2000, 1);
  14344. else if (offset == 2001)
  14345. sink.os.write(rand2.data() + 2001, 999);
  14346. else if (offset == rand2.size())
  14347. sink.done();
  14348. return true;
  14349. },
  14350. "filename4",
  14351. {}});
  14352. {
  14353. auto res = cli.Post("/post-providers", {}, {}, providers);
  14354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14355. ASSERT_EQ(StatusCode::OK_200, res->status);
  14356. }
  14357. {
  14358. auto res = cli.Post("/post-both", {}, items, providers);
  14359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14360. ASSERT_EQ(StatusCode::OK_200, res->status);
  14361. }
  14362. }
  14363. }
  14364. TEST(MultipartFormDataTest, BadHeader) {
  14365. Server svr;
  14366. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14367. res.set_content("ok", "text/plain");
  14368. });
  14369. thread t = thread([&] { svr.listen(HOST, PORT); });
  14370. auto se = detail::scope_exit([&] {
  14371. svr.stop();
  14372. t.join();
  14373. ASSERT_FALSE(svr.is_running());
  14374. });
  14375. svr.wait_until_ready();
  14376. const std::string body =
  14377. "This is the preamble. It is to be ignored, though it\r\n"
  14378. "is a handy place for composition agents to include an\r\n"
  14379. "explanatory note to non-MIME conformant readers.\r\n"
  14380. "\r\n"
  14381. "\r\n"
  14382. "--simple boundary\r\n"
  14383. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14384. ": BAD...\r\n"
  14385. "\r\n"
  14386. "value1\r\n"
  14387. "--simple boundary\r\n"
  14388. "Content-Disposition: form-data; name=\"field2\"; "
  14389. "filename=\"example.txt\"\r\n"
  14390. "\r\n"
  14391. "value2\r\n"
  14392. "--simple boundary--\r\n"
  14393. "This is the epilogue. It is also to be ignored.\r\n";
  14394. std::string content_type =
  14395. R"(multipart/form-data; boundary="simple boundary")";
  14396. Client cli(HOST, PORT);
  14397. auto res = cli.Post("/post", body, content_type.c_str());
  14398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14399. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14400. }
  14401. TEST(MultipartFormDataTest, WithPreamble) {
  14402. Server svr;
  14403. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14404. res.set_content("ok", "text/plain");
  14405. });
  14406. thread t = thread([&] { svr.listen(HOST, PORT); });
  14407. auto se = detail::scope_exit([&] {
  14408. svr.stop();
  14409. t.join();
  14410. ASSERT_FALSE(svr.is_running());
  14411. });
  14412. svr.wait_until_ready();
  14413. const std::string body =
  14414. "This is the preamble. It is to be ignored, though it\r\n"
  14415. "is a handy place for composition agents to include an\r\n"
  14416. "explanatory note to non-MIME conformant readers.\r\n"
  14417. "\r\n"
  14418. "\r\n"
  14419. "--simple boundary\r\n"
  14420. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14421. "\r\n"
  14422. "value1\r\n"
  14423. "--simple boundary\r\n"
  14424. "Content-Disposition: form-data; name=\"field2\"; "
  14425. "filename=\"example.txt\"\r\n"
  14426. "\r\n"
  14427. "value2\r\n"
  14428. "--simple boundary--\r\n"
  14429. "This is the epilogue. It is also to be ignored.\r\n";
  14430. std::string content_type =
  14431. R"(multipart/form-data; boundary="simple boundary")";
  14432. Client cli(HOST, PORT);
  14433. auto res = cli.Post("/post", body, content_type.c_str());
  14434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14435. EXPECT_EQ(StatusCode::OK_200, res->status);
  14436. }
  14437. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14438. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14439. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14440. const ContentReader &content_reader) {
  14441. if (req.is_multipart_form_data()) {
  14442. std::vector<FormData> items;
  14443. content_reader(
  14444. [&](const FormData &file) {
  14445. items.push_back(file);
  14446. return true;
  14447. },
  14448. [&](const char *data, size_t data_length) {
  14449. items.back().content.append(data, data_length);
  14450. return true;
  14451. });
  14452. EXPECT_TRUE(std::string(items[0].name) == "document");
  14453. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14454. EXPECT_TRUE(items[0].filename == "2MB_data");
  14455. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14456. EXPECT_TRUE(items[1].name == "hello");
  14457. EXPECT_TRUE(items[1].content == "world");
  14458. EXPECT_TRUE(items[1].filename == "");
  14459. EXPECT_TRUE(items[1].content_type == "");
  14460. } else {
  14461. std::string body;
  14462. content_reader([&](const char *data, size_t data_length) {
  14463. body.append(data, data_length);
  14464. return true;
  14465. });
  14466. }
  14467. });
  14468. auto port = svr.bind_to_any_port("localhost");
  14469. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14470. auto se = detail::scope_exit([&] {
  14471. svr.stop();
  14472. t.join();
  14473. ASSERT_FALSE(svr.is_running());
  14474. });
  14475. svr.wait_until_ready();
  14476. {
  14477. std::string data(1024 * 1024 * 2, '.');
  14478. std::stringstream buffer;
  14479. buffer << data;
  14480. SSLClient cli("localhost", port);
  14481. cli.enable_server_certificate_verification(false);
  14482. UploadFormDataItems items{
  14483. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14484. {"hello", "world", "", ""},
  14485. };
  14486. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14488. ASSERT_EQ(StatusCode::OK_200, res->status);
  14489. }
  14490. }
  14491. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14492. std::string data(1024 * 1024 * 2, '&');
  14493. std::stringstream buffer;
  14494. buffer << data;
  14495. Client cli("https://localhost:8080");
  14496. UploadFormDataItems items{
  14497. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14498. {"hello", "world", "", ""},
  14499. };
  14500. for (const char &c : " \t\r\n") {
  14501. auto res =
  14502. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14503. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14504. ASSERT_FALSE(res);
  14505. }
  14506. }
  14507. TEST(MultipartFormDataTest, PutFormData) {
  14508. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14509. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14510. const ContentReader &content_reader) {
  14511. if (req.is_multipart_form_data()) {
  14512. std::vector<FormData> items;
  14513. content_reader(
  14514. [&](const FormData &file) {
  14515. items.push_back(file);
  14516. return true;
  14517. },
  14518. [&](const char *data, size_t data_length) {
  14519. items.back().content.append(data, data_length);
  14520. return true;
  14521. });
  14522. EXPECT_TRUE(std::string(items[0].name) == "document");
  14523. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14524. EXPECT_TRUE(items[0].filename == "2MB_data");
  14525. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14526. EXPECT_TRUE(items[1].name == "hello");
  14527. EXPECT_TRUE(items[1].content == "world");
  14528. EXPECT_TRUE(items[1].filename == "");
  14529. EXPECT_TRUE(items[1].content_type == "");
  14530. } else {
  14531. std::string body;
  14532. content_reader([&](const char *data, size_t data_length) {
  14533. body.append(data, data_length);
  14534. return true;
  14535. });
  14536. }
  14537. });
  14538. auto port = svr.bind_to_any_port("localhost");
  14539. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14540. auto se = detail::scope_exit([&] {
  14541. svr.stop();
  14542. t.join();
  14543. ASSERT_FALSE(svr.is_running());
  14544. });
  14545. svr.wait_until_ready();
  14546. {
  14547. std::string data(1024 * 1024 * 2, '&');
  14548. std::stringstream buffer;
  14549. buffer << data;
  14550. SSLClient cli("localhost", port);
  14551. cli.enable_server_certificate_verification(false);
  14552. UploadFormDataItems items{
  14553. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14554. {"hello", "world", "", ""},
  14555. };
  14556. auto res = cli.Put("/put", items);
  14557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14558. ASSERT_EQ(StatusCode::OK_200, res->status);
  14559. }
  14560. }
  14561. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14562. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14563. svr.Put("/put_customboundary",
  14564. [&](const Request &req, const Response & /*res*/,
  14565. const ContentReader &content_reader) {
  14566. if (req.is_multipart_form_data()) {
  14567. std::vector<FormData> items;
  14568. content_reader(
  14569. [&](const FormData &file) {
  14570. items.push_back(file);
  14571. return true;
  14572. },
  14573. [&](const char *data, size_t data_length) {
  14574. items.back().content.append(data, data_length);
  14575. return true;
  14576. });
  14577. EXPECT_TRUE(std::string(items[0].name) == "document");
  14578. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14579. EXPECT_TRUE(items[0].filename == "2MB_data");
  14580. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14581. EXPECT_TRUE(items[1].name == "hello");
  14582. EXPECT_TRUE(items[1].content == "world");
  14583. EXPECT_TRUE(items[1].filename == "");
  14584. EXPECT_TRUE(items[1].content_type == "");
  14585. } else {
  14586. std::string body;
  14587. content_reader([&](const char *data, size_t data_length) {
  14588. body.append(data, data_length);
  14589. return true;
  14590. });
  14591. }
  14592. });
  14593. auto port = svr.bind_to_any_port("localhost");
  14594. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14595. auto se = detail::scope_exit([&] {
  14596. svr.stop();
  14597. t.join();
  14598. ASSERT_FALSE(svr.is_running());
  14599. });
  14600. svr.wait_until_ready();
  14601. {
  14602. std::string data(1024 * 1024 * 2, '&');
  14603. std::stringstream buffer;
  14604. buffer << data;
  14605. SSLClient cli("localhost", port);
  14606. cli.enable_server_certificate_verification(false);
  14607. UploadFormDataItems items{
  14608. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14609. {"hello", "world", "", ""},
  14610. };
  14611. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14613. ASSERT_EQ(StatusCode::OK_200, res->status);
  14614. }
  14615. }
  14616. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14617. std::string data(1024 * 1024 * 2, '&');
  14618. std::stringstream buffer;
  14619. buffer << data;
  14620. Client cli("https://localhost:8080");
  14621. cli.enable_server_certificate_verification(false);
  14622. UploadFormDataItems items{
  14623. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14624. {"hello", "world", "", ""},
  14625. };
  14626. for (const char &c : " \t\r\n") {
  14627. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14628. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14629. ASSERT_FALSE(res);
  14630. }
  14631. }
  14632. TEST(MultipartFormDataTest, AlternateFilename) {
  14633. auto handled = false;
  14634. Server svr;
  14635. svr.Post("/test", [&](const Request &req, Response &res) {
  14636. ASSERT_EQ(2u, req.form.files.size());
  14637. ASSERT_EQ(1u, req.form.fields.size());
  14638. // Test files
  14639. const auto &file1 = req.form.get_file("file1");
  14640. ASSERT_EQ("file1", file1.name);
  14641. ASSERT_EQ("A.txt", file1.filename);
  14642. ASSERT_EQ("text/plain", file1.content_type);
  14643. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14644. const auto &file2 = req.form.get_file("file2");
  14645. ASSERT_EQ("file2", file2.name);
  14646. ASSERT_EQ("a.html", file2.filename);
  14647. ASSERT_EQ("text/html", file2.content_type);
  14648. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14649. file2.content);
  14650. // Test text field
  14651. const auto &text = req.form.get_field("text");
  14652. ASSERT_EQ("text default", text);
  14653. res.set_content("ok", "text/plain");
  14654. handled = true;
  14655. });
  14656. thread t = thread([&] { svr.listen(HOST, PORT); });
  14657. auto se = detail::scope_exit([&] {
  14658. svr.stop();
  14659. t.join();
  14660. ASSERT_FALSE(svr.is_running());
  14661. ASSERT_TRUE(handled);
  14662. });
  14663. svr.wait_until_ready();
  14664. auto req = "POST /test HTTP/1.1\r\n"
  14665. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14666. "Content-Length: 399\r\n"
  14667. "\r\n"
  14668. "----------\r\n"
  14669. "Content-Disposition: form-data; name=\"text\"\r\n"
  14670. "\r\n"
  14671. "text default\r\n"
  14672. "----------\r\n"
  14673. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14674. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14675. "Content-Type: text/plain\r\n"
  14676. "\r\n"
  14677. "Content of a.txt.\r\n"
  14678. "\r\n"
  14679. "----------\r\n"
  14680. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14681. "\"a.html\"\r\n"
  14682. "Content-Type: text/html\r\n"
  14683. "\r\n"
  14684. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14685. "\r\n"
  14686. "------------\r\n";
  14687. ASSERT_TRUE(send_request(1, req));
  14688. }
  14689. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14690. auto handled = false;
  14691. Server svr;
  14692. svr.Post("/test", [&](const Request &req, Response &res) {
  14693. // Case-insensitive "utf-8''" prefix with a long value
  14694. const auto &file = req.form.get_file("file1");
  14695. ASSERT_EQ("file1", file.name);
  14696. // 8000 chars exercises both the Content-Disposition parser and the
  14697. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  14698. // Prior to the fix, std::regex_match on this header would cause O(N)
  14699. // stack recursion in libstdc++, leading to SIGSEGV.
  14700. std::string expected_filename(8000, 'A');
  14701. ASSERT_EQ(expected_filename, file.filename);
  14702. res.set_content("ok", "text/plain");
  14703. handled = true;
  14704. });
  14705. thread t = thread([&] { svr.listen(HOST, PORT); });
  14706. auto se = detail::scope_exit([&] {
  14707. svr.stop();
  14708. t.join();
  14709. ASSERT_FALSE(svr.is_running());
  14710. ASSERT_TRUE(handled);
  14711. });
  14712. svr.wait_until_ready();
  14713. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14714. // Regression test for GHSA-qq6v-r583-3h69
  14715. std::string long_filename(8000, 'A');
  14716. std::string body = "----------\r\n"
  14717. "Content-Disposition: form-data; name=\"file1\"; "
  14718. "filename*=\"Utf-8''" +
  14719. long_filename +
  14720. "\"\r\n"
  14721. "\r\n"
  14722. "hello\r\n"
  14723. "------------\r\n";
  14724. auto req = "POST /test HTTP/1.1\r\n"
  14725. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14726. "Content-Length: " +
  14727. std::to_string(body.size()) + "\r\n\r\n" + body;
  14728. ASSERT_TRUE(send_request(1, req));
  14729. }
  14730. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14731. auto handled = false;
  14732. Server svr;
  14733. svr.Post("/test", [&](const Request &req, Response &) {
  14734. ASSERT_EQ(2u, req.form.fields.size());
  14735. const auto &text1 = req.form.get_field("text1");
  14736. ASSERT_EQ("text1", text1);
  14737. const auto &text2 = req.form.get_field("text2");
  14738. ASSERT_EQ("text2", text2);
  14739. handled = true;
  14740. });
  14741. thread t = thread([&] { svr.listen(HOST, PORT); });
  14742. auto se = detail::scope_exit([&] {
  14743. svr.stop();
  14744. t.join();
  14745. ASSERT_FALSE(svr.is_running());
  14746. ASSERT_TRUE(handled);
  14747. });
  14748. svr.wait_until_ready();
  14749. auto req = "POST /test HTTP/1.1\r\n"
  14750. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14751. "Content-Length: 146\r\n"
  14752. "\r\n----------\r\n"
  14753. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14754. "\r\n"
  14755. "text1"
  14756. "\r\n----------\r\n"
  14757. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14758. "\r\n"
  14759. "text2"
  14760. "\r\n------------";
  14761. std::string response;
  14762. ASSERT_TRUE(send_request(1, req, &response));
  14763. ASSERT_EQ("200", response.substr(9, 3));
  14764. }
  14765. TEST(MultipartFormDataTest, ContentLength) {
  14766. auto handled = false;
  14767. Server svr;
  14768. svr.Post("/test", [&](const Request &req, Response &) {
  14769. ASSERT_EQ(2u, req.form.fields.size());
  14770. const auto &text1 = req.form.get_field("text1");
  14771. ASSERT_EQ("text1", text1);
  14772. const auto &text2 = req.form.get_field("text2");
  14773. ASSERT_EQ("text2", text2);
  14774. handled = true;
  14775. });
  14776. thread t = thread([&] { svr.listen(HOST, PORT); });
  14777. auto se = detail::scope_exit([&] {
  14778. svr.stop();
  14779. t.join();
  14780. ASSERT_FALSE(svr.is_running());
  14781. ASSERT_TRUE(handled);
  14782. });
  14783. svr.wait_until_ready();
  14784. auto req = "POST /test HTTP/1.1\r\n"
  14785. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14786. "Content-Length: 167\r\n"
  14787. "\r\n----------\r\n"
  14788. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14789. "Content-Length: 5\r\n"
  14790. "\r\n"
  14791. "text1"
  14792. "\r\n----------\r\n"
  14793. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14794. "\r\n"
  14795. "text2"
  14796. "\r\n------------\r\n";
  14797. std::string response;
  14798. ASSERT_TRUE(send_request(1, req, &response));
  14799. ASSERT_EQ("200", response.substr(9, 3));
  14800. }
  14801. TEST(MultipartFormDataTest, AccessPartHeaders) {
  14802. auto handled = false;
  14803. Server svr;
  14804. svr.Post("/test", [&](const Request &req, Response &) {
  14805. ASSERT_EQ(2u, req.form.fields.size());
  14806. const auto &text1 = req.form.get_field("text1");
  14807. ASSERT_EQ("text1", text1);
  14808. // TODO: Add header access for text fields if needed
  14809. const auto &text2 = req.form.get_field("text2");
  14810. ASSERT_EQ("text2", text2);
  14811. // TODO: Header access for text fields needs to be implemented
  14812. // auto &headers = it->second.headers;
  14813. // ASSERT_EQ(3U, headers.size());
  14814. // auto custom_header = headers.find("x-whatever");
  14815. // ASSERT_TRUE(custom_header != headers.end());
  14816. // ASSERT_NE("customvalue", custom_header->second);
  14817. // ASSERT_EQ("CustomValue", custom_header->second);
  14818. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14819. handled = true;
  14820. });
  14821. thread t = thread([&] { svr.listen(HOST, PORT); });
  14822. auto se = detail::scope_exit([&] {
  14823. svr.stop();
  14824. t.join();
  14825. ASSERT_FALSE(svr.is_running());
  14826. ASSERT_TRUE(handled);
  14827. });
  14828. svr.wait_until_ready();
  14829. auto req = "POST /test HTTP/1.1\r\n"
  14830. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14831. "Content-Length: 232\r\n"
  14832. "\r\n----------\r\n"
  14833. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14834. "Content-Length: 5\r\n"
  14835. "X-Test: 1\r\n"
  14836. "\r\n"
  14837. "text1"
  14838. "\r\n----------\r\n"
  14839. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14840. "Content-Type: text/plain\r\n"
  14841. "X-Whatever: CustomValue\r\n"
  14842. "\r\n"
  14843. "text2"
  14844. "\r\n------------\r\n"
  14845. "That should be disregarded. Not even read";
  14846. std::string response;
  14847. ASSERT_TRUE(send_request(1, req, &response));
  14848. ASSERT_EQ("200", response.substr(9, 3));
  14849. }
  14850. TEST(MultipartFormDataTest, LargeHeader) {
  14851. auto handled = false;
  14852. Server svr;
  14853. svr.Post("/test", [&](const Request &req, Response &) {
  14854. ASSERT_EQ(1u, req.form.fields.size());
  14855. const auto &text = req.form.get_field("name1");
  14856. ASSERT_EQ("text1", text);
  14857. handled = true;
  14858. });
  14859. thread t = thread([&] { svr.listen(HOST, PORT); });
  14860. auto se = detail::scope_exit([&] {
  14861. svr.stop();
  14862. t.join();
  14863. ASSERT_FALSE(svr.is_running());
  14864. ASSERT_TRUE(handled);
  14865. });
  14866. svr.wait_until_ready();
  14867. auto boundary = std::string("cpp-httplib-multipart-data");
  14868. std::string content = "--" + boundary +
  14869. "\r\n"
  14870. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14871. "\r\n"
  14872. "text1\r\n"
  14873. "--" +
  14874. boundary + "--\r\n";
  14875. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14876. "Content-Type: multipart/form-data;boundary=" +
  14877. boundary +
  14878. "\r\n"
  14879. "Content-Length: " +
  14880. std::to_string(content.size()) +
  14881. "\r\n"
  14882. "Dummy-Header: ";
  14883. std::string header_suffix = "\r\n"
  14884. "\r\n";
  14885. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14886. size_t header_dummy_size =
  14887. read_buff_size -
  14888. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14889. auto header_dummy = std::string(header_dummy_size, '@');
  14890. auto req = header_prefix + header_dummy + header_suffix + content;
  14891. std::string response;
  14892. ASSERT_TRUE(send_request(1, req, &response));
  14893. ASSERT_EQ("200", response.substr(9, 3));
  14894. }
  14895. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14896. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14897. // (not chunked Transfer-Encoding) after the streaming refactor.
  14898. auto handled = false;
  14899. Server svr;
  14900. svr.Post("/upload", [&](const Request &req, Response &res) {
  14901. auto cl_it = req.headers.find("Content-Length");
  14902. EXPECT_TRUE(cl_it != req.headers.end());
  14903. auto te_it = req.headers.find("Transfer-Encoding");
  14904. EXPECT_TRUE(te_it == req.headers.end());
  14905. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  14906. res.set_content("ok", "text/plain");
  14907. handled = true;
  14908. });
  14909. auto port = svr.bind_to_any_port(HOST);
  14910. auto t = thread([&] { svr.listen_after_bind(); });
  14911. auto se = detail::scope_exit([&] {
  14912. svr.stop();
  14913. t.join();
  14914. ASSERT_FALSE(svr.is_running());
  14915. ASSERT_TRUE(handled);
  14916. });
  14917. svr.wait_until_ready();
  14918. UploadFormDataItems items = {
  14919. {"field1", "hello", "", "text/plain"},
  14920. {"file1", "world", "test.txt", "application/octet-stream"},
  14921. };
  14922. Client cli(HOST, port);
  14923. auto res = cli.Post("/upload", {}, items);
  14924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14925. EXPECT_EQ(StatusCode::OK_200, res->status);
  14926. }
  14927. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14928. // Verify that make_multipart_content_provider coalesces many small segments
  14929. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14930. constexpr size_t kItemCount = 1000;
  14931. UploadFormDataItems items;
  14932. items.reserve(kItemCount);
  14933. for (size_t i = 0; i < kItemCount; i++) {
  14934. items.push_back(
  14935. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14936. }
  14937. const std::string boundary = "----test-boundary";
  14938. auto content_length = detail::get_multipart_content_length(items, boundary);
  14939. auto provider = detail::make_multipart_content_provider(items, boundary);
  14940. // Drive the provider the same way write_content_with_progress does
  14941. size_t write_count = 0;
  14942. size_t total_bytes = 0;
  14943. DataSink sink;
  14944. size_t offset = 0;
  14945. sink.write = [&](const char *d, size_t l) -> bool {
  14946. (void)d;
  14947. write_count++;
  14948. total_bytes += l;
  14949. offset += l;
  14950. return true;
  14951. };
  14952. sink.is_writable = []() -> bool { return true; };
  14953. while (offset < content_length) {
  14954. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  14955. }
  14956. EXPECT_EQ(content_length, total_bytes);
  14957. // The total number of segments is 3 * kItemCount + 1 = 3001.
  14958. // With buffering into 64KB blocks, write_count should be much smaller.
  14959. auto segment_count = 3 * kItemCount + 1;
  14960. EXPECT_LT(write_count, segment_count / 10);
  14961. }
  14962. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  14963. // Integration test: send many UploadFormDataItems and verify the server
  14964. // receives all of them correctly (#2410).
  14965. constexpr size_t kItemCount = 500;
  14966. auto handled = false;
  14967. Server svr;
  14968. svr.Post("/upload", [&](const Request &req, Response &res) {
  14969. EXPECT_EQ(kItemCount, req.form.fields.size());
  14970. for (size_t i = 0; i < kItemCount; i++) {
  14971. auto key = "field" + std::to_string(i);
  14972. auto val = "value" + std::to_string(i);
  14973. auto it = req.form.fields.find(key);
  14974. if (it != req.form.fields.end()) {
  14975. EXPECT_EQ(val, it->second.content);
  14976. } else {
  14977. ADD_FAILURE() << "Missing field: " << key;
  14978. }
  14979. }
  14980. res.set_content("ok", "text/plain");
  14981. handled = true;
  14982. });
  14983. auto port = svr.bind_to_any_port(HOST);
  14984. auto t = thread([&] { svr.listen_after_bind(); });
  14985. auto se = detail::scope_exit([&] {
  14986. svr.stop();
  14987. t.join();
  14988. ASSERT_FALSE(svr.is_running());
  14989. ASSERT_TRUE(handled);
  14990. });
  14991. svr.wait_until_ready();
  14992. UploadFormDataItems items;
  14993. items.reserve(kItemCount);
  14994. for (size_t i = 0; i < kItemCount; i++) {
  14995. items.push_back(
  14996. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14997. }
  14998. Client cli(HOST, port);
  14999. auto res = cli.Post("/upload", items);
  15000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15001. EXPECT_EQ(StatusCode::OK_200, res->status);
  15002. }
  15003. TEST(MultipartFormDataTest, MakeFileProvider) {
  15004. // Verify make_file_provider sends a file's contents correctly.
  15005. const std::string file_content(4096, 'Z');
  15006. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  15007. {
  15008. std::ofstream ofs(tmp_path, std::ios::binary);
  15009. ofs.write(file_content.data(),
  15010. static_cast<std::streamsize>(file_content.size()));
  15011. }
  15012. auto handled = false;
  15013. Server svr;
  15014. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  15015. const ContentReader &content_reader) {
  15016. ASSERT_TRUE(req.is_multipart_form_data());
  15017. std::vector<FormData> items;
  15018. content_reader(
  15019. [&](const FormData &file) {
  15020. items.push_back(file);
  15021. return true;
  15022. },
  15023. [&](const char *data, size_t data_length) {
  15024. items.back().content.append(data, data_length);
  15025. return true;
  15026. });
  15027. ASSERT_EQ(1u, items.size());
  15028. EXPECT_EQ("myfile", items[0].name);
  15029. EXPECT_EQ("data.bin", items[0].filename);
  15030. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15031. EXPECT_EQ(file_content, items[0].content);
  15032. handled = true;
  15033. });
  15034. auto port = svr.bind_to_any_port(HOST);
  15035. auto t = thread([&] { svr.listen_after_bind(); });
  15036. auto se = detail::scope_exit([&] {
  15037. svr.stop();
  15038. t.join();
  15039. ASSERT_FALSE(svr.is_running());
  15040. ASSERT_TRUE(handled);
  15041. std::remove(tmp_path.c_str());
  15042. });
  15043. svr.wait_until_ready();
  15044. FormDataProviderItems providers;
  15045. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15046. "application/octet-stream"));
  15047. Client cli(HOST, port);
  15048. auto res = cli.Post("/upload", {}, {}, providers);
  15049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15050. EXPECT_EQ(StatusCode::OK_200, res->status);
  15051. }
  15052. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15053. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15054. // (100) headers is rejected with a 400 Bad Request response.
  15055. Server svr;
  15056. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15057. res.set_content("ok", "text/plain");
  15058. });
  15059. thread t = thread([&] { svr.listen(HOST, PORT); });
  15060. auto se = detail::scope_exit([&] {
  15061. svr.stop();
  15062. t.join();
  15063. ASSERT_FALSE(svr.is_running());
  15064. });
  15065. svr.wait_until_ready();
  15066. // Build a multipart part with 101 custom headers (exceeding
  15067. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15068. std::stringstream body;
  15069. body << "--simpleboundary\r\n"
  15070. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15071. for (int i = 0; i < 101; i++) {
  15072. body << "X-Custom-Header-" << i << ": value\r\n";
  15073. }
  15074. body << "\r\n"
  15075. << "value1\r\n"
  15076. << "--simpleboundary--\r\n";
  15077. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15078. Client cli(HOST, PORT);
  15079. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15081. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15082. }
  15083. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15084. // A body that never contains the declared boundary must not be accumulated
  15085. // while the parser waits for it. Buffering it would also make every read
  15086. // rescan everything seen so far, which is quadratic in the body size.
  15087. Server svr;
  15088. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15089. res.set_content("ok", "text/plain");
  15090. });
  15091. auto port = svr.bind_to_any_port(HOST);
  15092. thread t = thread([&] { svr.listen_after_bind(); });
  15093. auto se = detail::scope_exit([&] {
  15094. svr.stop();
  15095. t.join();
  15096. ASSERT_FALSE(svr.is_running());
  15097. });
  15098. svr.wait_until_ready();
  15099. Client cli(HOST, port);
  15100. cli.set_read_timeout(60, 0);
  15101. cli.set_write_timeout(60, 0);
  15102. // '-' is the worst case: it matches the first character of the boundary, so
  15103. // every position has to be checked against it.
  15104. auto post_dashes = [&](size_t size) {
  15105. const std::string body(size, '-');
  15106. auto start = std::chrono::steady_clock::now();
  15107. auto res =
  15108. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15109. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15110. std::chrono::steady_clock::now() - start)
  15111. .count();
  15112. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15113. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15114. return ms;
  15115. };
  15116. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15117. // Windows.
  15118. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15119. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15120. // Comparing the two sizes rather than checking an absolute duration keeps
  15121. // this meaningful across build types and CI load, both of which move the
  15122. // absolute numbers by more than an order of magnitude. Four times the bytes
  15123. // costs about four times the time when parsing is linear, and about sixteen
  15124. // times when the body is buffered and rescanned.
  15125. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15126. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15127. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15128. << "ms, which suggests the body is being buffered and rescanned";
  15129. }
  15130. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15131. // A boundary can only be followed by CRLF or by "--", so anything else is
  15132. // malformed no matter what comes next. The parser must say so right away
  15133. // instead of buffering the rest of the declared body.
  15134. Server svr;
  15135. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15136. res.set_content("ok", "text/plain");
  15137. });
  15138. auto port = svr.bind_to_any_port(HOST);
  15139. thread t = thread([&] { svr.listen_after_bind(); });
  15140. auto se = detail::scope_exit([&] {
  15141. svr.stop();
  15142. t.join();
  15143. ASSERT_FALSE(svr.is_running());
  15144. });
  15145. svr.wait_until_ready();
  15146. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15147. // buffers instead of failing would still be waiting for the remaining bytes.
  15148. const std::string body = "--zzzz\r\n"
  15149. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15150. "\r\n"
  15151. "text1"
  15152. "\r\n--zzzzXX";
  15153. const std::string req = "POST /post HTTP/1.1\r\n"
  15154. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15155. "Content-Length: 1048576\r\n"
  15156. "\r\n" +
  15157. body;
  15158. std::string response;
  15159. ASSERT_TRUE(send_request(3, req, &response, port));
  15160. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15161. EXPECT_EQ("400", response.substr(9, 3));
  15162. }
  15163. // Posts a multipart body split into two writes, so that the server sees the
  15164. // split at whatever offset the caller chose, and expects the single "text1"
  15165. // field to come through.
  15166. static void expect_split_multipart_ok(const std::string &body1,
  15167. const std::string &body2) {
  15168. auto handled = false;
  15169. Server svr;
  15170. svr.Post("/post", [&](const Request &req, Response &) {
  15171. EXPECT_EQ(1u, req.form.fields.size());
  15172. EXPECT_EQ("text1", req.form.get_field("text1"));
  15173. handled = true;
  15174. });
  15175. auto port = svr.bind_to_any_port(HOST);
  15176. thread t = thread([&] { svr.listen_after_bind(); });
  15177. auto se = detail::scope_exit([&] {
  15178. svr.stop();
  15179. t.join();
  15180. ASSERT_FALSE(svr.is_running());
  15181. ASSERT_TRUE(handled);
  15182. });
  15183. svr.wait_until_ready();
  15184. // "Connection: close" makes the server close once it has answered, so the
  15185. // response drain ends immediately instead of idling until the read timeout.
  15186. const std::string head =
  15187. "POST /post HTTP/1.1\r\n"
  15188. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15189. "Connection: close\r\n"
  15190. "Content-Length: " +
  15191. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15192. std::string response;
  15193. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15194. ASSERT_GE(response.size(), 12u) << "no response";
  15195. EXPECT_EQ("200", response.substr(9, 3));
  15196. }
  15197. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15198. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15199. // ignored, including when it does not arrive in the same read as the
  15200. // close-delimiter itself.
  15201. expect_split_multipart_ok("--zzzz\r\n"
  15202. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15203. "\r\n"
  15204. "text1"
  15205. "\r\n--zzzz--",
  15206. "\r\nthis epilogue must be ignored\r\n");
  15207. }
  15208. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15209. // The initial boundary may be preceded by a preamble of any length and may
  15210. // straddle a read boundary. Discarding data while waiting for it must not
  15211. // throw away a partial boundary sitting at the end of the buffer.
  15212. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15213. "zz\r\n"
  15214. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15215. "\r\n"
  15216. "text1"
  15217. "\r\n--zzzz--\r\n");
  15218. }
  15219. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15220. // The received boundary was only checked for being non-empty, so it could be
  15221. // as long as a header is allowed to be. The parser scans the body for
  15222. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15223. // costs a nearly full comparison at nearly every position, making the
  15224. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15225. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15226. Server svr;
  15227. svr.Post("/post", [](const Request &req, Response &res) {
  15228. EXPECT_EQ(1u, req.form.fields.size());
  15229. EXPECT_EQ("text1", req.form.get_field("text1"));
  15230. res.set_content("ok", "text/plain");
  15231. });
  15232. auto port = svr.bind_to_any_port(HOST);
  15233. thread t = thread([&] { svr.listen_after_bind(); });
  15234. auto se = detail::scope_exit([&] {
  15235. svr.stop();
  15236. t.join();
  15237. ASSERT_FALSE(svr.is_running());
  15238. });
  15239. svr.wait_until_ready();
  15240. Client cli(HOST, port);
  15241. auto post_with_boundary_of_length = [&](size_t len) {
  15242. const std::string boundary(len, 'a');
  15243. const std::string body =
  15244. "--" + boundary +
  15245. "\r\n"
  15246. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15247. "\r\n"
  15248. "text1"
  15249. "\r\n--" +
  15250. boundary + "--\r\n";
  15251. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15252. };
  15253. auto res = post_with_boundary_of_length(70);
  15254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15255. EXPECT_EQ(StatusCode::OK_200, res->status);
  15256. res = post_with_boundary_of_length(71);
  15257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15258. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15259. }
  15260. TEST(MakeFileBodyTest, Basic) {
  15261. const std::string file_content(4096, 'Z');
  15262. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15263. {
  15264. std::ofstream ofs(tmp_path, std::ios::binary);
  15265. ofs.write(file_content.data(),
  15266. static_cast<std::streamsize>(file_content.size()));
  15267. }
  15268. auto handled = false;
  15269. Server svr;
  15270. svr.Post("/upload", [&](const Request &req, Response &res) {
  15271. EXPECT_EQ(file_content, req.body);
  15272. handled = true;
  15273. res.status = StatusCode::OK_200;
  15274. });
  15275. auto port = svr.bind_to_any_port(HOST);
  15276. auto t = thread([&] { svr.listen_after_bind(); });
  15277. auto se = detail::scope_exit([&] {
  15278. svr.stop();
  15279. t.join();
  15280. ASSERT_FALSE(svr.is_running());
  15281. ASSERT_TRUE(handled);
  15282. std::remove(tmp_path.c_str());
  15283. });
  15284. svr.wait_until_ready();
  15285. auto fb = make_file_body(tmp_path);
  15286. ASSERT_GT(fb.first, 0u);
  15287. Client cli(HOST, port);
  15288. auto res =
  15289. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15291. EXPECT_EQ(StatusCode::OK_200, res->status);
  15292. }
  15293. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15294. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15295. {
  15296. std::ofstream ofs(path, std::ios::binary);
  15297. const std::string content(100, 'A');
  15298. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15299. }
  15300. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15301. auto body = make_file_body(path);
  15302. ASSERT_EQ(100u, body.first);
  15303. ASSERT_TRUE(static_cast<bool>(body.second));
  15304. // Rewritten shorter after its length was measured - and, on a server, after
  15305. // that length has already gone out as Content-Length.
  15306. {
  15307. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15308. const std::string content(10, 'A');
  15309. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15310. }
  15311. std::string written;
  15312. DataSink sink;
  15313. sink.write = [&](const char *d, size_t l) {
  15314. written.append(d, l);
  15315. return true;
  15316. };
  15317. // The provider has to report failure. write_content_with_progress() advances
  15318. // its offset only by what was written, so a provider that returns true
  15319. // without completing the length it promised is called again straight away,
  15320. // and again.
  15321. EXPECT_FALSE(body.second(0, body.first, sink));
  15322. EXPECT_EQ(std::string(10, 'A'), written);
  15323. }
  15324. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15325. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15326. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15327. {
  15328. std::ofstream ofs(path, std::ios::binary);
  15329. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15330. }
  15331. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15332. auto body = make_file_body(path);
  15333. ASSERT_EQ(content.size(), body.first);
  15334. ASSERT_TRUE(static_cast<bool>(body.second));
  15335. std::string written;
  15336. DataSink sink;
  15337. sink.write = [&](const char *d, size_t l) {
  15338. written.append(d, l);
  15339. return true;
  15340. };
  15341. EXPECT_TRUE(body.second(0, body.first, sink));
  15342. EXPECT_EQ(content, written);
  15343. }
  15344. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15345. static constexpr unsigned int number_of_tasks{1000000};
  15346. std::atomic_uint count{0};
  15347. std::unique_ptr<TaskQueue> task_queue{
  15348. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15349. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15350. auto queued = task_queue->enqueue(
  15351. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15352. EXPECT_TRUE(queued);
  15353. }
  15354. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15355. task_queue->shutdown();
  15356. #else
  15357. EXPECT_NO_THROW(task_queue->shutdown());
  15358. #endif
  15359. EXPECT_EQ(number_of_tasks, count.load());
  15360. }
  15361. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15362. static constexpr unsigned int number_of_tasks{1000000};
  15363. static constexpr unsigned int qlimit{2};
  15364. unsigned int queued_count{0};
  15365. std::atomic_uint count{0};
  15366. std::unique_ptr<TaskQueue> task_queue{
  15367. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15368. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15369. if (task_queue->enqueue(
  15370. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15371. queued_count++;
  15372. }
  15373. }
  15374. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15375. task_queue->shutdown();
  15376. #else
  15377. EXPECT_NO_THROW(task_queue->shutdown());
  15378. #endif
  15379. EXPECT_EQ(queued_count, count.load());
  15380. EXPECT_TRUE(queued_count <= number_of_tasks);
  15381. EXPECT_TRUE(queued_count >= qlimit);
  15382. }
  15383. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15384. // Use a short idle timeout so a dynamic thread spawns, times out and
  15385. // exits during the test, and the pool keeps working afterwards.
  15386. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15387. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15388. /*idle_timeout_sec=*/1}};
  15389. std::atomic_uint count{0};
  15390. std::condition_variable cv;
  15391. std::mutex mtx;
  15392. bool release = false;
  15393. // Block the base thread so the second task spawns a dynamic thread.
  15394. EXPECT_TRUE(task_queue->enqueue([&] {
  15395. std::unique_lock<std::mutex> lock(mtx);
  15396. while (!release) {
  15397. cv.wait(lock);
  15398. }
  15399. count++;
  15400. }));
  15401. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15402. // Let the dynamic thread finish its task and exceed the idle timeout.
  15403. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15404. {
  15405. std::unique_lock<std::mutex> lock(mtx);
  15406. release = true;
  15407. }
  15408. cv.notify_all();
  15409. // The pool must still accept and run tasks after the dynamic thread exited.
  15410. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15411. task_queue->shutdown();
  15412. EXPECT_EQ(3u, count.load());
  15413. }
  15414. TEST(TaskQueueTest, MaxQueuedRequests) {
  15415. static constexpr unsigned int qlimit{3};
  15416. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15417. std::condition_variable sem_cv;
  15418. std::mutex sem_mtx;
  15419. int credits = 0;
  15420. bool queued;
  15421. /* Fill up the queue with tasks that will block until we give them credits to
  15422. * complete. */
  15423. for (unsigned int n = 0; n <= qlimit;) {
  15424. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15425. std::unique_lock<std::mutex> lock(sem_mtx);
  15426. while (credits <= 0) {
  15427. sem_cv.wait(lock);
  15428. }
  15429. /* Consume the credit and signal the test code if they are all gone. */
  15430. if (--credits == 0) { sem_cv.notify_one(); }
  15431. });
  15432. if (n < qlimit) {
  15433. /* The first qlimit enqueues must succeed. */
  15434. EXPECT_TRUE(queued);
  15435. } else {
  15436. /* The last one will succeed only when the worker thread
  15437. * starts and dequeues the first blocking task. Although
  15438. * not necessary for the correctness of this test, we sleep for
  15439. * a short while to avoid busy waiting. */
  15440. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15441. }
  15442. if (queued) { n++; }
  15443. }
  15444. /* Further enqueues must fail since the queue is full. */
  15445. for (auto i = 0; i < 4; i++) {
  15446. queued = task_queue->enqueue([] {});
  15447. EXPECT_FALSE(queued);
  15448. }
  15449. /* Give the credits to allow the previous tasks to complete. */
  15450. {
  15451. std::unique_lock<std::mutex> lock(sem_mtx);
  15452. credits += qlimit + 1;
  15453. }
  15454. sem_cv.notify_all();
  15455. /* Wait for all the credits to be consumed. */
  15456. {
  15457. std::unique_lock<std::mutex> lock(sem_mtx);
  15458. while (credits > 0) {
  15459. sem_cv.wait(lock);
  15460. }
  15461. }
  15462. /* Check that we are able again to enqueue at least qlimit tasks. */
  15463. for (unsigned int i = 0; i < qlimit; i++) {
  15464. queued = task_queue->enqueue([] {});
  15465. EXPECT_TRUE(queued);
  15466. }
  15467. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15468. task_queue->shutdown();
  15469. #else
  15470. EXPECT_NO_THROW(task_queue->shutdown());
  15471. #endif
  15472. }
  15473. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15474. Server svr;
  15475. std::string method;
  15476. std::string body;
  15477. auto has_content_length = false;
  15478. auto has_transfer_encoding = false;
  15479. std::atomic<int> bad_requests{0};
  15480. // Leftover body bytes get parsed as a malformed request and answered with
  15481. // 400
  15482. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15483. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15484. });
  15485. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15486. res.set_redirect("/down", StatusCode::SeeOther_303);
  15487. });
  15488. svr.Get("/down", [&](const Request &req, Response &res) {
  15489. method = req.method;
  15490. body = req.body;
  15491. has_content_length = req.has_header("Content-Length");
  15492. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15493. res.set_content("ok", "text/plain");
  15494. });
  15495. auto port = svr.bind_to_any_port(HOST);
  15496. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15497. auto se = detail::scope_exit([&] {
  15498. svr.stop();
  15499. thread.join();
  15500. ASSERT_FALSE(svr.is_running());
  15501. });
  15502. svr.wait_until_ready();
  15503. const std::string payload = "SECRET-BODY";
  15504. auto check = [&](Client &cli, const Result &res) {
  15505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15506. EXPECT_EQ(StatusCode::OK_200, res->status);
  15507. EXPECT_EQ("ok", res->body);
  15508. EXPECT_EQ("GET", method);
  15509. EXPECT_TRUE(body.empty());
  15510. EXPECT_FALSE(has_content_length);
  15511. EXPECT_FALSE(has_transfer_encoding);
  15512. // Nothing of the original body may be left on the connection
  15513. auto res2 = cli.Get("/down");
  15514. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15515. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15516. EXPECT_EQ("ok", res2->body);
  15517. EXPECT_EQ(0, bad_requests);
  15518. };
  15519. // With content length
  15520. {
  15521. Client cli(HOST, port);
  15522. cli.set_keep_alive(true);
  15523. cli.set_follow_location(true);
  15524. auto res = cli.Post(
  15525. "/up", payload.size(),
  15526. [&](size_t offset, size_t length, DataSink &sink) {
  15527. return sink.write(payload.data() + offset, length);
  15528. },
  15529. "text/plain");
  15530. check(cli, res);
  15531. }
  15532. // Without content length (chunked)
  15533. {
  15534. Client cli(HOST, port);
  15535. cli.set_keep_alive(true);
  15536. cli.set_follow_location(true);
  15537. auto res = cli.Post(
  15538. "/up",
  15539. [&](size_t /*offset*/, DataSink &sink) {
  15540. sink.write(payload.data(), payload.size());
  15541. sink.done();
  15542. return true;
  15543. },
  15544. "text/plain");
  15545. check(cli, res);
  15546. }
  15547. }
  15548. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15549. Server svr;
  15550. std::string target;
  15551. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15552. // Echo the still-encoded name back in the Location
  15553. const std::string prefix = "/start/";
  15554. res.status = StatusCode::Found_302;
  15555. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15556. });
  15557. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15558. target = req.target;
  15559. res.set_content("ok", "text/plain");
  15560. });
  15561. auto port = svr.bind_to_any_port(HOST);
  15562. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15563. auto se = detail::scope_exit([&] {
  15564. svr.stop();
  15565. thread.join();
  15566. ASSERT_FALSE(svr.is_running());
  15567. });
  15568. svr.wait_until_ready();
  15569. // Decoding the Location path would turn the first four into a path
  15570. // separator, a query delimiter, a fragment delimiter and a different
  15571. // percent-encoded octet. The rest must keep reaching the server as they are.
  15572. const std::vector<std::string> names = {
  15573. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15574. };
  15575. for (auto path_encode : {true, false}) {
  15576. Client cli(HOST, port);
  15577. cli.set_follow_location(true);
  15578. cli.set_path_encode(path_encode);
  15579. for (const auto &name : names) {
  15580. target.clear();
  15581. auto res = cli.Get("/start/" + name);
  15582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15583. EXPECT_EQ(StatusCode::OK_200, res->status);
  15584. EXPECT_EQ("/dest/" + name, target);
  15585. }
  15586. }
  15587. }
  15588. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15589. Server svr;
  15590. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15591. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15592. });
  15593. svr.Get("/hello", [](const Request &req, Response &res) {
  15594. res.set_content(req.get_param_value("key"), "text/plain");
  15595. });
  15596. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15597. auto se = detail::scope_exit([&] {
  15598. svr.stop();
  15599. thread.join();
  15600. ASSERT_FALSE(svr.is_running());
  15601. });
  15602. svr.wait_until_ready();
  15603. {
  15604. Client cli(HOST, PORT);
  15605. cli.set_follow_location(true);
  15606. auto res = cli.Get("/");
  15607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15608. EXPECT_EQ(StatusCode::OK_200, res->status);
  15609. EXPECT_EQ("val&key2=val2", res->body);
  15610. }
  15611. }
  15612. #endif
  15613. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15614. Server svr;
  15615. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15616. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15617. });
  15618. svr.Get("/hello", [](const Request &req, Response &res) {
  15619. res.set_content(req.get_param_value("key"), "text/plain");
  15620. });
  15621. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15622. auto se = detail::scope_exit([&] {
  15623. svr.stop();
  15624. thread.join();
  15625. ASSERT_FALSE(svr.is_running());
  15626. });
  15627. svr.wait_until_ready();
  15628. {
  15629. Client cli(HOST, PORT);
  15630. cli.set_follow_location(true);
  15631. auto res = cli.Get("/");
  15632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15633. EXPECT_EQ(StatusCode::OK_200, res->status);
  15634. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15635. }
  15636. }
  15637. TEST(RedirectTest, RedirectWithPlusInPath) {
  15638. Server svr;
  15639. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15640. res.set_redirect("/a+b");
  15641. });
  15642. // Route pattern uses regex; escape + as \\+
  15643. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15644. res.set_content(req.path, "text/plain");
  15645. });
  15646. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15647. auto se = detail::scope_exit([&] {
  15648. svr.stop();
  15649. thread.join();
  15650. ASSERT_FALSE(svr.is_running());
  15651. });
  15652. svr.wait_until_ready();
  15653. {
  15654. Client cli(HOST, PORT);
  15655. cli.set_follow_location(true);
  15656. auto res = cli.Get("/");
  15657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15658. EXPECT_EQ(StatusCode::OK_200, res->status);
  15659. EXPECT_EQ("/a+b", res->body);
  15660. }
  15661. }
  15662. TEST(RedirectTest, ResolveRelativeLocation) {
  15663. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15664. const std::vector<std::pair<std::string, std::string>> cases = {
  15665. {"g", "/b/c/g"},
  15666. {"./g", "/b/c/g"},
  15667. {"g/", "/b/c/g/"},
  15668. {"?y", "/b/c/d;p?y"},
  15669. {"g?y", "/b/c/g?y"},
  15670. {"#s", "/b/c/d;p?q#s"},
  15671. {"g#s", "/b/c/g#s"},
  15672. {"g?y#s", "/b/c/g?y#s"},
  15673. {";x", "/b/c/;x"},
  15674. {"g;x", "/b/c/g;x"},
  15675. {".", "/b/c/"},
  15676. {"./", "/b/c/"},
  15677. {"..", "/b/"},
  15678. {"../", "/b/"},
  15679. {"../g", "/b/g"},
  15680. {"../..", "/"},
  15681. {"../../", "/"},
  15682. {"../../g", "/g"},
  15683. {"../../../g", "/g"},
  15684. {"g.", "/b/c/g."},
  15685. {".g", "/b/c/.g"},
  15686. {"g..", "/b/c/g.."},
  15687. {"..g", "/b/c/..g"},
  15688. {"./../g", "/b/g"},
  15689. {"./g/.", "/b/c/g/"},
  15690. {"g/./h", "/b/c/g/h"},
  15691. {"g/../h", "/b/c/h"},
  15692. {"g;x=1/./y", "/b/c/g;x=1/y"},
  15693. {"g;x=1/../y", "/b/c/y"},
  15694. {"g?y/./x", "/b/c/g?y/./x"},
  15695. {"g#s/../x", "/b/c/g#s/../x"},
  15696. // Not relative-path references, so left for parse_url.
  15697. {"/g", "/g"},
  15698. {"//g", "//g"},
  15699. {"http://g/x", "http://g/x"},
  15700. {"g:h", "g:h"},
  15701. };
  15702. for (const auto &c : cases) {
  15703. EXPECT_EQ(c.second,
  15704. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15705. << c.first;
  15706. }
  15707. }
  15708. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15709. Server svr;
  15710. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15711. res.set_redirect(req.get_param_value("to"));
  15712. });
  15713. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15714. res.set_content(req.target, "text/plain");
  15715. });
  15716. svr.Get("/other", [](const Request &req, Response &res) {
  15717. res.set_content(req.target, "text/plain");
  15718. });
  15719. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15720. auto se = detail::scope_exit([&] {
  15721. svr.stop();
  15722. thread.join();
  15723. ASSERT_FALSE(svr.is_running());
  15724. });
  15725. svr.wait_until_ready();
  15726. const std::vector<std::pair<std::string, std::string>> cases = {
  15727. {"next", "/dir/next"},
  15728. {"./next?x=1", "/dir/next?x=1"},
  15729. {"../other", "/other"},
  15730. };
  15731. for (const auto &c : cases) {
  15732. Client cli(HOST, PORT);
  15733. cli.set_follow_location(true);
  15734. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15735. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15736. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  15737. EXPECT_EQ(c.second, res->body) << c.first;
  15738. }
  15739. }
  15740. #ifdef CPPHTTPLIB_SSL_ENABLED
  15741. TEST(RedirectTest, Issue2185_Online) {
  15742. SSLClient client("github.com");
  15743. client.set_follow_location(true);
  15744. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  15745. "Coollab-Windows.zip");
  15746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15747. EXPECT_EQ(StatusCode::OK_200, res->status);
  15748. EXPECT_EQ(9920427U, res->body.size());
  15749. }
  15750. #endif
  15751. TEST(VulnerabilityTest, CRLFInjection) {
  15752. Server svr;
  15753. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  15754. res.set_content("Hello 1", "text/plain");
  15755. });
  15756. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  15757. res.set_content("Hello 2", "text/plain");
  15758. });
  15759. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  15760. res.set_content("Hello 3", "text/plain");
  15761. });
  15762. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  15763. res.set_content("Hello 4", "text/plain");
  15764. });
  15765. svr.set_logger([](const Request &req, const Response & /*res*/) {
  15766. for (const auto &x : req.headers) {
  15767. auto key = x.first;
  15768. EXPECT_STRNE("evil", key.c_str());
  15769. }
  15770. });
  15771. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15772. auto se = detail::scope_exit([&] {
  15773. svr.stop();
  15774. thread.join();
  15775. ASSERT_FALSE(svr.is_running());
  15776. });
  15777. svr.wait_until_ready();
  15778. {
  15779. Client cli(HOST, PORT);
  15780. cli.Post("/test1", "A=B",
  15781. "application/x-www-form-urlencoded\r\nevil: hello1");
  15782. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  15783. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  15784. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  15785. }
  15786. }
  15787. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  15788. auto server_thread = std::thread([] {
  15789. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15790. default_socket_options(srv);
  15791. sockaddr_in addr{};
  15792. addr.sin_family = AF_INET;
  15793. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15794. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15795. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  15796. ::listen(srv, 1);
  15797. sockaddr_in cli_addr{};
  15798. socklen_t cli_len = sizeof(cli_addr);
  15799. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15800. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  15801. std::string buf_all;
  15802. char buf[2048];
  15803. ssize_t n;
  15804. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  15805. buf_all.append(buf, static_cast<size_t>(n));
  15806. size_t pos;
  15807. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  15808. auto request_block = buf_all.substr(0, pos + 4); // include separator
  15809. auto e = request_block.find("\r\n");
  15810. if (e != std::string::npos) {
  15811. auto request_line = request_block.substr(0, e);
  15812. std::string msg =
  15813. "CRLF injection detected in request line: '" + request_line + "'";
  15814. EXPECT_FALSE(true) << msg;
  15815. }
  15816. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  15817. ::send(cli,
  15818. #ifdef _WIN32
  15819. static_cast<const char *>(resp.c_str()),
  15820. static_cast<int>(resp.size()),
  15821. #else
  15822. resp.c_str(), resp.size(),
  15823. #endif
  15824. 0);
  15825. buf_all.erase(0, pos + 4);
  15826. }
  15827. }
  15828. detail::close_socket(cli);
  15829. detail::close_socket(srv);
  15830. });
  15831. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15832. auto cli = Client("127.0.0.1", PORT + 1);
  15833. auto headers = Headers{
  15834. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  15835. {"Connection", "keep-alive"}};
  15836. auto res = cli.Get("/hi", headers);
  15837. EXPECT_FALSE(res);
  15838. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15839. server_thread.join();
  15840. }
  15841. // A request rejected before any byte reaches the socket must fail right away
  15842. // instead of waiting for a response the server will never send.
  15843. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  15844. // The kernel completes the TCP handshake from the listen backlog, so the
  15845. // client connects, but nothing ever reads, responds or closes.
  15846. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15847. default_socket_options(srv);
  15848. sockaddr_in addr{};
  15849. addr.sin_family = AF_INET;
  15850. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15851. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15852. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15853. ASSERT_EQ(0, ::listen(srv, 8));
  15854. auto cli = Client("127.0.0.1", PORT + 1);
  15855. cli.set_read_timeout(10, 0);
  15856. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  15857. return std::chrono::duration_cast<std::chrono::milliseconds>(
  15858. std::chrono::steady_clock::now() - start)
  15859. .count();
  15860. };
  15861. {
  15862. Request req;
  15863. req.method = "GE T";
  15864. req.path = "/";
  15865. auto start = std::chrono::steady_clock::now();
  15866. auto res = cli.send(req);
  15867. EXPECT_FALSE(res);
  15868. EXPECT_EQ(Error::Write, res.error());
  15869. EXPECT_LT(elapsed_ms(start), 1000);
  15870. }
  15871. {
  15872. auto start = std::chrono::steady_clock::now();
  15873. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  15874. EXPECT_FALSE(res);
  15875. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15876. EXPECT_LT(elapsed_ms(start), 1000);
  15877. }
  15878. EXPECT_FALSE(cli.is_socket_open());
  15879. detail::close_socket(srv);
  15880. }
  15881. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  15882. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15883. default_socket_options(srv);
  15884. sockaddr_in addr{};
  15885. addr.sin_family = AF_INET;
  15886. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15887. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15888. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15889. ASSERT_EQ(0, ::listen(srv, 1));
  15890. std::string received;
  15891. auto server_thread = std::thread([&] {
  15892. auto sock = ::accept(srv, nullptr, nullptr);
  15893. if (sock == INVALID_SOCKET) { return; }
  15894. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  15895. char buf[2048];
  15896. ssize_t n;
  15897. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  15898. received.append(buf, static_cast<size_t>(n));
  15899. }
  15900. detail::close_socket(sock);
  15901. });
  15902. {
  15903. auto cli = Client("127.0.0.1", PORT + 1);
  15904. // "Z" sorts after the default headers, so writing straight to the socket
  15905. // would have sent the request line and those headers before the rejection.
  15906. auto handle =
  15907. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  15908. EXPECT_FALSE(handle.is_valid());
  15909. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  15910. }
  15911. server_thread.join();
  15912. detail::close_socket(srv);
  15913. EXPECT_TRUE(received.empty()) << received;
  15914. }
  15915. TEST(PathParamsTest, StaticMatch) {
  15916. const auto pattern = "/users/all";
  15917. detail::PathParamsMatcher matcher(pattern);
  15918. Request request;
  15919. request.path = "/users/all";
  15920. ASSERT_TRUE(matcher.match(request));
  15921. std::unordered_map<std::string, std::string> expected_params = {};
  15922. EXPECT_EQ(request.path_params, expected_params);
  15923. }
  15924. TEST(PathParamsTest, StaticMismatch) {
  15925. const auto pattern = "/users/all";
  15926. detail::PathParamsMatcher matcher(pattern);
  15927. Request request;
  15928. request.path = "/users/1";
  15929. ASSERT_FALSE(matcher.match(request));
  15930. }
  15931. TEST(PathParamsTest, SingleParamInTheMiddle) {
  15932. const auto pattern = "/users/:id/subscriptions";
  15933. detail::PathParamsMatcher matcher(pattern);
  15934. Request request;
  15935. request.path = "/users/42/subscriptions";
  15936. ASSERT_TRUE(matcher.match(request));
  15937. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15938. EXPECT_EQ(request.path_params, expected_params);
  15939. }
  15940. TEST(PathParamsTest, SingleParamInTheEnd) {
  15941. const auto pattern = "/users/:id";
  15942. detail::PathParamsMatcher matcher(pattern);
  15943. Request request;
  15944. request.path = "/users/24";
  15945. ASSERT_TRUE(matcher.match(request));
  15946. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  15947. EXPECT_EQ(request.path_params, expected_params);
  15948. }
  15949. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  15950. const auto pattern = "/users/:id/";
  15951. detail::PathParamsMatcher matcher(pattern);
  15952. Request request;
  15953. request.path = "/users/42/";
  15954. ASSERT_TRUE(matcher.match(request));
  15955. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15956. EXPECT_EQ(request.path_params, expected_params);
  15957. }
  15958. TEST(PathParamsTest, EmptyParam) {
  15959. const auto pattern = "/users/:id/";
  15960. detail::PathParamsMatcher matcher(pattern);
  15961. Request request;
  15962. request.path = "/users//";
  15963. ASSERT_TRUE(matcher.match(request));
  15964. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  15965. EXPECT_EQ(request.path_params, expected_params);
  15966. }
  15967. TEST(PathParamsTest, FragmentMismatch) {
  15968. const auto pattern = "/users/:id/";
  15969. detail::PathParamsMatcher matcher(pattern);
  15970. Request request;
  15971. request.path = "/admins/24/";
  15972. ASSERT_FALSE(matcher.match(request));
  15973. }
  15974. TEST(PathParamsTest, ExtraFragments) {
  15975. const auto pattern = "/users/:id";
  15976. detail::PathParamsMatcher matcher(pattern);
  15977. Request request;
  15978. request.path = "/users/42/subscriptions";
  15979. ASSERT_FALSE(matcher.match(request));
  15980. }
  15981. TEST(PathParamsTest, MissingTrailingParam) {
  15982. const auto pattern = "/users/:id";
  15983. detail::PathParamsMatcher matcher(pattern);
  15984. Request request;
  15985. request.path = "/users";
  15986. ASSERT_FALSE(matcher.match(request));
  15987. }
  15988. TEST(PathParamsTest, MissingParamInTheMiddle) {
  15989. const auto pattern = "/users/:id/subscriptions";
  15990. detail::PathParamsMatcher matcher(pattern);
  15991. Request request;
  15992. request.path = "/users/subscriptions";
  15993. ASSERT_FALSE(matcher.match(request));
  15994. }
  15995. TEST(PathParamsTest, MultipleParams) {
  15996. const auto pattern = "/users/:userid/subscriptions/:subid";
  15997. detail::PathParamsMatcher matcher(pattern);
  15998. Request request;
  15999. request.path = "/users/42/subscriptions/2";
  16000. ASSERT_TRUE(matcher.match(request));
  16001. std::unordered_map<std::string, std::string> expected_params = {
  16002. {"userid", "42"}, {"subid", "2"}};
  16003. EXPECT_EQ(request.path_params, expected_params);
  16004. }
  16005. TEST(PathParamsTest, SequenceOfParams) {
  16006. const auto pattern = "/values/:x/:y/:z";
  16007. detail::PathParamsMatcher matcher(pattern);
  16008. Request request;
  16009. request.path = "/values/1/2/3";
  16010. ASSERT_TRUE(matcher.match(request));
  16011. std::unordered_map<std::string, std::string> expected_params = {
  16012. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  16013. EXPECT_EQ(request.path_params, expected_params);
  16014. }
  16015. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  16016. const auto pattern = "/prefix:suffix";
  16017. detail::PathParamsMatcher matcher(pattern);
  16018. Request request;
  16019. request.path = "/prefix:suffix";
  16020. ASSERT_TRUE(matcher.match(request));
  16021. const std::unordered_map<std::string, std::string> expected_params = {};
  16022. EXPECT_EQ(request.path_params, expected_params);
  16023. }
  16024. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16025. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16026. // calling thread's stack on a long enough path for a quantified pattern;
  16027. // RegexMatcher must refuse to run regex matching on paths beyond
  16028. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16029. detail::RegexMatcher matcher("/files/(.*)");
  16030. Request within_limit;
  16031. within_limit.path = "/files/" + std::string(10, 'A');
  16032. EXPECT_TRUE(matcher.match(within_limit));
  16033. Request over_limit;
  16034. over_limit.path =
  16035. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16036. EXPECT_FALSE(matcher.match(over_limit));
  16037. }
  16038. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16039. Server svr;
  16040. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16041. res.set_content("ok", "text/plain");
  16042. });
  16043. auto port = svr.bind_to_any_port(HOST);
  16044. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16045. auto se = detail::scope_exit([&] {
  16046. svr.stop();
  16047. thread.join();
  16048. ASSERT_FALSE(svr.is_running());
  16049. });
  16050. svr.wait_until_ready();
  16051. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16052. // request URI limit; this used to be able to crash the process.
  16053. std::string path =
  16054. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16055. std::string req = "GET " + path +
  16056. " HTTP/1.1\r\n"
  16057. "Host: " +
  16058. std::string(HOST) + ":" + std::to_string(port) +
  16059. "\r\n"
  16060. "Connection: close\r\n"
  16061. "\r\n";
  16062. std::string response;
  16063. ASSERT_TRUE(send_request(5, req, &response, port));
  16064. EXPECT_NE(std::string::npos, response.find("404"));
  16065. }
  16066. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16067. Server svr;
  16068. auto handler = [](const Request & /*req*/, Response &res) {
  16069. res.set_content("hit", "text/plain");
  16070. };
  16071. // No regex metacharacter, so this one is compared literally
  16072. svr.Get("/literal/route", handler);
  16073. // '.' is a regex metacharacter, so this one must keep regex semantics
  16074. svr.Get("/a.c", handler);
  16075. auto port = svr.bind_to_any_port(HOST);
  16076. std::thread t([&]() { svr.listen_after_bind(); });
  16077. auto se = detail::scope_exit([&] {
  16078. svr.stop();
  16079. t.join();
  16080. ASSERT_FALSE(svr.is_running());
  16081. });
  16082. svr.wait_until_ready();
  16083. Client cli(HOST, port);
  16084. struct {
  16085. const char *path;
  16086. int status;
  16087. } cases[] = {
  16088. {"/literal/route", StatusCode::OK_200},
  16089. {"/literal/routes", StatusCode::NotFound_404},
  16090. {"/literal/rout", StatusCode::NotFound_404},
  16091. {"/abc", StatusCode::OK_200},
  16092. {"/a.c", StatusCode::OK_200},
  16093. };
  16094. for (const auto &x : cases) {
  16095. auto res = cli.Get(x.path);
  16096. ASSERT_TRUE(res) << x.path;
  16097. EXPECT_EQ(x.status, res->status) << x.path;
  16098. }
  16099. }
  16100. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16101. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16102. // from exhausting the stack, so it must only constrain routes that actually
  16103. // run a regular expression. A literal route is matched by comparison and
  16104. // stays usable at any length.
  16105. Server svr;
  16106. const std::string pattern =
  16107. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16108. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16109. res.set_content("hit", "text/plain");
  16110. });
  16111. auto port = svr.bind_to_any_port(HOST);
  16112. std::thread t([&]() { 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. Client cli(HOST, port);
  16120. auto res = cli.Get(pattern);
  16121. ASSERT_TRUE(res);
  16122. EXPECT_EQ(StatusCode::OK_200, res->status);
  16123. }
  16124. TEST(ParseUrlTest, VariousPatterns) {
  16125. {
  16126. detail::UrlComponents uc;
  16127. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16128. EXPECT_EQ("http", uc.scheme);
  16129. EXPECT_EQ("example.com", uc.host);
  16130. EXPECT_EQ("8080", uc.port);
  16131. EXPECT_EQ("/path", uc.path);
  16132. EXPECT_EQ("?q=1", uc.query);
  16133. }
  16134. {
  16135. detail::UrlComponents uc;
  16136. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16137. EXPECT_EQ("https", uc.scheme);
  16138. EXPECT_EQ("example.com", uc.host);
  16139. EXPECT_TRUE(uc.port.empty());
  16140. EXPECT_EQ("/path", uc.path);
  16141. }
  16142. {
  16143. detail::UrlComponents uc;
  16144. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16145. EXPECT_EQ("::1", uc.host);
  16146. EXPECT_EQ("8080", uc.port);
  16147. EXPECT_EQ("/path", uc.path);
  16148. }
  16149. {
  16150. detail::UrlComponents uc;
  16151. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16152. }
  16153. {
  16154. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16155. // the path while the connection still targets the bracketed host.
  16156. detail::UrlComponents uc;
  16157. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16158. }
  16159. {
  16160. detail::UrlComponents uc;
  16161. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16162. }
  16163. {
  16164. detail::UrlComponents uc;
  16165. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16166. EXPECT_EQ("::1", uc.host);
  16167. EXPECT_TRUE(uc.port.empty());
  16168. EXPECT_EQ("/path", uc.path);
  16169. }
  16170. {
  16171. detail::UrlComponents uc;
  16172. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16173. EXPECT_TRUE(uc.scheme.empty());
  16174. EXPECT_EQ("example.com", uc.host);
  16175. EXPECT_EQ("/path", uc.path);
  16176. EXPECT_EQ("?q=1", uc.query);
  16177. }
  16178. {
  16179. detail::UrlComponents uc;
  16180. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16181. EXPECT_TRUE(uc.host.empty());
  16182. EXPECT_EQ("/path", uc.path);
  16183. EXPECT_EQ("?q=1", uc.query);
  16184. }
  16185. {
  16186. detail::UrlComponents uc;
  16187. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16188. EXPECT_EQ("example.com", uc.host);
  16189. EXPECT_EQ("8080", uc.port);
  16190. }
  16191. {
  16192. // Unix socket path — must not be parsed as host
  16193. detail::UrlComponents uc;
  16194. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16195. EXPECT_TRUE(uc.host.empty());
  16196. }
  16197. {
  16198. detail::UrlComponents uc;
  16199. ASSERT_TRUE(detail::parse_url("", uc));
  16200. EXPECT_TRUE(uc.host.empty());
  16201. EXPECT_TRUE(uc.path.empty());
  16202. }
  16203. {
  16204. detail::UrlComponents uc;
  16205. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16206. }
  16207. {
  16208. detail::UrlComponents uc;
  16209. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16210. }
  16211. {
  16212. // Accepted by parse_url; callers restrict to http/https
  16213. detail::UrlComponents uc;
  16214. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16215. EXPECT_EQ("ftp", uc.scheme);
  16216. }
  16217. {
  16218. detail::UrlComponents uc;
  16219. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16220. }
  16221. {
  16222. detail::UrlComponents uc;
  16223. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16224. }
  16225. }
  16226. TEST(ParseUrlTest, FragmentHandling) {
  16227. {
  16228. detail::UrlComponents uc;
  16229. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16230. EXPECT_EQ("/path", uc.path);
  16231. EXPECT_TRUE(uc.query.empty());
  16232. }
  16233. {
  16234. detail::UrlComponents uc;
  16235. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16236. EXPECT_TRUE(uc.path.empty());
  16237. EXPECT_TRUE(uc.query.empty());
  16238. }
  16239. }
  16240. TEST(ParseUrlTest, UserinfoHandling) {
  16241. // Userinfo with @ but no colon — host includes @
  16242. detail::UrlComponents uc;
  16243. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  16244. EXPECT_EQ("user@host.com", uc.host);
  16245. EXPECT_EQ("/path", uc.path);
  16246. }
  16247. TEST(ParseUrlTest, IPv6EdgeCases) {
  16248. {
  16249. detail::UrlComponents uc;
  16250. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16251. EXPECT_TRUE(uc.scheme.empty());
  16252. EXPECT_EQ("::1", uc.host);
  16253. EXPECT_EQ("8080", uc.port);
  16254. }
  16255. {
  16256. // Zone ID '%25' is not in [a-fA-F0-9:]
  16257. detail::UrlComponents uc;
  16258. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16259. }
  16260. }
  16261. TEST(ParseUrlTest, SchemeEdgeCases) {
  16262. {
  16263. detail::UrlComponents uc;
  16264. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16265. }
  16266. {
  16267. detail::UrlComponents uc;
  16268. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16269. }
  16270. {
  16271. detail::UrlComponents uc;
  16272. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16273. }
  16274. }
  16275. TEST(ParseUrlTest, PortEdgeCases) {
  16276. {
  16277. detail::UrlComponents uc;
  16278. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16279. EXPECT_TRUE(uc.port.empty());
  16280. EXPECT_EQ("/path", uc.path);
  16281. }
  16282. {
  16283. // parse_url accepts any port string; validation is done by parse_port
  16284. detail::UrlComponents uc;
  16285. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16286. EXPECT_EQ("abc", uc.port);
  16287. }
  16288. }
  16289. TEST(ParseUrlTest, WebSocketPatterns) {
  16290. {
  16291. detail::UrlComponents uc;
  16292. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16293. EXPECT_EQ("ws", uc.scheme);
  16294. EXPECT_EQ("echo.example.com", uc.host);
  16295. EXPECT_EQ("8080", uc.port);
  16296. EXPECT_EQ("/ws", uc.path);
  16297. }
  16298. {
  16299. detail::UrlComponents uc;
  16300. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16301. EXPECT_EQ("wss", uc.scheme);
  16302. EXPECT_EQ("echo.example.com", uc.host);
  16303. EXPECT_TRUE(uc.port.empty());
  16304. EXPECT_EQ("/ws", uc.path);
  16305. }
  16306. }
  16307. TEST(ParseUrlTest, QueryOnly) {
  16308. detail::UrlComponents uc;
  16309. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16310. EXPECT_TRUE(uc.host.empty());
  16311. EXPECT_TRUE(uc.path.empty());
  16312. EXPECT_EQ("?q=1&r=2", uc.query);
  16313. }
  16314. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16315. detail::UrlComponents uc;
  16316. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16317. EXPECT_TRUE(uc.scheme.empty());
  16318. EXPECT_EQ("example.com", uc.host);
  16319. EXPECT_EQ("443", uc.port);
  16320. EXPECT_EQ("/path", uc.path);
  16321. }
  16322. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16323. // If ipv6 regex working, regex match codepath is taken.
  16324. // else port will default to 80 in Client impl
  16325. int clientImplMagicPort = 80;
  16326. int port = 4321;
  16327. // above ports must be different to avoid false negative
  16328. EXPECT_NE(clientImplMagicPort, port);
  16329. std::string ipV6TestURL = "http://[ff06::c3]";
  16330. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16331. CLIENT_PRIVATE_KEY_FILE);
  16332. EXPECT_EQ(cli.port(), port);
  16333. }
  16334. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16335. auto file_path = "./www/dir/index.html";
  16336. auto dir_path = "./www/dir";
  16337. detail::FileStat stat_file(file_path);
  16338. EXPECT_TRUE(stat_file.is_file());
  16339. EXPECT_FALSE(stat_file.is_dir());
  16340. detail::FileStat stat_dir(dir_path);
  16341. EXPECT_FALSE(stat_dir.is_file());
  16342. EXPECT_TRUE(stat_dir.is_dir());
  16343. }
  16344. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16345. // IPv4 with default HTTP port (80)
  16346. EXPECT_EQ("example.com",
  16347. detail::make_host_and_port_string("example.com", 80, false));
  16348. // IPv4 with default HTTPS port (443)
  16349. EXPECT_EQ("example.com",
  16350. detail::make_host_and_port_string("example.com", 443, true));
  16351. // IPv4 with non-default HTTP port
  16352. EXPECT_EQ("example.com:8080",
  16353. detail::make_host_and_port_string("example.com", 8080, false));
  16354. // IPv4 with non-default HTTPS port
  16355. EXPECT_EQ("example.com:8443",
  16356. detail::make_host_and_port_string("example.com", 8443, true));
  16357. // IPv6 with default HTTP port (80)
  16358. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16359. // IPv6 with default HTTPS port (443)
  16360. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16361. // IPv6 with non-default HTTP port
  16362. EXPECT_EQ("[::1]:8080",
  16363. detail::make_host_and_port_string("::1", 8080, false));
  16364. // IPv6 with non-default HTTPS port
  16365. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16366. // IPv6 full address with default port
  16367. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16368. detail::make_host_and_port_string(
  16369. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16370. // IPv6 full address with non-default port
  16371. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16372. detail::make_host_and_port_string(
  16373. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16374. // IPv6 localhost with non-default port
  16375. EXPECT_EQ("[::1]:3000",
  16376. detail::make_host_and_port_string("::1", 3000, false));
  16377. // IPv6 with zone ID (link-local address) with default port
  16378. EXPECT_EQ("[fe80::1%eth0]",
  16379. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16380. // IPv6 with zone ID (link-local address) with non-default port
  16381. EXPECT_EQ("[fe80::1%eth0]:8080",
  16382. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16383. // Edge case: Port 443 with is_ssl=false (should add port)
  16384. EXPECT_EQ("example.com:443",
  16385. detail::make_host_and_port_string("example.com", 443, false));
  16386. // Edge case: Port 80 with is_ssl=true (should add port)
  16387. EXPECT_EQ("example.com:80",
  16388. detail::make_host_and_port_string("example.com", 80, true));
  16389. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16390. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16391. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16392. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16393. // Security fix: Already bracketed IPv6 should not get double brackets
  16394. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16395. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16396. EXPECT_EQ("[::1]:8080",
  16397. detail::make_host_and_port_string("[::1]", 8080, false));
  16398. EXPECT_EQ("[2001:db8::1]:8080",
  16399. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16400. EXPECT_EQ("[fe80::1%eth0]",
  16401. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16402. EXPECT_EQ("[fe80::1%eth0]:8080",
  16403. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16404. // Edge case: Empty host (should return as-is)
  16405. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16406. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16407. // This is a known limitation but shouldn't crash
  16408. EXPECT_EQ("[host:name]",
  16409. detail::make_host_and_port_string("host:name", 80, false));
  16410. // Port number edge cases (no validation, but should not crash)
  16411. EXPECT_EQ("example.com:0",
  16412. detail::make_host_and_port_string("example.com", 0, false));
  16413. EXPECT_EQ("example.com:-1",
  16414. detail::make_host_and_port_string("example.com", -1, false));
  16415. EXPECT_EQ("example.com:65535",
  16416. detail::make_host_and_port_string("example.com", 65535, false));
  16417. EXPECT_EQ("example.com:65536",
  16418. detail::make_host_and_port_string("example.com", 65536, false));
  16419. }
  16420. #ifdef CPPHTTPLIB_SSL_ENABLED
  16421. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16422. httplib::SSLClient cli("roblox.com", 443);
  16423. cli.set_follow_location(true);
  16424. auto res = cli.Get("/");
  16425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16426. EXPECT_EQ(StatusCode::OK_200, res->status);
  16427. }
  16428. #endif
  16429. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16430. Server svr;
  16431. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16432. EXPECT_EQ(res.status, 400);
  16433. });
  16434. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16435. auto se = detail::scope_exit([&] {
  16436. svr.stop();
  16437. thread.join();
  16438. ASSERT_FALSE(svr.is_running());
  16439. });
  16440. svr.wait_until_ready();
  16441. Client cli(HOST, PORT);
  16442. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16443. }
  16444. TEST(InvalidHeaderCharsTest, is_field_name) {
  16445. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16446. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16447. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16448. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16449. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16450. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16451. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16452. EXPECT_FALSE(detail::fields::is_field_name(""));
  16453. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16454. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16455. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16456. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16457. }
  16458. TEST(InvalidHeaderCharsTest, is_field_value) {
  16459. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16460. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16461. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16462. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16463. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16464. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16465. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16466. EXPECT_TRUE(detail::fields::is_field_value(""));
  16467. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16468. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16469. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16470. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16471. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16472. }
  16473. TEST(InvalidHeaderCharsTest, OnServer) {
  16474. Server svr;
  16475. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16476. std::string header = "Not Set";
  16477. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16478. res.set_header(header, "value");
  16479. res.set_content("Page Content Page Content", "text/plain");
  16480. });
  16481. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16482. std::string header = "Not Set";
  16483. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16484. res.set_header("X-Test", header);
  16485. res.set_content("Page Content Page Content", "text/plain");
  16486. });
  16487. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16488. auto se = detail::scope_exit([&] {
  16489. svr.stop();
  16490. thread.join();
  16491. ASSERT_FALSE(svr.is_running());
  16492. });
  16493. svr.wait_until_ready();
  16494. Client cli(HOST, PORT);
  16495. {
  16496. auto res = cli.Get(
  16497. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16499. EXPECT_EQ("Page Content Page Content", res->body);
  16500. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16501. }
  16502. {
  16503. auto res = cli.Get(
  16504. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16506. EXPECT_EQ("Page Content Page Content", res->body);
  16507. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16508. }
  16509. }
  16510. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16511. auto handled = false;
  16512. Server svr;
  16513. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16514. thread t = thread([&] { svr.listen(HOST, PORT); });
  16515. auto se = detail::scope_exit([&] {
  16516. svr.stop();
  16517. t.join();
  16518. ASSERT_FALSE(svr.is_running());
  16519. ASSERT_FALSE(handled);
  16520. });
  16521. svr.wait_until_ready();
  16522. auto req = "POST /test HTTP/1.1\r\n"
  16523. "Content-Length: x\r\n"
  16524. "\r\n";
  16525. std::string response;
  16526. ASSERT_TRUE(send_request(1, req, &response));
  16527. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16528. response.substr(0, response.find("\r\n")));
  16529. }
  16530. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16531. // case-insensitive, and a server that receives a 100-continue expectation in
  16532. // an HTTP/1.0 request MUST ignore it.
  16533. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16534. std::string response;
  16535. ASSERT_TRUE(send_request(1, req, &response, port));
  16536. *got_100 = response.find("100 Continue") != std::string::npos;
  16537. }
  16538. class ExpectTokenTest : public ::testing::Test {
  16539. protected:
  16540. void SetUp() override {
  16541. svr_.Post("/p", [](const Request &, Response &res) {
  16542. res.set_content("ok", "text/plain");
  16543. });
  16544. port_ = svr_.bind_to_any_port(HOST);
  16545. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16546. svr_.wait_until_ready();
  16547. }
  16548. void TearDown() override {
  16549. svr_.stop();
  16550. if (thread_.joinable()) { thread_.join(); }
  16551. }
  16552. std::string request(const char *version, const char *expect_value) const {
  16553. return std::string("POST /p ") + version +
  16554. "\r\n"
  16555. "Host: localhost\r\n"
  16556. "Content-Length: 2\r\n"
  16557. "Connection: close\r\n"
  16558. "Expect: " +
  16559. expect_value +
  16560. "\r\n"
  16561. "\r\n"
  16562. "hi";
  16563. }
  16564. Server svr_;
  16565. int port_ = 0;
  16566. thread thread_;
  16567. };
  16568. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16569. bool got_100 = false;
  16570. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16571. EXPECT_TRUE(got_100);
  16572. }
  16573. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16574. bool got_100 = true;
  16575. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16576. EXPECT_FALSE(got_100);
  16577. }
  16578. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16579. bool got_100 = false;
  16580. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16581. EXPECT_TRUE(got_100);
  16582. }
  16583. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16584. bool got_100 = false;
  16585. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16586. EXPECT_TRUE(got_100);
  16587. }
  16588. // `100 Continue` is sent only when the server starts reading the body, so a
  16589. // request rejected before that never invites the client to send it. The
  16590. // requests below carry the expectation but withhold the body, as a client
  16591. // waiting for `100 Continue` would.
  16592. // A POST that expects `100 Continue` and withholds its two-byte body.
  16593. static std::string expect_headers_only(const std::string &path) {
  16594. return "POST " + path +
  16595. " HTTP/1.1\r\n"
  16596. "Host: localhost\r\n"
  16597. "Content-Length: 2\r\n"
  16598. "Expect: 100-continue\r\n"
  16599. "\r\n";
  16600. }
  16601. class ExpectLazyContinueTest : public ::testing::Test {
  16602. protected:
  16603. void SetUp() override {
  16604. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16605. if (req.path == "/pre-routing") {
  16606. res.status = StatusCode::Unauthorized_401;
  16607. return Server::HandlerResponse::Handled;
  16608. }
  16609. return Server::HandlerResponse::Unhandled;
  16610. });
  16611. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16612. if (req.matched_route == "/pre-request") {
  16613. res.status = StatusCode::Forbidden_403;
  16614. return Server::HandlerResponse::Handled;
  16615. }
  16616. return Server::HandlerResponse::Unhandled;
  16617. });
  16618. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16619. res.set_content("ok", "text/plain");
  16620. });
  16621. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16622. res.set_content("ok", "text/plain");
  16623. });
  16624. svr_.Post("/reader-used", [](const Request &, Response &res,
  16625. const ContentReader &content_reader) {
  16626. std::string body;
  16627. content_reader([&](const char *data, size_t len) {
  16628. body.append(data, len);
  16629. return true;
  16630. });
  16631. res.set_content(body, "text/plain");
  16632. });
  16633. svr_.Post("/reader-unused",
  16634. [](const Request &, Response &res, const ContentReader &) {
  16635. res.set_content("ignored", "text/plain");
  16636. });
  16637. port_ = svr_.bind_to_any_port(HOST);
  16638. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16639. svr_.wait_until_ready();
  16640. }
  16641. void TearDown() override {
  16642. svr_.stop();
  16643. if (thread_.joinable()) { thread_.join(); }
  16644. }
  16645. // Sends `req` and reads until the server closes the connection. Returns
  16646. // false if the read had to wait for the client-side timeout instead.
  16647. bool send_until_closed(const std::string &req, std::string *resp) const {
  16648. auto start = std::chrono::steady_clock::now();
  16649. if (!send_request(3, req, resp, port_)) { return false; }
  16650. auto elapsed = std::chrono::steady_clock::now() - start;
  16651. return elapsed < std::chrono::seconds(2);
  16652. }
  16653. // The final response comes without `100 Continue`, and the server closes
  16654. // the connection since the body may or may not follow.
  16655. void expect_final_without_interim(const std::string &path,
  16656. const char *status_line) const {
  16657. std::string resp;
  16658. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16659. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16660. EXPECT_EQ(0u, resp.find(status_line));
  16661. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16662. }
  16663. Server svr_;
  16664. int port_ = 0;
  16665. thread thread_;
  16666. };
  16667. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16668. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16669. }
  16670. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16671. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16672. }
  16673. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16674. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16675. }
  16676. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16677. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16678. }
  16679. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16680. // The body follows once `100 Continue` has had time to arrive.
  16681. auto req = expect_headers_only("/reader-used");
  16682. req.insert(req.size() - 2, "Connection: close\r\n");
  16683. std::string resp;
  16684. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16685. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  16686. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  16687. EXPECT_NE(std::string::npos, resp.find("hi"));
  16688. }
  16689. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  16690. // Large enough for the client to add `Expect: 100-continue` itself.
  16691. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  16692. std::atomic<bool> body_sent{false};
  16693. Client cli(HOST, port_);
  16694. auto res = cli.Post(
  16695. "/pre-request", length,
  16696. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  16697. body_sent = true;
  16698. std::string chunk(len, 'x');
  16699. sink.write(chunk.data(), chunk.size());
  16700. return true;
  16701. },
  16702. "application/octet-stream");
  16703. ASSERT_TRUE(res);
  16704. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16705. EXPECT_FALSE(body_sent);
  16706. }
  16707. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16708. Server svr;
  16709. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16710. return StatusCode::ExpectationFailed_417;
  16711. });
  16712. svr.Post("/p", [](const Request &, Response &res) {
  16713. res.set_content("ok", "text/plain");
  16714. });
  16715. auto port = svr.bind_to_any_port(HOST);
  16716. thread t = thread([&] { svr.listen_after_bind(); });
  16717. auto se = detail::scope_exit([&] {
  16718. svr.stop();
  16719. t.join();
  16720. });
  16721. svr.wait_until_ready();
  16722. std::string resp;
  16723. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16724. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16725. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16726. // Exactly one response: the route handler must not run after the 417.
  16727. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16728. }
  16729. #ifndef _WIN32
  16730. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16731. static constexpr char reject[] = "Unauthorized";
  16732. static constexpr char accept[] = "Upload accepted";
  16733. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  16734. Server svr;
  16735. svr.set_expect_100_continue_handler(
  16736. [](const Request & /*req*/, Response &res) {
  16737. res.status = StatusCode::Unauthorized_401;
  16738. res.set_content(reject, "text/plain");
  16739. return res.status;
  16740. });
  16741. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  16742. res.set_content(accept, "text/plain");
  16743. });
  16744. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16745. auto se = detail::scope_exit([&] {
  16746. svr.stop();
  16747. thread.join();
  16748. ASSERT_FALSE(svr.is_running());
  16749. });
  16750. svr.wait_until_ready();
  16751. {
  16752. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  16753. curl_easy_init(), &curl_easy_cleanup};
  16754. ASSERT_NE(curl, nullptr);
  16755. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  16756. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  16757. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  16758. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  16759. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  16760. &curl_slist_free_all};
  16761. ASSERT_NE(list, nullptr);
  16762. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  16763. struct read_data {
  16764. size_t read_size;
  16765. size_t total_size;
  16766. } data = {0, total_size};
  16767. using read_callback_t =
  16768. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16769. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  16770. void *userdata) -> size_t {
  16771. read_data *d = (read_data *)userdata;
  16772. if (!userdata || d->read_size >= d->total_size) { return 0; }
  16773. std::fill_n(ptr, size * nmemb, 'A');
  16774. d->read_size += size * nmemb;
  16775. return size * nmemb;
  16776. };
  16777. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  16778. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  16779. std::vector<char> buffer;
  16780. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  16781. using write_callback_t =
  16782. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16783. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  16784. void *userdata) -> size_t {
  16785. std::vector<char> *buf = (std::vector<char> *)userdata;
  16786. buf->reserve(buf->size() + size * nmemb + 1);
  16787. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  16788. return size * nmemb;
  16789. };
  16790. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  16791. {
  16792. const auto res = curl_easy_perform(curl.get());
  16793. ASSERT_EQ(res, CURLE_OK);
  16794. }
  16795. {
  16796. auto response_code = long{};
  16797. const auto res =
  16798. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  16799. ASSERT_EQ(res, CURLE_OK);
  16800. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  16801. }
  16802. {
  16803. auto dl = curl_off_t{};
  16804. const auto res =
  16805. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  16806. ASSERT_EQ(res, CURLE_OK);
  16807. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  16808. }
  16809. {
  16810. buffer.push_back('\0');
  16811. ASSERT_STRCASEEQ(buffer.data(), reject);
  16812. }
  16813. }
  16814. }
  16815. #endif
  16816. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  16817. // Regression test for #2458.
  16818. //
  16819. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  16820. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  16821. // ticket can make the client socket spuriously readable during the
  16822. // 100-continue wait. If the readiness is mistaken for an incoming response,
  16823. // the client withholds the body and then blocks reading a response that never
  16824. // comes, failing with `Failed to read connection`.
  16825. //
  16826. // A correct client (like curl) sends the body once no `100 Continue` arrives
  16827. // within the timeout. This raw OpenSSL server deliberately never sends
  16828. // `100 Continue`; the client must still deliver the body and receive 200.
  16829. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  16830. signal(SIGPIPE, SIG_IGN);
  16831. const auto port = PORT + 4;
  16832. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16833. ASSERT_NE(srv, INVALID_SOCKET);
  16834. int opt = 1;
  16835. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  16836. sockaddr_in addr{};
  16837. addr.sin_family = AF_INET;
  16838. addr.sin_port = htons(static_cast<uint16_t>(port));
  16839. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16840. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16841. ASSERT_EQ(0, ::listen(srv, 1));
  16842. std::atomic<size_t> server_body_bytes{0};
  16843. auto server_thread = std::thread([&] {
  16844. sockaddr_in cli_addr{};
  16845. socklen_t cli_len = sizeof(cli_addr);
  16846. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16847. if (cli == INVALID_SOCKET) { return; }
  16848. // Bound the lifetime of the server side so a buggy client (which never
  16849. // sends the body) cannot make this thread block forever on join.
  16850. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  16851. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16852. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  16853. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  16854. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  16855. SSL *ssl = SSL_new(ctx);
  16856. SSL_set_fd(ssl, static_cast<int>(cli));
  16857. if (SSL_accept(ssl) > 0) {
  16858. // Read the request headers. Reading here also flushes the TLS 1.3
  16859. // session tickets to the client. Deliberately do NOT send
  16860. // `100 Continue`.
  16861. std::string buf;
  16862. char tmp[1024];
  16863. while (buf.find("\r\n\r\n") == std::string::npos) {
  16864. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16865. if (n <= 0) { break; }
  16866. buf.append(tmp, static_cast<size_t>(n));
  16867. }
  16868. // A correct client sends the body now; count what arrives.
  16869. auto pos = buf.find("\r\n\r\n");
  16870. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  16871. while (body < 4096) {
  16872. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16873. if (n <= 0) { break; }
  16874. body += static_cast<size_t>(n);
  16875. }
  16876. server_body_bytes = body;
  16877. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  16878. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  16879. SSL_shutdown(ssl);
  16880. }
  16881. SSL_free(ssl);
  16882. detail::close_socket(cli);
  16883. SSL_CTX_free(ctx);
  16884. });
  16885. auto se = detail::scope_exit([&] {
  16886. server_thread.join();
  16887. detail::close_socket(srv);
  16888. });
  16889. SSLClient cli("127.0.0.1", port);
  16890. cli.enable_server_certificate_verification(false);
  16891. cli.set_connection_timeout(5, 0);
  16892. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  16893. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  16894. std::string body(4096, 'A');
  16895. auto res = cli.Put("/api/test", body, "application/json");
  16896. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  16897. EXPECT_EQ(StatusCode::OK_200, res->status);
  16898. EXPECT_EQ(body.size(), server_body_bytes.load());
  16899. }
  16900. #endif
  16901. template <typename S, typename C>
  16902. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  16903. svr.Get("/stream", [&](const Request &, Response &res) {
  16904. auto data = new std::string("01234567890123456789");
  16905. res.set_content_provider(
  16906. data->size(), "text/plain",
  16907. [&, data](size_t offset, size_t length, DataSink &sink) {
  16908. const size_t DATA_CHUNK_SIZE = 4;
  16909. const auto &d = *data;
  16910. std::this_thread::sleep_for(std::chrono::seconds(1));
  16911. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  16912. return true;
  16913. },
  16914. [data](bool success) {
  16915. EXPECT_FALSE(success);
  16916. delete data;
  16917. });
  16918. });
  16919. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  16920. auto i = new size_t(0);
  16921. res.set_content_provider(
  16922. "text/plain",
  16923. [i](size_t, DataSink &sink) {
  16924. if (*i < 5) {
  16925. std::this_thread::sleep_for(std::chrono::seconds(1));
  16926. sink.write("abcd", 4);
  16927. (*i)++;
  16928. } else {
  16929. sink.done();
  16930. }
  16931. return true;
  16932. },
  16933. [i](bool success) {
  16934. EXPECT_FALSE(success);
  16935. delete i;
  16936. });
  16937. });
  16938. svr.Get("/chunked", [&](const Request &, Response &res) {
  16939. auto i = new size_t(0);
  16940. res.set_chunked_content_provider(
  16941. "text/plain",
  16942. [i](size_t, DataSink &sink) {
  16943. if (*i < 5) {
  16944. std::this_thread::sleep_for(std::chrono::seconds(1));
  16945. sink.os << "abcd";
  16946. (*i)++;
  16947. } else {
  16948. sink.done();
  16949. }
  16950. return true;
  16951. },
  16952. [i](bool success) {
  16953. EXPECT_FALSE(success);
  16954. delete i;
  16955. });
  16956. });
  16957. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16958. auto se = detail::scope_exit([&] {
  16959. svr.stop();
  16960. listen_thread.join();
  16961. ASSERT_FALSE(svr.is_running());
  16962. });
  16963. svr.wait_until_ready();
  16964. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  16965. {
  16966. auto start = std::chrono::steady_clock::now();
  16967. auto res = cli.Get("/stream");
  16968. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16969. std::chrono::steady_clock::now() - start)
  16970. .count();
  16971. ASSERT_FALSE(res);
  16972. EXPECT_EQ(Error::Read, res.error());
  16973. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16974. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16975. }
  16976. {
  16977. auto start = std::chrono::steady_clock::now();
  16978. auto res = cli.Get("/stream_without_length");
  16979. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16980. std::chrono::steady_clock::now() - start)
  16981. .count();
  16982. ASSERT_FALSE(res);
  16983. EXPECT_EQ(Error::Read, res.error());
  16984. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16985. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16986. }
  16987. {
  16988. auto start = std::chrono::steady_clock::now();
  16989. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  16990. EXPECT_EQ("abcd", string(data, data_length));
  16991. return true;
  16992. });
  16993. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16994. std::chrono::steady_clock::now() - start)
  16995. .count();
  16996. ASSERT_FALSE(res);
  16997. EXPECT_EQ(Error::Read, res.error());
  16998. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16999. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17000. }
  17001. }
  17002. TEST(MaxTimeoutTest, ContentStream) {
  17003. time_t timeout = 2000;
  17004. time_t threshold = 200;
  17005. Server svr;
  17006. Client cli("localhost", PORT);
  17007. max_timeout_test(svr, cli, timeout, threshold);
  17008. }
  17009. #ifdef CPPHTTPLIB_SSL_ENABLED
  17010. TEST(MaxTimeoutTest, ContentStreamSSL) {
  17011. time_t timeout = 2000;
  17012. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  17013. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17014. SSLClient cli("localhost", PORT);
  17015. cli.enable_server_certificate_verification(false);
  17016. max_timeout_test(svr, cli, timeout, threshold);
  17017. }
  17018. #endif
  17019. class EventDispatcher {
  17020. public:
  17021. EventDispatcher() {}
  17022. bool wait_event(DataSink *sink) {
  17023. unique_lock<mutex> lk(m_);
  17024. int id = id_;
  17025. // Wait with timeout to prevent hanging if client disconnects
  17026. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17027. [&] { return cid_ == id; })) {
  17028. return false; // Timeout occurred
  17029. }
  17030. sink->write(message_.data(), message_.size());
  17031. return true;
  17032. }
  17033. void send_event(const string &message) {
  17034. lock_guard<mutex> lk(m_);
  17035. cid_ = id_++;
  17036. message_ = message;
  17037. cv_.notify_all();
  17038. }
  17039. private:
  17040. mutex m_;
  17041. condition_variable cv_;
  17042. atomic_int id_{0};
  17043. atomic_int cid_{-1};
  17044. string message_;
  17045. };
  17046. TEST(ClientInThreadTest, Issue2068) {
  17047. EventDispatcher ed;
  17048. Server svr;
  17049. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17050. res.set_chunked_content_provider("text/event-stream",
  17051. [&](size_t /*offset*/, DataSink &sink) {
  17052. return ed.wait_event(&sink);
  17053. });
  17054. });
  17055. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17056. svr.wait_until_ready();
  17057. thread event_thread([&] {
  17058. int id = 0;
  17059. while (svr.is_running()) {
  17060. this_thread::sleep_for(chrono::milliseconds(500));
  17061. std::stringstream ss;
  17062. ss << "data: " << id << "\n\n";
  17063. ed.send_event(ss.str());
  17064. id++;
  17065. }
  17066. });
  17067. auto se = detail::scope_exit([&] {
  17068. svr.stop();
  17069. listen_thread.join();
  17070. event_thread.join();
  17071. ASSERT_FALSE(svr.is_running());
  17072. });
  17073. {
  17074. auto client = detail::make_unique<Client>(HOST, PORT);
  17075. client->set_read_timeout(std::chrono::minutes(10));
  17076. std::atomic<bool> stop{false};
  17077. std::thread t([&] {
  17078. client->Get("/event1",
  17079. [&](const char *, size_t) -> bool { return !stop; });
  17080. });
  17081. std::this_thread::sleep_for(std::chrono::seconds(2));
  17082. stop = true;
  17083. client->stop();
  17084. t.join();
  17085. // Reset client after thread has finished
  17086. client.reset();
  17087. }
  17088. }
  17089. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17090. auto handled = false;
  17091. Server svr;
  17092. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17093. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17094. auto se = detail::scope_exit([&] {
  17095. svr.stop();
  17096. t.join();
  17097. ASSERT_FALSE(svr.is_running());
  17098. ASSERT_FALSE(handled);
  17099. });
  17100. svr.wait_until_ready();
  17101. // Two Content-Length headers with different values — must be rejected
  17102. auto req = "POST /test HTTP/1.1\r\n"
  17103. "Content-Length: 5\r\n"
  17104. "Content-Length: 10\r\n"
  17105. "\r\n"
  17106. "hello";
  17107. std::string response;
  17108. ASSERT_TRUE(send_request(1, req, &response));
  17109. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17110. response.substr(0, response.find("\r\n")));
  17111. }
  17112. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17113. auto handled = false;
  17114. Server svr;
  17115. svr.Post("/test", [&](const Request &, Response &res) {
  17116. handled = true;
  17117. res.set_content("ok", "text/plain");
  17118. });
  17119. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17120. auto se = detail::scope_exit([&] {
  17121. svr.stop();
  17122. t.join();
  17123. ASSERT_FALSE(svr.is_running());
  17124. ASSERT_TRUE(handled);
  17125. });
  17126. svr.wait_until_ready();
  17127. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17128. auto req = "POST /test HTTP/1.1\r\n"
  17129. "Content-Length: 5\r\n"
  17130. "Content-Length: 5\r\n"
  17131. "\r\n"
  17132. "hello";
  17133. std::string response;
  17134. ASSERT_TRUE(send_request(1, req, &response));
  17135. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17136. }
  17137. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17138. Server svr;
  17139. svr.Get("/test", [](const Request &, Response &res) {
  17140. res.set_content("ok", "text/plain");
  17141. });
  17142. auto port = svr.bind_to_any_port(HOST);
  17143. thread t = thread([&] { svr.listen_after_bind(); });
  17144. auto se = detail::scope_exit([&] {
  17145. svr.stop();
  17146. t.join();
  17147. ASSERT_FALSE(svr.is_running());
  17148. });
  17149. svr.wait_until_ready();
  17150. auto status_line = [&](const std::string &host_lines) {
  17151. std::string res;
  17152. send_request(
  17153. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17154. &res, port);
  17155. return res.substr(0, res.find("\r\n"));
  17156. };
  17157. const char *accepted[] = {
  17158. "Host: localhost\r\n",
  17159. "Host: a.example:8080\r\n",
  17160. "Host: my_service\r\n",
  17161. "Host: [::1]:8080\r\n",
  17162. "Host: [fe80::1%25eth0]\r\n",
  17163. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17164. };
  17165. for (auto host_lines : accepted) {
  17166. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17167. }
  17168. const char *rejected[] = {
  17169. "Host: a.example\r\nHost: b.example\r\n",
  17170. "Host: a.example\r\nHost: a.example\r\n",
  17171. "Host: a@b.example\r\n",
  17172. "Host: a.example/b\r\n",
  17173. "Host: a.example\\b\r\n",
  17174. "Host: a.example?b\r\n",
  17175. "Host: a.example#b\r\n",
  17176. "Host: a.example b.example\r\n",
  17177. };
  17178. for (auto host_lines : rejected) {
  17179. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17180. << host_lines;
  17181. }
  17182. }
  17183. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17184. Server svr;
  17185. svr.Get("/", [](const Request &req, Response &res) {
  17186. EXPECT_EQ(2U, req.trailers.size());
  17187. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17188. // Denied
  17189. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17190. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17191. // Accepted
  17192. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17193. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17194. EXPECT_TRUE(req.has_trailer("X-World"));
  17195. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17196. res.set_content("ok", "text/plain");
  17197. });
  17198. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17199. auto se = detail::scope_exit([&] {
  17200. svr.stop();
  17201. t.join();
  17202. ASSERT_FALSE(svr.is_running());
  17203. });
  17204. svr.wait_until_ready();
  17205. const std::string req = "GET / HTTP/1.1\r\n"
  17206. "Transfer-Encoding: chunked\r\n"
  17207. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17208. "\r\n"
  17209. "0\r\n"
  17210. "Content-Length: 10\r\n"
  17211. "Host: internal.local\r\n"
  17212. "Content-Type: malicious/content\r\n"
  17213. "Cookie: any\r\n"
  17214. "Set-Cookie: any\r\n"
  17215. "X-Forwarded-For: attacker.com\r\n"
  17216. "X-Real-Ip: 1.1.1.1\r\n"
  17217. "X-Hello: hello\r\n"
  17218. "X-World: world\r\n"
  17219. "\r\n";
  17220. std::string res;
  17221. ASSERT_TRUE(send_request(1, req, &res));
  17222. }
  17223. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17224. // several field lines, and the combined value is what has to be parsed. A
  17225. // Trailer field split across lines therefore declares every name it lists;
  17226. // reading only the first line silently drops the trailers the later lines
  17227. // declare. The prohibited-trailer filter still applies to every line.
  17228. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17229. Server svr;
  17230. size_t observed_trailer_count = 0;
  17231. std::string observed_hello;
  17232. std::string observed_world;
  17233. bool observed_content_length = true;
  17234. svr.Get("/", [&](const Request &req, Response &res) {
  17235. observed_trailer_count = req.trailers.size();
  17236. observed_hello = req.get_trailer_value("X-Hello");
  17237. observed_world = req.get_trailer_value("X-World");
  17238. observed_content_length = req.has_trailer("Content-Length");
  17239. res.set_content("ok", "text/plain");
  17240. });
  17241. auto port = svr.bind_to_any_port(HOST);
  17242. thread t = thread([&]() { svr.listen_after_bind(); });
  17243. auto se = detail::scope_exit([&] {
  17244. svr.stop();
  17245. t.join();
  17246. ASSERT_FALSE(svr.is_running());
  17247. });
  17248. svr.wait_until_ready();
  17249. const std::string req = "GET / HTTP/1.1\r\n"
  17250. "Transfer-Encoding: chunked\r\n"
  17251. "Trailer: X-Hello\r\n"
  17252. "Trailer: X-World, Content-Length\r\n"
  17253. "\r\n"
  17254. "0\r\n"
  17255. "X-Hello: hello\r\n"
  17256. "X-World: world\r\n"
  17257. "Content-Length: 10\r\n"
  17258. "\r\n";
  17259. std::string res;
  17260. ASSERT_TRUE(send_request(1, req, &res, port));
  17261. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17262. // Accepted: both field lines contribute to the declared set
  17263. EXPECT_EQ(2U, observed_trailer_count);
  17264. EXPECT_EQ(observed_hello, "hello");
  17265. EXPECT_EQ(observed_world, "world");
  17266. // Denied: a prohibited name stays prohibited on a later field line
  17267. EXPECT_FALSE(observed_content_length);
  17268. }
  17269. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17270. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17271. // unbounded run of fields that are never declared, because the counter would
  17272. // only advance for declared fields.
  17273. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17274. Server svr;
  17275. bool handler_called = false;
  17276. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17277. handler_called = true;
  17278. res.set_content("ok", "text/plain");
  17279. });
  17280. auto port = svr.bind_to_any_port(HOST);
  17281. thread t = thread([&]() { svr.listen_after_bind(); });
  17282. auto se = detail::scope_exit([&] {
  17283. svr.stop();
  17284. t.join();
  17285. ASSERT_FALSE(svr.is_running());
  17286. });
  17287. svr.wait_until_ready();
  17288. // Declare nothing, then send far more undeclared trailer fields than the
  17289. // header-count limit. Parsing must stop and reject the request rather than
  17290. // read every line.
  17291. std::string req = "GET / HTTP/1.1\r\n"
  17292. "Transfer-Encoding: chunked\r\n"
  17293. "\r\n"
  17294. "0\r\n";
  17295. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17296. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17297. }
  17298. req += "\r\n";
  17299. std::string res;
  17300. ASSERT_TRUE(send_request(1, req, &res, port));
  17301. // The request is rejected before the handler runs.
  17302. EXPECT_FALSE(handler_called);
  17303. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17304. }
  17305. // The set of declared trailer names is capped so a peer cannot grow it without
  17306. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17307. // declared past the cap is not honored, even if the field is actually sent.
  17308. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17309. Server svr;
  17310. // One name inside the cap and one past it, so the test tracks the cap rather
  17311. // than a fixed count.
  17312. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17313. const std::string within_cap_name = "X-T-0";
  17314. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17315. bool observed_within_cap = false;
  17316. bool observed_past_cap = false;
  17317. svr.Get("/", [&](const Request &req, Response &res) {
  17318. observed_within_cap = req.has_trailer(within_cap_name);
  17319. observed_past_cap = req.has_trailer(past_cap_name);
  17320. res.set_content("ok", "text/plain");
  17321. });
  17322. auto port = svr.bind_to_any_port(HOST);
  17323. thread t = thread([&]() { svr.listen_after_bind(); });
  17324. auto se = detail::scope_exit([&] {
  17325. svr.stop();
  17326. t.join();
  17327. ASSERT_FALSE(svr.is_running());
  17328. });
  17329. svr.wait_until_ready();
  17330. // Declare more trailer names than the cap in a single Trailer field, then
  17331. // actually send the first (within the cap) and the last (past it).
  17332. std::string trailer_decl = "Trailer: ";
  17333. for (int i = 0; i < declared_count; i++) {
  17334. if (i != 0) { trailer_decl += ", "; }
  17335. trailer_decl += "X-T-" + std::to_string(i);
  17336. }
  17337. trailer_decl += "\r\n";
  17338. const std::string req = "GET / HTTP/1.1\r\n"
  17339. "Transfer-Encoding: chunked\r\n" +
  17340. trailer_decl +
  17341. "\r\n"
  17342. "0\r\n" +
  17343. within_cap_name + ": a\r\n" + past_cap_name +
  17344. ": b\r\n"
  17345. "\r\n";
  17346. std::string res;
  17347. ASSERT_TRUE(send_request(1, req, &res, port));
  17348. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17349. // A name within the cap is honored; one declared past the cap is dropped.
  17350. EXPECT_TRUE(observed_within_cap);
  17351. EXPECT_FALSE(observed_past_cap);
  17352. }
  17353. // A direct client that is not listed in trusted_proxies must not be able to
  17354. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17355. // the peer address on the actual TCP connection determines whether the
  17356. // header is honored.
  17357. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17358. Server svr;
  17359. // Deliberately does NOT include the loopback address the test client
  17360. // actually connects from, so the direct connection is not a trusted proxy.
  17361. svr.set_trusted_proxies({"203.0.113.66"});
  17362. std::string observed_remote_addr;
  17363. svr.Get("/ip", [&](const Request &req, Response &res) {
  17364. observed_remote_addr = req.remote_addr;
  17365. res.set_content("ok", "text/plain");
  17366. });
  17367. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17368. auto se = detail::scope_exit([&] {
  17369. svr.stop();
  17370. t.join();
  17371. ASSERT_FALSE(svr.is_running());
  17372. });
  17373. svr.wait_until_ready();
  17374. Client cli(HOST, PORT);
  17375. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17377. EXPECT_EQ(StatusCode::OK_200, res->status);
  17378. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17379. // ignored entirely and the real connection-level address retained.
  17380. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17381. observed_remote_addr == "127.0.0.1");
  17382. }
  17383. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17384. Server svr;
  17385. std::string observed_remote_addr;
  17386. std::string observed_xff;
  17387. svr.Get("/ip", [&](const Request &req, Response &res) {
  17388. observed_remote_addr = req.remote_addr;
  17389. observed_xff = req.get_header_value("X-Forwarded-For");
  17390. res.set_content("ok", "text/plain");
  17391. });
  17392. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17393. auto se = detail::scope_exit([&] {
  17394. svr.stop();
  17395. t.join();
  17396. ASSERT_FALSE(svr.is_running());
  17397. });
  17398. svr.wait_until_ready();
  17399. Client cli(HOST, PORT);
  17400. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17402. EXPECT_EQ(StatusCode::OK_200, res->status);
  17403. EXPECT_EQ(observed_xff, "203.0.113.66");
  17404. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17405. observed_remote_addr == "127.0.0.1");
  17406. }
  17407. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17408. Server svr;
  17409. svr.set_trusted_proxies({"203.0.113.66"});
  17410. std::string observed_remote_addr;
  17411. std::string observed_xff;
  17412. svr.Get("/ip", [&](const Request &req, Response &res) {
  17413. observed_remote_addr = req.remote_addr;
  17414. observed_xff = req.get_header_value("X-Forwarded-For");
  17415. res.set_content("ok", "text/plain");
  17416. });
  17417. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17418. auto se = detail::scope_exit([&] {
  17419. svr.stop();
  17420. t.join();
  17421. ASSERT_FALSE(svr.is_running());
  17422. });
  17423. svr.wait_until_ready();
  17424. Client cli(HOST, PORT);
  17425. auto res = cli.Get("/ip");
  17426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17427. EXPECT_EQ(StatusCode::OK_200, res->status);
  17428. EXPECT_EQ(observed_xff, "");
  17429. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17430. observed_remote_addr == "127.0.0.1");
  17431. }
  17432. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17433. Server svr;
  17434. // Include the loopback address the test client actually connects from, so
  17435. // the direct connection itself is recognized as the trusted proxy hop.
  17436. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17437. std::string observed_remote_addr;
  17438. std::string observed_xff;
  17439. svr.Get("/ip", [&](const Request &req, Response &res) {
  17440. observed_remote_addr = req.remote_addr;
  17441. observed_xff = req.get_header_value("X-Forwarded-For");
  17442. res.set_content("ok", "text/plain");
  17443. });
  17444. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17445. auto se = detail::scope_exit([&] {
  17446. svr.stop();
  17447. t.join();
  17448. ASSERT_FALSE(svr.is_running());
  17449. });
  17450. svr.wait_until_ready();
  17451. Client cli(HOST, PORT);
  17452. auto res = cli.Get(
  17453. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17455. EXPECT_EQ(StatusCode::OK_200, res->status);
  17456. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17457. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17458. }
  17459. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17460. Server svr;
  17461. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17462. std::string observed_remote_addr;
  17463. std::string observed_xff;
  17464. svr.Get("/ip", [&](const Request &req, Response &res) {
  17465. observed_remote_addr = req.remote_addr;
  17466. observed_xff = req.get_header_value("X-Forwarded-For");
  17467. res.set_content("ok", "text/plain");
  17468. });
  17469. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17470. auto se = detail::scope_exit([&] {
  17471. svr.stop();
  17472. t.join();
  17473. ASSERT_FALSE(svr.is_running());
  17474. });
  17475. svr.wait_until_ready();
  17476. Client cli(HOST, PORT);
  17477. auto res = cli.Get(
  17478. "/ip",
  17479. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17481. EXPECT_EQ(StatusCode::OK_200, res->status);
  17482. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17483. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17484. }
  17485. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17486. Server svr;
  17487. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17488. std::string observed_remote_addr;
  17489. std::string observed_xff;
  17490. svr.Get("/ip", [&](const Request &req, Response &res) {
  17491. observed_remote_addr = req.remote_addr;
  17492. observed_xff = req.get_header_value("X-Forwarded-For");
  17493. res.set_content("ok", "text/plain");
  17494. });
  17495. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17496. auto se = detail::scope_exit([&] {
  17497. svr.stop();
  17498. t.join();
  17499. ASSERT_FALSE(svr.is_running());
  17500. });
  17501. svr.wait_until_ready();
  17502. Client cli(HOST, PORT);
  17503. auto res = cli.Get(
  17504. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17506. EXPECT_EQ(StatusCode::OK_200, res->status);
  17507. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17508. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17509. // and must not be selected.
  17510. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17511. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17512. }
  17513. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17514. Server svr;
  17515. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17516. std::string observed_remote_addr;
  17517. svr.Get("/ip", [&](const Request &req, Response &res) {
  17518. observed_remote_addr = req.remote_addr;
  17519. res.set_content("ok", "text/plain");
  17520. });
  17521. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17522. auto se = detail::scope_exit([&] {
  17523. svr.stop();
  17524. t.join();
  17525. ASSERT_FALSE(svr.is_running());
  17526. });
  17527. svr.wait_until_ready();
  17528. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17529. // a forged address and the trusted proxy's own address; the forged value must
  17530. // not win over the address the trusted proxy actually recorded.
  17531. Client cli(HOST, PORT);
  17532. auto res = cli.Get(
  17533. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17535. EXPECT_EQ(StatusCode::OK_200, res->status);
  17536. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17537. }
  17538. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17539. Server svr;
  17540. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17541. std::string observed_remote_addr;
  17542. std::string observed_xff;
  17543. svr.Get("/ip", [&](const Request &req, Response &res) {
  17544. observed_remote_addr = req.remote_addr;
  17545. observed_xff = req.get_header_value("X-Forwarded-For");
  17546. res.set_content("ok", "text/plain");
  17547. });
  17548. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17549. auto se = detail::scope_exit([&] {
  17550. svr.stop();
  17551. t.join();
  17552. ASSERT_FALSE(svr.is_running());
  17553. });
  17554. svr.wait_until_ready();
  17555. Client cli(HOST, PORT);
  17556. auto res = cli.Get(
  17557. "/ip",
  17558. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17560. EXPECT_EQ(StatusCode::OK_200, res->status);
  17561. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17562. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17563. }
  17564. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17565. Server svr;
  17566. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17567. std::string observed_remote_addr;
  17568. std::string observed_xff;
  17569. svr.Get("/ip", [&](const Request &req, Response &res) {
  17570. observed_remote_addr = req.remote_addr;
  17571. observed_xff = req.get_header_value("X-Forwarded-For");
  17572. res.set_content("ok", "text/plain");
  17573. });
  17574. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17575. auto se = detail::scope_exit([&] {
  17576. svr.stop();
  17577. t.join();
  17578. ASSERT_FALSE(svr.is_running());
  17579. });
  17580. svr.wait_until_ready();
  17581. std::string raw_req =
  17582. "GET /ip HTTP/1.1\r\n"
  17583. "Host: localhost\r\n"
  17584. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17585. "Connection: close\r\n"
  17586. "\r\n";
  17587. std::string out;
  17588. ASSERT_TRUE(send_request(5, raw_req, &out));
  17589. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17590. // Header parser trims surrounding whitespace of the header value
  17591. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17592. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17593. }
  17594. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17595. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17596. // their own X-Forwarded-For as a separate field line rather than extending the
  17597. // one the client sent, so every occurrence has to be taken into account.
  17598. // Reading only the first one hands back the address the client chose.
  17599. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17600. Server svr;
  17601. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17602. std::string observed_remote_addr;
  17603. size_t observed_xff_count = 0;
  17604. svr.Get("/ip", [&](const Request &req, Response &res) {
  17605. observed_remote_addr = req.remote_addr;
  17606. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17607. res.set_content("ok", "text/plain");
  17608. });
  17609. auto port = svr.bind_to_any_port(HOST);
  17610. thread t = thread([&]() { svr.listen_after_bind(); });
  17611. auto se = detail::scope_exit([&] {
  17612. svr.stop();
  17613. t.join();
  17614. ASSERT_FALSE(svr.is_running());
  17615. });
  17616. svr.wait_until_ready();
  17617. // The client supplies the first field line; the trusted proxy appends the
  17618. // address it observed as a second one.
  17619. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17620. "Host: localhost\r\n"
  17621. "X-Forwarded-For: 1.2.3.4\r\n"
  17622. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17623. "Connection: close\r\n"
  17624. "\r\n";
  17625. std::string out;
  17626. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17627. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17628. EXPECT_EQ(observed_xff_count, 2U);
  17629. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17630. // The same chain spread over one field line per hop derives the same client
  17631. // address, i.e. the split and the comma-joined representations agree.
  17632. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17633. "Host: localhost\r\n"
  17634. "X-Forwarded-For: 1.2.3.4\r\n"
  17635. "X-Forwarded-For: 198.51.100.23\r\n"
  17636. "X-Forwarded-For: 192.0.2.45\r\n"
  17637. "Connection: close\r\n"
  17638. "\r\n";
  17639. out.clear();
  17640. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17641. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17642. EXPECT_EQ(observed_xff_count, 3U);
  17643. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17644. }
  17645. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17646. // crash the server (it used to call front() on an empty vector inside
  17647. // get_client_ip). The connection-level remote address must be retained instead.
  17648. static void run_malformed_xff_test(const std::string &xff_value) {
  17649. Server svr;
  17650. svr.set_trusted_proxies({"192.0.2.45"});
  17651. std::string observed_remote_addr;
  17652. svr.Get("/ip", [&](const Request &req, Response &res) {
  17653. observed_remote_addr = req.remote_addr;
  17654. res.set_content("ok", "text/plain");
  17655. });
  17656. int port = 0;
  17657. thread t = thread([&]() {
  17658. port = svr.bind_to_any_port(HOST);
  17659. svr.listen_after_bind();
  17660. });
  17661. auto se = detail::scope_exit([&] {
  17662. svr.stop();
  17663. t.join();
  17664. ASSERT_FALSE(svr.is_running());
  17665. });
  17666. svr.wait_until_ready();
  17667. Client cli(HOST, port);
  17668. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17670. EXPECT_EQ(StatusCode::OK_200, res->status);
  17671. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17672. observed_remote_addr == "127.0.0.1");
  17673. }
  17674. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  17675. run_malformed_xff_test("");
  17676. }
  17677. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  17678. run_malformed_xff_test(",");
  17679. }
  17680. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  17681. run_malformed_xff_test(", , ,");
  17682. }
  17683. // The same rule applies to Accept: a request whose acceptable types are spread
  17684. // over several field lines must be negotiated against all of them.
  17685. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  17686. // case-insensitive connection options. Comparing the whole field value against
  17687. // one option misses a client that sends several of them, and misses every
  17688. // casing but the one written in the comparison.
  17689. //
  17690. // Sends req, reads the response, then reuses the same socket for a second
  17691. // request to find out whether the server kept the connection.
  17692. static void probe_connection_reuse(int port, const std::string &req,
  17693. bool *announced_close, bool *reusable) {
  17694. auto error = Error::Success;
  17695. auto sock = detail::create_client_socket(
  17696. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17697. /*connection_timeout_sec=*/5, 0,
  17698. /*read_timeout_sec=*/1, 0,
  17699. /*write_timeout_sec=*/5, 0, std::string(), error);
  17700. ASSERT_NE(sock, INVALID_SOCKET);
  17701. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  17702. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  17703. "Host: localhost\r\n"
  17704. "Connection: close\r\n"
  17705. "\r\n";
  17706. std::string first_response;
  17707. std::string second_response;
  17708. detail::process_client_socket(
  17709. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  17710. [&](Stream &strm) {
  17711. if (strm.write(req.data(), req.size()) !=
  17712. static_cast<ssize_t>(req.size())) {
  17713. return false;
  17714. }
  17715. char buf[512];
  17716. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  17717. // Headers plus the two-byte body of the handler below
  17718. while (reader.getline()) {
  17719. first_response += reader.ptr();
  17720. if (first_response.find("ok") != std::string::npos) { break; }
  17721. }
  17722. if (strm.write(second.data(), second.size()) !=
  17723. static_cast<ssize_t>(second.size())) {
  17724. return true;
  17725. }
  17726. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  17727. while (reader2.getline()) {
  17728. second_response += reader2.ptr();
  17729. if (second_response.find("ok") != std::string::npos) { break; }
  17730. }
  17731. return true;
  17732. });
  17733. *announced_close =
  17734. first_response.find("Connection: close") != std::string::npos;
  17735. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  17736. }
  17737. class ConnectionTokenTest : public ::testing::Test {
  17738. protected:
  17739. void SetUp() override {
  17740. svr_.Get("/keepalive", [](const Request &, Response &res) {
  17741. res.set_content("ok", "text/plain");
  17742. });
  17743. port_ = svr_.bind_to_any_port(HOST);
  17744. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17745. svr_.wait_until_ready();
  17746. }
  17747. void TearDown() override {
  17748. svr_.stop();
  17749. if (thread_.joinable()) { thread_.join(); }
  17750. }
  17751. Server svr_;
  17752. int port_ = 0;
  17753. thread thread_;
  17754. };
  17755. // "close" alongside another option still closes the connection, and the
  17756. // response says so rather than leaving the peer to discover it.
  17757. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  17758. bool announced_close = false;
  17759. bool reusable = true;
  17760. probe_connection_reuse(port_,
  17761. "GET /keepalive HTTP/1.1\r\n"
  17762. "Host: localhost\r\n"
  17763. "Connection: keep-alive, close\r\n"
  17764. "\r\n",
  17765. &announced_close, &reusable);
  17766. EXPECT_TRUE(announced_close);
  17767. EXPECT_FALSE(reusable);
  17768. }
  17769. // "close" split over two field lines is the same list, so it is honored too.
  17770. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  17771. bool announced_close = false;
  17772. bool reusable = true;
  17773. probe_connection_reuse(port_,
  17774. "GET /keepalive HTTP/1.1\r\n"
  17775. "Host: localhost\r\n"
  17776. "Connection: keep-alive\r\n"
  17777. "Connection: close\r\n"
  17778. "\r\n",
  17779. &announced_close, &reusable);
  17780. EXPECT_TRUE(announced_close);
  17781. EXPECT_FALSE(reusable);
  17782. }
  17783. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  17784. // keep-alive in the spelling everyone actually sends keeps its connection.
  17785. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  17786. bool announced_close = false;
  17787. bool reusable = false;
  17788. probe_connection_reuse(port_,
  17789. "GET /keepalive HTTP/1.0\r\n"
  17790. "Host: localhost\r\n"
  17791. "Connection: keep-alive\r\n"
  17792. "\r\n",
  17793. &announced_close, &reusable);
  17794. EXPECT_FALSE(announced_close);
  17795. EXPECT_TRUE(reusable);
  17796. }
  17797. // A token the value merely contains is not the token itself.
  17798. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  17799. bool announced_close = false;
  17800. bool reusable = false;
  17801. probe_connection_reuse(port_,
  17802. "GET /keepalive HTTP/1.1\r\n"
  17803. "Host: localhost\r\n"
  17804. "Connection: notclose\r\n"
  17805. "\r\n",
  17806. &announced_close, &reusable);
  17807. EXPECT_FALSE(announced_close);
  17808. EXPECT_TRUE(reusable);
  17809. }
  17810. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  17811. Server svr;
  17812. std::vector<std::string> observed_types;
  17813. svr.Get("/", [&](const Request &req, Response &res) {
  17814. observed_types = req.accept_content_types;
  17815. res.set_content("ok", "text/plain");
  17816. });
  17817. auto port = svr.bind_to_any_port(HOST);
  17818. thread t = thread([&]() { svr.listen_after_bind(); });
  17819. auto se = detail::scope_exit([&] {
  17820. svr.stop();
  17821. t.join();
  17822. ASSERT_FALSE(svr.is_running());
  17823. });
  17824. svr.wait_until_ready();
  17825. Client cli(HOST, port);
  17826. Headers headers;
  17827. headers.emplace("Accept", "text/plain;q=0.5");
  17828. headers.emplace("Accept", "application/json");
  17829. auto res = cli.Get("/", headers);
  17830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17831. EXPECT_EQ(StatusCode::OK_200, res->status);
  17832. // Sorted by q-value, so the second field line's type comes first
  17833. ASSERT_EQ(2U, observed_types.size());
  17834. EXPECT_EQ("application/json", observed_types[0]);
  17835. EXPECT_EQ("text/plain", observed_types[1]);
  17836. }
  17837. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  17838. // empty field line must not contribute a bare comma to the combined value.
  17839. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  17840. Server svr;
  17841. std::vector<std::string> observed_types;
  17842. svr.Get("/", [&](const Request &req, Response &res) {
  17843. observed_types = req.accept_content_types;
  17844. res.set_content("ok", "text/plain");
  17845. });
  17846. auto port = svr.bind_to_any_port(HOST);
  17847. thread t = thread([&]() { svr.listen_after_bind(); });
  17848. auto se = detail::scope_exit([&] {
  17849. svr.stop();
  17850. t.join();
  17851. ASSERT_FALSE(svr.is_running());
  17852. });
  17853. svr.wait_until_ready();
  17854. // Empty first field line, then a real one
  17855. std::string raw_req = "GET / HTTP/1.1\r\n"
  17856. "Host: localhost\r\n"
  17857. "Accept:\r\n"
  17858. "Accept: application/json\r\n"
  17859. "Connection: close\r\n"
  17860. "\r\n";
  17861. std::string out;
  17862. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17863. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17864. ASSERT_EQ(1U, observed_types.size());
  17865. EXPECT_EQ("application/json", observed_types[0]);
  17866. }
  17867. // The skip in get_combined_header_value() is what keeps an empty field line
  17868. // from contributing a bare comma. Only a trailing empty field line exercises
  17869. // it: a leading one is already covered by the "combined is still empty" check,
  17870. // and parse_accept_header() now ignores the empty element either way, so the
  17871. // request-level test above can no longer tell the two apart.
  17872. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  17873. Headers headers;
  17874. headers.emplace("Accept", "text/html");
  17875. headers.emplace("Accept", "");
  17876. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  17877. headers.clear();
  17878. headers.emplace("Accept", "");
  17879. headers.emplace("Accept", "application/json");
  17880. EXPECT_EQ("application/json",
  17881. detail::get_combined_header_value(headers, "Accept"));
  17882. }
  17883. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17884. // An encoding offered on a later Accept-Encoding field line is still offered.
  17885. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  17886. Server svr;
  17887. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17888. res.set_content(std::string(1024, 'x'), "text/plain");
  17889. });
  17890. auto port = svr.bind_to_any_port(HOST);
  17891. thread t = thread([&]() { svr.listen_after_bind(); });
  17892. auto se = detail::scope_exit([&] {
  17893. svr.stop();
  17894. t.join();
  17895. ASSERT_FALSE(svr.is_running());
  17896. });
  17897. svr.wait_until_ready();
  17898. Client cli(HOST, port);
  17899. cli.set_decompress(false);
  17900. Headers headers;
  17901. headers.emplace("Accept-Encoding", "identity");
  17902. headers.emplace("Accept-Encoding", "gzip");
  17903. auto res = cli.Get("/", headers);
  17904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17905. EXPECT_EQ(StatusCode::OK_200, res->status);
  17906. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  17907. }
  17908. #endif
  17909. #ifndef _WIN32
  17910. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  17911. Server svr;
  17912. svr.Post("/post", [&](const Request &req, Response &res) {
  17913. res.set_content(req.body, "text/plain");
  17914. });
  17915. svr.Put("/put", [&](const Request &req, Response &res) {
  17916. res.set_content(req.body, "text/plain");
  17917. });
  17918. svr.Patch("/patch", [&](const Request &req, Response &res) {
  17919. res.set_content(req.body, "text/plain");
  17920. });
  17921. svr.Delete("/delete", [&](const Request &req, Response &res) {
  17922. res.set_content(req.body, "text/plain");
  17923. });
  17924. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17925. auto se = detail::scope_exit([&] {
  17926. svr.stop();
  17927. t.join();
  17928. ASSERT_FALSE(svr.is_running());
  17929. });
  17930. svr.wait_until_ready();
  17931. std::string resp;
  17932. // POST without Content-Length
  17933. ASSERT_TRUE(send_request(5,
  17934. "POST /post HTTP/1.1\r\n"
  17935. "Host: localhost\r\n"
  17936. "Connection: close\r\n"
  17937. "\r\n",
  17938. &resp));
  17939. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17940. // PUT without Content-Length
  17941. resp.clear();
  17942. ASSERT_TRUE(send_request(5,
  17943. "PUT /put HTTP/1.1\r\n"
  17944. "Host: localhost\r\n"
  17945. "Connection: close\r\n"
  17946. "\r\n",
  17947. &resp));
  17948. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17949. // PATCH without Content-Length
  17950. resp.clear();
  17951. ASSERT_TRUE(send_request(5,
  17952. "PATCH /patch HTTP/1.1\r\n"
  17953. "Host: localhost\r\n"
  17954. "Connection: close\r\n"
  17955. "\r\n",
  17956. &resp));
  17957. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17958. // DELETE without Content-Length
  17959. resp.clear();
  17960. ASSERT_TRUE(send_request(5,
  17961. "DELETE /delete HTTP/1.1\r\n"
  17962. "Host: localhost\r\n"
  17963. "Connection: close\r\n"
  17964. "\r\n",
  17965. &resp));
  17966. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17967. }
  17968. #endif
  17969. //==============================================================================
  17970. // open_stream() Tests
  17971. //==============================================================================
  17972. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  17973. std::string result;
  17974. char buf[8192];
  17975. ssize_t n;
  17976. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17977. result.append(buf, static_cast<size_t>(n));
  17978. }
  17979. return result;
  17980. }
  17981. // Mock stream for unit tests
  17982. class MockStream : public Stream {
  17983. public:
  17984. std::string data;
  17985. size_t pos = 0;
  17986. ssize_t error_after = -1; // -1 = no error
  17987. explicit MockStream(const std::string &d, ssize_t err = -1)
  17988. : data(d), error_after(err) {}
  17989. bool is_readable() const override { return true; }
  17990. bool wait_readable() const override { return true; }
  17991. bool wait_writable() const override { return true; }
  17992. ssize_t read(char *ptr, size_t size) override {
  17993. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  17994. if (pos >= data.size()) return 0;
  17995. size_t limit =
  17996. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  17997. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  17998. std::memcpy(ptr, data.data() + pos, to_read);
  17999. pos += to_read;
  18000. return static_cast<ssize_t>(to_read);
  18001. }
  18002. ssize_t write(const char *, size_t) override { return -1; }
  18003. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  18004. ip = "127.0.0.1";
  18005. port = 0;
  18006. }
  18007. void get_local_ip_and_port(std::string &ip, int &port) const override {
  18008. ip = "127.0.0.1";
  18009. port = 0;
  18010. }
  18011. socket_t socket() const override { return INVALID_SOCKET; }
  18012. time_t duration() const override { return 0; }
  18013. };
  18014. TEST(StreamHandleTest, Basic) {
  18015. ClientImpl::StreamHandle handle;
  18016. EXPECT_FALSE(handle.is_valid());
  18017. handle.response = detail::make_unique<Response>();
  18018. handle.error = Error::Connection;
  18019. EXPECT_FALSE(handle.is_valid());
  18020. handle.error = Error::Success;
  18021. EXPECT_TRUE(handle.is_valid());
  18022. }
  18023. TEST(BodyReaderTest, Basic) {
  18024. MockStream stream("Hello, World!");
  18025. detail::BodyReader reader;
  18026. reader.stream = &stream;
  18027. reader.content_length = 13;
  18028. char buf[32];
  18029. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18030. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18031. EXPECT_TRUE(reader.eof);
  18032. }
  18033. TEST(BodyReaderTest, NoStream) {
  18034. detail::BodyReader reader;
  18035. char buf[32];
  18036. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18037. EXPECT_EQ(Error::Connection, reader.last_error);
  18038. }
  18039. TEST(BodyReaderTest, Error) {
  18040. MockStream stream("Hello, World!", 5);
  18041. detail::BodyReader reader;
  18042. reader.stream = &stream;
  18043. reader.content_length = 13;
  18044. char buf[32];
  18045. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18046. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18047. EXPECT_EQ(Error::Read, reader.last_error);
  18048. }
  18049. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18050. // Mock-based StreamHandle tests relying on private internals are removed.
  18051. class OpenStreamTest : public ::testing::Test {
  18052. protected:
  18053. void SetUp() override {
  18054. svr_.Get("/hello", [](const Request &, Response &res) {
  18055. res.set_content("Hello World!", "text/plain");
  18056. });
  18057. svr_.Get("/large", [](const Request &, Response &res) {
  18058. res.set_content(std::string(10000, 'X'), "text/plain");
  18059. });
  18060. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18061. res.set_content("Hello World!", "image/jpeg");
  18062. res.set_header("Content-Encoding", "UTF-8");
  18063. });
  18064. svr_.Get("/chunked", [](const Request &, Response &res) {
  18065. res.set_chunked_content_provider("text/plain",
  18066. [](size_t offset, DataSink &sink) {
  18067. if (offset < 15) {
  18068. sink.write("chunk", 5);
  18069. return true;
  18070. }
  18071. sink.done();
  18072. return true;
  18073. });
  18074. });
  18075. svr_.Get("/compressible", [](const Request &, Response &res) {
  18076. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18077. DataSink &sink) {
  18078. if (offset < 100 * 1024) {
  18079. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18080. sink.write(chunk.data(), chunk.size());
  18081. return true;
  18082. }
  18083. sink.done();
  18084. return true;
  18085. });
  18086. });
  18087. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18088. [](const Request & /*req*/, Response &res) {
  18089. auto i = new int(0);
  18090. res.set_header("Trailer", "Content-Length, X-Allowed");
  18091. res.set_chunked_content_provider(
  18092. "text/plain",
  18093. [i](size_t /*offset*/, DataSink &sink) {
  18094. switch (*i) {
  18095. case 0: sink.os << "123"; break;
  18096. case 1: sink.os << "456"; break;
  18097. case 2: sink.os << "789"; break;
  18098. case 3: {
  18099. sink.done_with_trailer(
  18100. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18101. } break;
  18102. }
  18103. (*i)++;
  18104. return true;
  18105. },
  18106. [i](bool success) {
  18107. EXPECT_TRUE(success);
  18108. delete i;
  18109. });
  18110. });
  18111. // Echo headers endpoint for header-related tests
  18112. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18113. std::string body;
  18114. for (const auto &h : req.headers) {
  18115. body.append(h.first);
  18116. body.push_back(':');
  18117. body.append(h.second);
  18118. body.push_back('\n');
  18119. }
  18120. res.set_content(body, "text/plain");
  18121. });
  18122. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18123. std::string body;
  18124. for (const auto &h : req.headers) {
  18125. body.append(h.first);
  18126. body.push_back(':');
  18127. body.append(h.second);
  18128. body.push_back('\n');
  18129. }
  18130. res.set_content(body, "text/plain");
  18131. });
  18132. port_ = svr_.bind_to_any_port("127.0.0.1");
  18133. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18134. svr_.wait_until_ready();
  18135. }
  18136. void TearDown() override {
  18137. svr_.stop();
  18138. if (thread_.joinable()) thread_.join();
  18139. }
  18140. Server svr_;
  18141. std::thread thread_;
  18142. int port_ = 0;
  18143. };
  18144. TEST_F(OpenStreamTest, Basic) {
  18145. Client cli("127.0.0.1", port_);
  18146. auto handle = cli.open_stream("GET", "/hello");
  18147. EXPECT_TRUE(handle.is_valid());
  18148. EXPECT_EQ("Hello World!", read_all(handle));
  18149. }
  18150. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18151. Client cli("127.0.0.1", port_);
  18152. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18153. ASSERT_TRUE(handle.is_valid());
  18154. EXPECT_EQ("Hello World!", read_all(handle));
  18155. }
  18156. TEST_F(OpenStreamTest, SmallBuffer) {
  18157. Client cli("127.0.0.1", port_);
  18158. auto handle = cli.open_stream("GET", "/hello");
  18159. std::string result;
  18160. char buf[4];
  18161. ssize_t n;
  18162. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18163. result.append(buf, static_cast<size_t>(n));
  18164. EXPECT_EQ("Hello World!", result);
  18165. }
  18166. TEST_F(OpenStreamTest, DefaultHeaders) {
  18167. Client cli("127.0.0.1", port_);
  18168. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18169. {
  18170. auto handle = cli.open_stream("GET", "/echo-headers");
  18171. ASSERT_TRUE(handle.is_valid());
  18172. auto body = read_all(handle);
  18173. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18174. std::string::npos);
  18175. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18176. std::string::npos);
  18177. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18178. }
  18179. // open_stream POST with body and no explicit content_type should NOT add
  18180. // text/plain Content-Type (behavior differs from non-streaming path), but
  18181. // should include Content-Length
  18182. {
  18183. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18184. ASSERT_TRUE(handle.is_valid());
  18185. auto body = read_all(handle);
  18186. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18187. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18188. }
  18189. // open_stream POST with explicit Content-Type should preserve it
  18190. {
  18191. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18192. {{"Content-Type", "application/custom"}},
  18193. "{}", "application/custom");
  18194. ASSERT_TRUE(handle.is_valid());
  18195. auto body = read_all(handle);
  18196. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18197. }
  18198. // User-specified User-Agent must not be overwritten for stream API
  18199. {
  18200. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18201. {{"User-Agent", "MyAgent/1.2"}});
  18202. ASSERT_TRUE(handle.is_valid());
  18203. auto body = read_all(handle);
  18204. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18205. }
  18206. }
  18207. TEST_F(OpenStreamTest, Large) {
  18208. Client cli("127.0.0.1", port_);
  18209. auto handle = cli.open_stream("GET", "/large");
  18210. EXPECT_EQ(10000u, read_all(handle).size());
  18211. }
  18212. TEST_F(OpenStreamTest, ConnectionError) {
  18213. Client cli("127.0.0.1", 9999);
  18214. auto handle = cli.open_stream("GET", "/hello");
  18215. EXPECT_FALSE(handle.is_valid());
  18216. }
  18217. TEST_F(OpenStreamTest, Chunked) {
  18218. Client cli("127.0.0.1", port_);
  18219. auto handle = cli.open_stream("GET", "/chunked");
  18220. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18221. "Transfer-Encoding") == "chunked");
  18222. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18223. }
  18224. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18225. Client cli("127.0.0.1", port_);
  18226. auto handle =
  18227. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18228. ASSERT_TRUE(handle.is_valid());
  18229. // Consume body to allow trailers to be received/parsed
  18230. auto body = read_all(handle);
  18231. // Explicitly parse trailers (ensure trailers are available for assertion)
  18232. handle.parse_trailers_if_needed();
  18233. EXPECT_EQ(std::string("123456789"), body);
  18234. // The response should include a Trailer header declaring both names
  18235. ASSERT_TRUE(handle.response);
  18236. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18237. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18238. handle.response->get_header_value("Trailer"));
  18239. // Prohibited trailer must not be present
  18240. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18241. // Allowed trailer should be present
  18242. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18243. EXPECT_EQ(std::string("yes"),
  18244. handle.response->get_trailer_value("X-Allowed"));
  18245. // Verify trailers are NOT present as regular headers
  18246. EXPECT_EQ(std::string(""),
  18247. handle.response->get_header_value("Content-Length"));
  18248. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18249. }
  18250. static std::thread serve_single_response(std::promise<int> &port_promise,
  18251. const std::string &response) {
  18252. return std::thread([&port_promise, response] {
  18253. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18254. default_socket_options(srv);
  18255. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18256. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18257. sockaddr_in addr{};
  18258. addr.sin_family = AF_INET;
  18259. addr.sin_port = htons(0); // Let OS assign a free port
  18260. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18261. int opt = 1;
  18262. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18263. #ifdef _WIN32
  18264. reinterpret_cast<const char *>(&opt),
  18265. #else
  18266. &opt,
  18267. #endif
  18268. sizeof(opt));
  18269. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18270. ::listen(srv, 1) != 0) {
  18271. port_promise.set_value(-1);
  18272. detail::close_socket(srv);
  18273. return;
  18274. }
  18275. socklen_t addr_len = sizeof(addr);
  18276. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18277. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18278. sockaddr_in cli_addr{};
  18279. socklen_t cli_len = sizeof(cli_addr);
  18280. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18281. if (cli != INVALID_SOCKET) {
  18282. // Read the complete HTTP request (until the blank line that terminates
  18283. // headers) before sending the response. If the server closes the socket
  18284. // while the client's request data is still unread in the kernel receive
  18285. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18286. // connection on both sides: it discards the client's receive buffer
  18287. // (which already holds our response) and causes any in-progress write on
  18288. // the client to fail with ECONNRESET. Reading all request data first
  18289. // ensures close() emits a graceful FIN.
  18290. {
  18291. char rbuf[256];
  18292. std::string req;
  18293. while (req.find("\r\n\r\n") == std::string::npos) {
  18294. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18295. if (n <= 0) { break; }
  18296. req.append(rbuf, static_cast<size_t>(n));
  18297. }
  18298. }
  18299. ::send(cli,
  18300. #ifdef _WIN32
  18301. static_cast<const char *>(response.c_str()),
  18302. static_cast<int>(response.size()),
  18303. #else
  18304. response.c_str(), response.size(),
  18305. #endif
  18306. 0);
  18307. detail::close_socket(cli);
  18308. }
  18309. detail::close_socket(srv);
  18310. });
  18311. }
  18312. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18313. #ifndef _WIN32
  18314. signal(SIGPIPE, SIG_IGN);
  18315. #endif
  18316. std::promise<int> port_promise;
  18317. auto port_future = port_promise.get_future();
  18318. auto server_thread =
  18319. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18320. "Content-Type: text/plain\r\n"
  18321. "Content-Length: not-a-number\r\n"
  18322. "Connection: close\r\n"
  18323. "\r\n"
  18324. "hello");
  18325. auto port = port_future.get();
  18326. ASSERT_GT(port, 0);
  18327. Client cli("127.0.0.1", port);
  18328. auto handle = cli.open_stream("GET", "/");
  18329. EXPECT_FALSE(handle.is_valid());
  18330. server_thread.join();
  18331. }
  18332. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18333. #ifndef _WIN32
  18334. signal(SIGPIPE, SIG_IGN);
  18335. #endif
  18336. std::promise<int> port_promise;
  18337. auto port_future = port_promise.get_future();
  18338. auto server_thread = serve_single_response(
  18339. port_promise, "HTTP/1.1 200 OK\r\n"
  18340. "Content-Type: text/plain\r\n"
  18341. "Content-Length: 99999999999999999999999999\r\n"
  18342. "Connection: close\r\n"
  18343. "\r\n"
  18344. "hello");
  18345. auto port = port_future.get();
  18346. ASSERT_GT(port, 0);
  18347. // Historically std::stoull would throw std::out_of_range here and crash
  18348. // the process, then parsing silently clamped to a bogus framing length and
  18349. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18350. // so the stream fails to open, matching the not-a-number case above. The
  18351. // process still must NOT terminate.
  18352. Client cli("127.0.0.1", port);
  18353. auto handle = cli.open_stream("GET", "/");
  18354. EXPECT_FALSE(handle.is_valid());
  18355. server_thread.join();
  18356. }
  18357. // Serves `response` to the single request `fn` makes with a fresh client.
  18358. template <typename Fn>
  18359. static void with_single_response(const std::string &response, Fn fn) {
  18360. #ifndef _WIN32
  18361. signal(SIGPIPE, SIG_IGN);
  18362. #endif
  18363. std::promise<int> port_promise;
  18364. auto port_future = port_promise.get_future();
  18365. auto server_thread = serve_single_response(port_promise, response);
  18366. auto se = detail::scope_exit([&] { server_thread.join(); });
  18367. auto port = port_future.get();
  18368. ASSERT_GT(port, 0);
  18369. Client cli("127.0.0.1", port);
  18370. fn(cli);
  18371. }
  18372. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18373. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18374. // the chunked coding and drop Content-Length, so a front-end that trusts
  18375. // Content-Length would disagree about where the body ends (response
  18376. // smuggling). The client must reject such a response.
  18377. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18378. for (const char *te : {"chunked", "gzip, chunked"}) {
  18379. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18380. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18381. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18382. "5\r\nhello\r\n0\r\n\r\n";
  18383. with_single_response(response, [&](Client &cli) {
  18384. auto res = cli.Get("/");
  18385. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18386. EXPECT_EQ(Error::Read, res.error()) << te;
  18387. });
  18388. with_single_response(response, [&](Client &cli) {
  18389. auto handle = cli.open_stream("GET", "/");
  18390. EXPECT_FALSE(handle.is_valid()) << te;
  18391. EXPECT_EQ(Error::Read, handle.error) << te;
  18392. });
  18393. }
  18394. }
  18395. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18396. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18397. // closing the connection (unlike a request, which must be rejected).
  18398. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18399. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18400. "Transfer-Encoding: chunked\r\n"
  18401. "Connection: close\r\n"
  18402. "\r\n"
  18403. "5\r\nhello\r\n0\r\n\r\n",
  18404. "HTTP/1.1 200 OK\r\n"
  18405. "Transfer-Encoding: gzip\r\n"
  18406. "Connection: close\r\n"
  18407. "\r\n"
  18408. "hello"}) {
  18409. with_single_response(response, [&](Client &cli) {
  18410. auto res = cli.Get("/");
  18411. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18412. EXPECT_EQ("hello", res->body);
  18413. });
  18414. with_single_response(response, [&](Client &cli) {
  18415. auto handle = cli.open_stream("GET", "/");
  18416. ASSERT_TRUE(handle.is_valid()) << response;
  18417. EXPECT_EQ("hello", read_all(handle));
  18418. });
  18419. }
  18420. }
  18421. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18422. // framing headers describe nothing to read and must not be rejected.
  18423. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18424. const std::string framing = "Content-Length: 5\r\n"
  18425. "Transfer-Encoding: chunked\r\n"
  18426. "Connection: close\r\n"
  18427. "\r\n";
  18428. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18429. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18430. });
  18431. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18432. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18433. });
  18434. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18435. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18436. with_single_response(response, [&](Client &cli) {
  18437. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18438. });
  18439. with_single_response(response, [&](Client &cli) {
  18440. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18441. });
  18442. }
  18443. }
  18444. // A payload max length of 0 means no limit, however the body is framed.
  18445. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18446. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18447. "Transfer-Encoding: chunked\r\n"
  18448. "\r\n"
  18449. "5\r\nhello\r\n0\r\n\r\n",
  18450. "HTTP/1.1 200 OK\r\n"
  18451. "Connection: close\r\n"
  18452. "\r\n"
  18453. "hello"}) {
  18454. with_single_response(response, [&](Client &cli) {
  18455. cli.set_payload_max_length(0);
  18456. auto res = cli.Get("/");
  18457. ASSERT_TRUE(res) << response;
  18458. EXPECT_EQ("hello", res->body) << response;
  18459. });
  18460. }
  18461. }
  18462. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18463. Server svr;
  18464. svr.set_payload_max_length(0);
  18465. svr.Post("/echo", [](const Request &req, Response &res) {
  18466. res.set_content(req.body, "text/plain");
  18467. });
  18468. auto port = svr.bind_to_any_port(HOST);
  18469. thread t = thread([&] { svr.listen_after_bind(); });
  18470. auto se = detail::scope_exit([&] {
  18471. svr.stop();
  18472. t.join();
  18473. ASSERT_FALSE(svr.is_running());
  18474. });
  18475. svr.wait_until_ready();
  18476. Client cli(HOST, port);
  18477. auto res = cli.Post(
  18478. "/echo",
  18479. [](size_t /*offset*/, DataSink &sink) {
  18480. sink.write("hello", 5);
  18481. sink.done();
  18482. return true;
  18483. },
  18484. "text/plain");
  18485. ASSERT_TRUE(res);
  18486. EXPECT_EQ(StatusCode::OK_200, res->status);
  18487. EXPECT_EQ("hello", res->body);
  18488. }
  18489. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18490. TEST_F(OpenStreamTest, Gzip) {
  18491. Client cli("127.0.0.1", port_);
  18492. auto handle = cli.open_stream("GET", "/compressible", {},
  18493. {{"Accept-Encoding", "gzip"}});
  18494. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18495. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18496. }
  18497. #endif
  18498. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18499. TEST_F(OpenStreamTest, Brotli) {
  18500. Client cli("127.0.0.1", port_);
  18501. auto handle =
  18502. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18503. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18504. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18505. }
  18506. #endif
  18507. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18508. TEST_F(OpenStreamTest, Zstd) {
  18509. Client cli("127.0.0.1", port_);
  18510. auto handle = cli.open_stream("GET", "/compressible", {},
  18511. {{"Accept-Encoding", "zstd"}});
  18512. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18513. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18514. }
  18515. #endif
  18516. #ifdef CPPHTTPLIB_SSL_ENABLED
  18517. class SSLOpenStreamTest : public ::testing::Test {
  18518. protected:
  18519. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18520. void SetUp() override {
  18521. svr_.Get("/hello", [](const Request &, Response &res) {
  18522. res.set_content("Hello SSL World!", "text/plain");
  18523. });
  18524. svr_.Get("/chunked", [](const Request &, Response &res) {
  18525. res.set_chunked_content_provider("text/plain",
  18526. [](size_t offset, DataSink &sink) {
  18527. if (offset < 15) {
  18528. sink.write("chunk", 5);
  18529. return true;
  18530. }
  18531. sink.done();
  18532. return true;
  18533. });
  18534. });
  18535. svr_.Post("/echo", [](const Request &req, Response &res) {
  18536. res.set_content(req.body, req.get_header_value("Content-Type"));
  18537. });
  18538. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18539. std::string body = req.body;
  18540. res.set_chunked_content_provider(
  18541. "text/plain", [body](size_t offset, DataSink &sink) {
  18542. if (offset < body.size()) {
  18543. sink.write(body.data() + offset, body.size() - offset);
  18544. }
  18545. sink.done();
  18546. return true;
  18547. });
  18548. });
  18549. port_ = svr_.bind_to_any_port("127.0.0.1");
  18550. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18551. svr_.wait_until_ready();
  18552. }
  18553. void TearDown() override {
  18554. svr_.stop();
  18555. if (thread_.joinable()) thread_.join();
  18556. }
  18557. SSLServer svr_;
  18558. std::thread thread_;
  18559. int port_ = 0;
  18560. };
  18561. TEST_F(SSLOpenStreamTest, Basic) {
  18562. SSLClient cli("127.0.0.1", port_);
  18563. cli.enable_server_certificate_verification(false);
  18564. auto handle = cli.open_stream("GET", "/hello");
  18565. ASSERT_TRUE(handle.is_valid());
  18566. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18567. }
  18568. TEST_F(SSLOpenStreamTest, Chunked) {
  18569. SSLClient cli("127.0.0.1", port_);
  18570. cli.enable_server_certificate_verification(false);
  18571. auto handle = cli.open_stream("GET", "/chunked");
  18572. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18573. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18574. "Transfer-Encoding") == "chunked");
  18575. auto body = read_all(handle);
  18576. EXPECT_EQ("chunkchunkchunk", body);
  18577. }
  18578. TEST_F(SSLOpenStreamTest, Post) {
  18579. SSLClient cli("127.0.0.1", port_);
  18580. cli.enable_server_certificate_verification(false);
  18581. auto handle =
  18582. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  18583. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18584. EXPECT_EQ(200, handle.response->status);
  18585. auto body = read_all(handle);
  18586. EXPECT_EQ("Hello SSL POST", body);
  18587. }
  18588. TEST_F(SSLOpenStreamTest, PostChunked) {
  18589. SSLClient cli("127.0.0.1", port_);
  18590. cli.enable_server_certificate_verification(false);
  18591. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  18592. "Chunked SSL Data", "text/plain");
  18593. ASSERT_TRUE(handle.is_valid());
  18594. EXPECT_EQ(200, handle.response->status);
  18595. auto body = read_all(handle);
  18596. EXPECT_EQ("Chunked SSL Data", body);
  18597. }
  18598. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  18599. // Content-Length is terminated by the server closing the connection. When the
  18600. // SSL peer sends a close_notify after the body, the client must treat it as a
  18601. // clean EOF and return a successful response rather than an error.
  18602. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  18603. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18604. ASSERT_TRUE(svr.is_valid());
  18605. svr.set_keep_alive_max_count(1);
  18606. const std::string expected_body = "Hello from connection-close response!";
  18607. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  18608. res.set_content_provider("text/plain",
  18609. [&](size_t offset, DataSink &sink) -> bool {
  18610. if (offset < expected_body.size()) {
  18611. sink.write(expected_body.data() + offset,
  18612. expected_body.size() - offset);
  18613. }
  18614. sink.done();
  18615. return true;
  18616. });
  18617. });
  18618. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  18619. auto se = detail::scope_exit([&] {
  18620. svr.stop();
  18621. listen_thread.join();
  18622. ASSERT_FALSE(svr.is_running());
  18623. });
  18624. svr.wait_until_ready();
  18625. SSLClient cli(HOST, PORT);
  18626. cli.enable_server_certificate_verification(false);
  18627. auto res = cli.Get("/no-content-length");
  18628. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18629. EXPECT_EQ(StatusCode::OK_200, res->status);
  18630. EXPECT_EQ(expected_body, res->body);
  18631. }
  18632. #endif // CPPHTTPLIB_SSL_ENABLED
  18633. //==============================================================================
  18634. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18635. // results for various scenarios.
  18636. //==============================================================================
  18637. TEST(ParityTest, GetVsOpenStream) {
  18638. Server svr;
  18639. const std::string path = "/parity";
  18640. const std::string content = "Parity test content: hello world";
  18641. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18642. res.set_content(content, "text/plain");
  18643. });
  18644. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18645. auto se = detail::scope_exit([&] {
  18646. svr.stop();
  18647. t.join();
  18648. ASSERT_FALSE(svr.is_running());
  18649. });
  18650. svr.wait_until_ready();
  18651. Client cli(HOST, PORT);
  18652. // Non-stream path
  18653. auto r1 = cli.Get(path);
  18654. ASSERT_TRUE(r1);
  18655. EXPECT_EQ(StatusCode::OK_200, r1->status);
  18656. // Stream path
  18657. auto h = cli.open_stream("GET", path);
  18658. ASSERT_TRUE(h.is_valid());
  18659. EXPECT_EQ(r1->body, read_all(h));
  18660. }
  18661. // Helper to compress data with provided compressor type T
  18662. template <typename Compressor>
  18663. static std::string compress_payload_for_parity(const std::string &in) {
  18664. std::string out;
  18665. Compressor compressor;
  18666. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  18667. [&](const char *data, size_t n) {
  18668. out.append(data, n);
  18669. return true;
  18670. });
  18671. EXPECT_TRUE(ok);
  18672. return out;
  18673. }
  18674. // Helper function for compression parity tests
  18675. template <typename Compressor>
  18676. static void test_compression_parity(const std::string &original,
  18677. const std::string &path,
  18678. const std::string &encoding) {
  18679. const std::string compressed =
  18680. compress_payload_for_parity<Compressor>(original);
  18681. Server svr;
  18682. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18683. res.set_content(compressed, "application/octet-stream");
  18684. res.set_header("Content-Encoding", encoding);
  18685. });
  18686. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  18687. auto se = detail::scope_exit([&] {
  18688. svr.stop();
  18689. t.join();
  18690. ASSERT_FALSE(svr.is_running());
  18691. });
  18692. svr.wait_until_ready();
  18693. Client cli(HOST, PORT);
  18694. // Non-streaming
  18695. {
  18696. auto res = cli.Get(path);
  18697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18698. EXPECT_EQ(StatusCode::OK_200, res->status);
  18699. EXPECT_EQ(original, res->body);
  18700. }
  18701. // Streaming
  18702. {
  18703. auto h = cli.open_stream("GET", path);
  18704. ASSERT_TRUE(h.is_valid());
  18705. EXPECT_EQ(original, read_all(h));
  18706. }
  18707. }
  18708. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18709. TEST(ParityTest, Gzip) {
  18710. test_compression_parity<detail::gzip_compressor>(
  18711. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  18712. }
  18713. #endif
  18714. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18715. TEST(ParityTest, Brotli) {
  18716. test_compression_parity<detail::brotli_compressor>(
  18717. "Hello, brotli parity test payload", "/parity-br", "br");
  18718. }
  18719. #endif
  18720. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18721. TEST(ParityTest, Zstd) {
  18722. test_compression_parity<detail::zstd_compressor>(
  18723. "Zstandard parity test payload", "/parity-zstd", "zstd");
  18724. }
  18725. #endif
  18726. //==============================================================================
  18727. // New Stream API Tests
  18728. //==============================================================================
  18729. inline std::string read_body(httplib::stream::Result &result) {
  18730. std::string body;
  18731. while (result.next()) {
  18732. body.append(result.data(), result.size());
  18733. }
  18734. return body;
  18735. }
  18736. TEST(ClientConnectionTest, Basic) {
  18737. httplib::ClientConnection conn;
  18738. EXPECT_FALSE(conn.is_open());
  18739. conn.sock = 1;
  18740. EXPECT_TRUE(conn.is_open());
  18741. httplib::ClientConnection conn2(std::move(conn));
  18742. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  18743. conn2.sock = INVALID_SOCKET;
  18744. }
  18745. // Unified test server for all stream::* tests
  18746. class StreamApiTest : public ::testing::Test {
  18747. protected:
  18748. void SetUp() override {
  18749. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18750. res.set_content("Hello World!", "text/plain");
  18751. });
  18752. svr_.Get("/echo-params",
  18753. [](const httplib::Request &req, httplib::Response &res) {
  18754. std::string r;
  18755. for (const auto &p : req.params) {
  18756. if (!r.empty()) r += "&";
  18757. r += p.first + "=" + p.second;
  18758. }
  18759. res.set_content(r, "text/plain");
  18760. });
  18761. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18762. res.set_content(req.body, req.get_header_value("Content-Type"));
  18763. });
  18764. svr_.Post("/echo-headers",
  18765. [](const httplib::Request &req, httplib::Response &res) {
  18766. std::string r;
  18767. for (const auto &h : req.headers)
  18768. r += h.first + ": " + h.second + "\n";
  18769. res.set_content(r, "text/plain");
  18770. });
  18771. svr_.Post("/echo-params",
  18772. [](const httplib::Request &req, httplib::Response &res) {
  18773. std::string r = "params:";
  18774. for (const auto &p : req.params)
  18775. r += p.first + "=" + p.second + ";";
  18776. res.set_content(r + " body:" + req.body, "text/plain");
  18777. });
  18778. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  18779. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  18780. });
  18781. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18782. res.set_content("PUT:" + req.body, "text/plain");
  18783. });
  18784. svr_.Patch("/echo",
  18785. [](const httplib::Request &req, httplib::Response &res) {
  18786. res.set_content("PATCH:" + req.body, "text/plain");
  18787. });
  18788. svr_.Delete(
  18789. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  18790. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  18791. "text/plain");
  18792. });
  18793. svr_.Get("/head-test",
  18794. [](const httplib::Request &, httplib::Response &res) {
  18795. res.set_content("body for HEAD", "text/plain");
  18796. });
  18797. svr_.Options("/options",
  18798. [](const httplib::Request &, httplib::Response &res) {
  18799. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  18800. });
  18801. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  18802. svr_.wait_until_ready();
  18803. }
  18804. void TearDown() override {
  18805. svr_.stop();
  18806. if (thread_.joinable()) thread_.join();
  18807. }
  18808. httplib::Server svr_;
  18809. std::thread thread_;
  18810. };
  18811. // stream::Get tests
  18812. TEST_F(StreamApiTest, GetBasic) {
  18813. httplib::Client cli(HOST, PORT);
  18814. auto result = httplib::stream::Get(cli, "/hello");
  18815. ASSERT_TRUE(result.is_valid());
  18816. EXPECT_EQ(200, result.status());
  18817. EXPECT_EQ("Hello World!", read_body(result));
  18818. }
  18819. TEST_F(StreamApiTest, GetWithParams) {
  18820. httplib::Client cli(HOST, PORT);
  18821. httplib::Params params{{"foo", "bar"}};
  18822. auto result = httplib::stream::Get(cli, "/echo-params", params);
  18823. ASSERT_TRUE(result.is_valid());
  18824. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  18825. }
  18826. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18827. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  18828. httplib::Client cli(HOST, PORT);
  18829. cli.set_payload_max_length(0);
  18830. auto result = httplib::stream::Get(cli, "/hello");
  18831. ASSERT_TRUE(result.is_valid());
  18832. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  18833. EXPECT_EQ("Hello World!", read_body(result));
  18834. }
  18835. #endif
  18836. TEST_F(StreamApiTest, GetConnectionError) {
  18837. httplib::Client cli(HOST, 9999);
  18838. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  18839. }
  18840. TEST_F(StreamApiTest, Get404) {
  18841. httplib::Client cli(HOST, PORT);
  18842. auto result = httplib::stream::Get(cli, "/nonexistent");
  18843. EXPECT_TRUE(result.is_valid());
  18844. EXPECT_EQ(404, result.status());
  18845. }
  18846. // stream::Post tests
  18847. TEST_F(StreamApiTest, PostBasic) {
  18848. httplib::Client cli(HOST, PORT);
  18849. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  18850. "application/json");
  18851. ASSERT_TRUE(result.is_valid());
  18852. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  18853. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  18854. }
  18855. TEST_F(StreamApiTest, PostWithHeaders) {
  18856. httplib::Client cli(HOST, PORT);
  18857. httplib::Headers headers{{"X-Custom", "value"}};
  18858. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  18859. "text/plain");
  18860. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  18861. }
  18862. TEST_F(StreamApiTest, PostWithParams) {
  18863. httplib::Client cli(HOST, PORT);
  18864. httplib::Params params{{"k", "v"}};
  18865. auto result =
  18866. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  18867. auto body = read_body(result);
  18868. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  18869. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  18870. }
  18871. TEST_F(StreamApiTest, PostLarge) {
  18872. httplib::Client cli(HOST, PORT);
  18873. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  18874. size_t total = 0;
  18875. while (result.next()) {
  18876. total += result.size();
  18877. }
  18878. EXPECT_EQ(100u * 1024u, total);
  18879. }
  18880. // stream::Put/Patch tests
  18881. TEST_F(StreamApiTest, PutAndPatch) {
  18882. httplib::Client cli(HOST, PORT);
  18883. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  18884. EXPECT_EQ("PUT:test", read_body(put));
  18885. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  18886. EXPECT_EQ("PATCH:test", read_body(patch));
  18887. }
  18888. // stream::Delete tests
  18889. TEST_F(StreamApiTest, Delete) {
  18890. httplib::Client cli(HOST, PORT);
  18891. auto del1 = httplib::stream::Delete(cli, "/resource");
  18892. EXPECT_EQ("Deleted", read_body(del1));
  18893. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  18894. EXPECT_EQ("Deleted:data", read_body(del2));
  18895. }
  18896. // stream::Head/Options tests
  18897. TEST_F(StreamApiTest, HeadAndOptions) {
  18898. httplib::Client cli(HOST, PORT);
  18899. auto head = httplib::stream::Head(cli, "/head-test");
  18900. EXPECT_TRUE(head.is_valid());
  18901. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  18902. auto opts = httplib::stream::Options(cli, "/options");
  18903. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  18904. }
  18905. // SSL stream::* tests
  18906. #ifdef CPPHTTPLIB_SSL_ENABLED
  18907. class SSLStreamApiTest : public ::testing::Test {
  18908. protected:
  18909. void SetUp() override {
  18910. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18911. res.set_content("Hello SSL!", "text/plain");
  18912. });
  18913. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18914. res.set_content(req.body, "text/plain");
  18915. });
  18916. port_ = svr_.bind_to_any_port("127.0.0.1");
  18917. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18918. svr_.wait_until_ready();
  18919. }
  18920. void TearDown() override {
  18921. svr_.stop();
  18922. if (thread_.joinable()) thread_.join();
  18923. }
  18924. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  18925. std::thread thread_;
  18926. int port_ = 0;
  18927. };
  18928. TEST_F(SSLStreamApiTest, GetAndPost) {
  18929. httplib::SSLClient cli("127.0.0.1", port_);
  18930. cli.enable_server_certificate_verification(false);
  18931. auto get = httplib::stream::Get(cli, "/hello");
  18932. EXPECT_EQ("Hello SSL!", read_body(get));
  18933. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  18934. EXPECT_EQ("test", read_body(post));
  18935. }
  18936. #endif
  18937. // Tests for Error::Timeout and Error::ConnectionClosed error types
  18938. // These errors are set in SocketStream/SSLSocketStream and propagated through
  18939. // BodyReader
  18940. TEST(ErrorHandlingTest, StreamReadTimeout) {
  18941. // Test that read timeout during streaming is detected
  18942. // Use a large content-length response where server delays mid-stream
  18943. Server svr;
  18944. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18945. // Send a large response with delay in the middle
  18946. res.set_content_provider(
  18947. 1000, // content_length
  18948. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  18949. if (offset < 100) {
  18950. // Send first 100 bytes immediately
  18951. std::string data(100, 'A');
  18952. sink.write(data.c_str(), data.size());
  18953. return true;
  18954. }
  18955. // Then delay longer than client timeout
  18956. std::this_thread::sleep_for(std::chrono::seconds(3));
  18957. std::string data(900, 'B');
  18958. sink.write(data.c_str(), data.size());
  18959. return true;
  18960. });
  18961. });
  18962. auto port = 8091;
  18963. std::thread t([&]() { svr.listen("localhost", port); });
  18964. svr.wait_until_ready();
  18965. Client cli("localhost", port);
  18966. cli.set_read_timeout(1, 0); // 1 second timeout
  18967. auto handle = cli.open_stream("GET", "/slow-stream");
  18968. ASSERT_TRUE(handle.is_valid());
  18969. char buf[256];
  18970. ssize_t total = 0;
  18971. ssize_t n;
  18972. bool got_error = false;
  18973. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18974. total += n;
  18975. }
  18976. if (n < 0) {
  18977. got_error = true;
  18978. // Should be timeout or read error
  18979. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18980. handle.get_read_error() == Error::Read)
  18981. << "Actual error: " << to_string(handle.get_read_error());
  18982. }
  18983. // Either we got an error, or we got less data than expected
  18984. EXPECT_TRUE(got_error || total < 1000)
  18985. << "Expected timeout but got all " << total << " bytes";
  18986. svr.stop();
  18987. t.join();
  18988. }
  18989. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  18990. // Test connection closed detection via BodyReader
  18991. Server svr;
  18992. std::atomic<bool> close_now{false};
  18993. svr.Get("/will-close", [&](const Request &, Response &res) {
  18994. res.set_content_provider(
  18995. 10000, // Large content_length that we won't fully send
  18996. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18997. if (offset < 100) {
  18998. std::string data(100, 'X');
  18999. sink.write(data.c_str(), data.size());
  19000. return true;
  19001. }
  19002. // Wait for signal then abort
  19003. while (!close_now) {
  19004. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19005. }
  19006. return false; // Abort - server will close connection
  19007. });
  19008. });
  19009. auto port = 8092;
  19010. std::thread t([&]() { svr.listen("localhost", port); });
  19011. svr.wait_until_ready();
  19012. Client cli("localhost", port);
  19013. auto handle = cli.open_stream("GET", "/will-close");
  19014. ASSERT_TRUE(handle.is_valid());
  19015. char buf[256];
  19016. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19017. EXPECT_GT(n, 0) << "First read should succeed";
  19018. // Signal server to close
  19019. close_now = true;
  19020. // Keep reading until error or EOF
  19021. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19022. // Keep reading
  19023. }
  19024. // Should get an error since content_length wasn't satisfied
  19025. if (n < 0) {
  19026. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19027. handle.get_read_error() == Error::Read)
  19028. << "Actual error: " << to_string(handle.get_read_error());
  19029. }
  19030. svr.stop();
  19031. t.join();
  19032. }
  19033. #ifdef CPPHTTPLIB_SSL_ENABLED
  19034. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  19035. // Test that read timeout during SSL streaming is detected
  19036. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19037. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19038. res.set_content_provider(
  19039. 1000, "text/plain",
  19040. [](size_t offset, size_t /*length*/, DataSink &sink) {
  19041. if (offset < 100) {
  19042. std::string data(100, 'A');
  19043. sink.write(data.c_str(), data.size());
  19044. return true;
  19045. }
  19046. std::this_thread::sleep_for(std::chrono::seconds(3));
  19047. std::string data(900, 'B');
  19048. sink.write(data.c_str(), data.size());
  19049. return true;
  19050. });
  19051. });
  19052. auto port = 8093;
  19053. std::thread t([&]() { svr.listen("localhost", port); });
  19054. svr.wait_until_ready();
  19055. SSLClient cli("localhost", port);
  19056. cli.enable_server_certificate_verification(false);
  19057. cli.set_read_timeout(1, 0); // 1 second timeout
  19058. auto handle = cli.open_stream("GET", "/slow-stream");
  19059. ASSERT_TRUE(handle.is_valid());
  19060. char buf[256];
  19061. ssize_t total = 0;
  19062. ssize_t n;
  19063. bool got_error = false;
  19064. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19065. total += n;
  19066. }
  19067. if (n < 0) {
  19068. got_error = true;
  19069. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19070. handle.get_read_error() == Error::Read)
  19071. << "Actual error: " << to_string(handle.get_read_error());
  19072. }
  19073. EXPECT_TRUE(got_error || total < 1000)
  19074. << "Expected timeout but got all " << total << " bytes";
  19075. svr.stop();
  19076. t.join();
  19077. }
  19078. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  19079. // Test SSL connection closed detection
  19080. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19081. std::atomic<bool> close_now{false};
  19082. svr.Get("/will-close", [&](const Request &, Response &res) {
  19083. res.set_content_provider(
  19084. 10000, "text/plain",
  19085. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19086. if (offset < 100) {
  19087. std::string data(100, 'X');
  19088. sink.write(data.c_str(), data.size());
  19089. return true;
  19090. }
  19091. while (!close_now) {
  19092. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19093. }
  19094. return false;
  19095. });
  19096. });
  19097. auto port = 8094;
  19098. std::thread t([&]() { svr.listen("localhost", port); });
  19099. svr.wait_until_ready();
  19100. SSLClient cli("localhost", port);
  19101. cli.enable_server_certificate_verification(false);
  19102. auto handle = cli.open_stream("GET", "/will-close");
  19103. ASSERT_TRUE(handle.is_valid());
  19104. char buf[256];
  19105. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19106. EXPECT_GT(n, 0);
  19107. // Signal server to close
  19108. close_now = true;
  19109. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19110. // Keep reading
  19111. }
  19112. if (n < 0) {
  19113. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19114. handle.get_read_error() == Error::Read)
  19115. << "Actual error: " << to_string(handle.get_read_error());
  19116. }
  19117. svr.stop();
  19118. t.join();
  19119. }
  19120. #endif
  19121. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19122. using namespace httplib;
  19123. // Create a test file
  19124. const char *fname = "etag_testfile.txt";
  19125. const char *content = "etag-content";
  19126. {
  19127. std::ofstream ofs(fname);
  19128. ofs << content;
  19129. ASSERT_TRUE(ofs.good());
  19130. }
  19131. Server svr;
  19132. svr.set_mount_point("/static", ".");
  19133. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19134. svr.wait_until_ready();
  19135. Client cli(HOST, PORT);
  19136. // First request: should get 200 with ETag header
  19137. auto res1 = cli.Get("/static/etag_testfile.txt");
  19138. ASSERT_TRUE(res1);
  19139. ASSERT_EQ(200, res1->status);
  19140. ASSERT_TRUE(res1->has_header("ETag"));
  19141. std::string etag = res1->get_header_value("ETag");
  19142. EXPECT_FALSE(etag.empty());
  19143. // Verify ETag format: W/"hex-hex"
  19144. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19145. EXPECT_EQ('W', etag[0]);
  19146. EXPECT_EQ('/', etag[1]);
  19147. EXPECT_EQ('"', etag[2]);
  19148. EXPECT_EQ('"', etag.back());
  19149. // Exact match: expect 304 Not Modified
  19150. Headers h2 = {{"If-None-Match", etag}};
  19151. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19152. ASSERT_TRUE(res2);
  19153. EXPECT_EQ(304, res2->status);
  19154. // Wildcard match: expect 304 Not Modified
  19155. Headers h3 = {{"If-None-Match", "*"}};
  19156. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19157. ASSERT_TRUE(res3);
  19158. EXPECT_EQ(304, res3->status);
  19159. // Non-matching ETag: expect 200
  19160. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19161. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19162. ASSERT_TRUE(res4);
  19163. EXPECT_EQ(200, res4->status);
  19164. // Multiple ETags with one matching: expect 304
  19165. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19166. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19167. ASSERT_TRUE(res5);
  19168. EXPECT_EQ(304, res5->status);
  19169. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19170. // that equivalent to the single comma-separated list above, so the match on
  19171. // the second line must still be found.
  19172. Headers h6;
  19173. h6.emplace("If-None-Match", "W/\"other\"");
  19174. h6.emplace("If-None-Match", etag);
  19175. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19176. ASSERT_TRUE(res6);
  19177. EXPECT_EQ(304, res6->status);
  19178. svr.stop();
  19179. t.join();
  19180. std::remove(fname);
  19181. }
  19182. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19183. using namespace httplib;
  19184. Server svr;
  19185. svr.set_mount_point("/static", ".");
  19186. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19187. svr.wait_until_ready();
  19188. Client cli(HOST, PORT);
  19189. // Send If-None-Match: * to a non-existent file
  19190. Headers h = {{"If-None-Match", "*"}};
  19191. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19193. EXPECT_EQ(404, res->status);
  19194. svr.stop();
  19195. t.join();
  19196. }
  19197. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  19198. using namespace httplib;
  19199. // Create a test file
  19200. const char *fname = "etag_boundary_testfile.txt";
  19201. const char *content = "boundary-test";
  19202. {
  19203. std::ofstream ofs(fname);
  19204. ofs << content;
  19205. ASSERT_TRUE(ofs.good());
  19206. }
  19207. Server svr;
  19208. svr.set_mount_point("/static", ".");
  19209. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19210. svr.wait_until_ready();
  19211. Client cli(HOST, PORT);
  19212. // Get the actual ETag
  19213. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  19214. ASSERT_TRUE(res1);
  19215. ASSERT_EQ(200, res1->status);
  19216. ASSERT_TRUE(res1->has_header("ETag"));
  19217. std::string etag = res1->get_header_value("ETag");
  19218. // Test 1: Very long ETag value (longer than actual ETag)
  19219. // Should NOT match and return 200 (not trigger out-of-bounds read)
  19220. Headers h1 = {{"If-None-Match", "W/"
  19221. "\"very-long-etag-value-that-is-much-longer-"
  19222. "than-the-actual-etag-value\""}};
  19223. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  19224. ASSERT_TRUE(res2);
  19225. EXPECT_EQ(200, res2->status); // Should not match
  19226. // Test 2: Long string followed by wildcard
  19227. // Should match on "*" and return 304 (without out-of-bounds read on the long
  19228. // string)
  19229. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19230. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19231. ASSERT_TRUE(res3);
  19232. EXPECT_EQ(304, res3->status); // Should match on "*"
  19233. // Test 3: Wildcard followed by long string
  19234. // Should match on "*" immediately and return 304
  19235. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  19236. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  19237. ASSERT_TRUE(res4);
  19238. EXPECT_EQ(304, res4->status); // Should match on "*"
  19239. // Test 4: Multiple long non-matching values
  19240. // Should NOT match and return 200 (test that all comparisons are safe)
  19241. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  19242. "W/\"second-long-non-matching-value\", "
  19243. "W/\"third-long-non-matching-value\""}};
  19244. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  19245. ASSERT_TRUE(res5);
  19246. EXPECT_EQ(200, res5->status); // Should not match
  19247. // Test 5: Single character that is not "*" (edge case)
  19248. Headers h5 = {{"If-None-Match", "X"}};
  19249. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  19250. ASSERT_TRUE(res6);
  19251. EXPECT_EQ(200, res6->status); // Should not match
  19252. svr.stop();
  19253. t.join();
  19254. std::remove(fname);
  19255. }
  19256. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  19257. using namespace httplib;
  19258. // Create a test file
  19259. const char *fname = "ims_testfile.txt";
  19260. const char *content = "if-modified-since-test";
  19261. {
  19262. std::ofstream ofs(fname);
  19263. ofs << content;
  19264. ASSERT_TRUE(ofs.good());
  19265. }
  19266. Server svr;
  19267. svr.set_mount_point("/static", ".");
  19268. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19269. svr.wait_until_ready();
  19270. Client cli(HOST, PORT);
  19271. // First request: should get 200 with Last-Modified header
  19272. auto res1 = cli.Get("/static/ims_testfile.txt");
  19273. ASSERT_TRUE(res1);
  19274. ASSERT_EQ(200, res1->status);
  19275. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19276. std::string last_modified = res1->get_header_value("Last-Modified");
  19277. EXPECT_FALSE(last_modified.empty());
  19278. // If-Modified-Since with same time: expect 304
  19279. Headers h2 = {{"If-Modified-Since", last_modified}};
  19280. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  19281. ASSERT_TRUE(res2);
  19282. EXPECT_EQ(304, res2->status);
  19283. // If-Modified-Since with future time: expect 304
  19284. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19285. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  19286. ASSERT_TRUE(res3);
  19287. EXPECT_EQ(304, res3->status);
  19288. // If-Modified-Since with past time: expect 200
  19289. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19290. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  19291. ASSERT_TRUE(res4);
  19292. EXPECT_EQ(200, res4->status);
  19293. // If-None-Match takes precedence over If-Modified-Since
  19294. // (send matching ETag with old If-Modified-Since -> should still be 304)
  19295. ASSERT_TRUE(res1->has_header("ETag"));
  19296. std::string etag = res1->get_header_value("ETag");
  19297. Headers h5 = {{"If-None-Match", etag},
  19298. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19299. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  19300. ASSERT_TRUE(res5);
  19301. EXPECT_EQ(304, res5->status);
  19302. svr.stop();
  19303. t.join();
  19304. std::remove(fname);
  19305. }
  19306. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  19307. using namespace httplib;
  19308. Server svr;
  19309. // Endpoint that returns compressible content
  19310. svr.Get("/compressible", [](const Request &, Response &res) {
  19311. // Return a large enough body to trigger compression
  19312. std::string body(1000, 'a');
  19313. res.set_content(body, "text/plain");
  19314. });
  19315. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19316. svr.wait_until_ready();
  19317. Client cli(HOST, PORT);
  19318. // Request with gzip support: should get Vary header when compressed
  19319. cli.set_compress(true);
  19320. auto res1 = cli.Get("/compressible");
  19321. ASSERT_TRUE(res1);
  19322. EXPECT_EQ(200, res1->status);
  19323. // If Content-Encoding is set, Vary should also be set
  19324. if (res1->has_header("Content-Encoding")) {
  19325. EXPECT_TRUE(res1->has_header("Vary"));
  19326. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  19327. }
  19328. // Request without Accept-Encoding header: should not have compression
  19329. Headers h_no_compress;
  19330. auto res2 = cli.Get("/compressible", h_no_compress);
  19331. ASSERT_TRUE(res2);
  19332. EXPECT_EQ(200, res2->status);
  19333. // Verify Vary header is present when compression is applied
  19334. // (the exact behavior depends on server configuration)
  19335. svr.stop();
  19336. t.join();
  19337. }
  19338. TEST(ETagTest, IfRangeWithETag) {
  19339. using namespace httplib;
  19340. // Create a test file with known content
  19341. const char *fname = "if_range_testfile.txt";
  19342. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  19343. {
  19344. std::ofstream ofs(fname);
  19345. ofs << content;
  19346. ASSERT_TRUE(ofs.good());
  19347. }
  19348. Server svr;
  19349. svr.set_mount_point("/static", ".");
  19350. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19351. svr.wait_until_ready();
  19352. Client cli(HOST, PORT);
  19353. // First request: get ETag
  19354. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19355. ASSERT_TRUE(res1);
  19356. ASSERT_EQ(200, res1->status);
  19357. ASSERT_TRUE(res1->has_header("ETag"));
  19358. std::string etag = res1->get_header_value("ETag");
  19359. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  19360. // Since our server generates weak ETags (W/"..."), If-Range with our
  19361. // ETag should NOT result in partial content - it should return full content.
  19362. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  19363. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  19364. ASSERT_TRUE(res2);
  19365. // Weak ETag in If-Range -> full content (200), not partial (206)
  19366. EXPECT_EQ(200, res2->status);
  19367. EXPECT_EQ(content, res2->body);
  19368. EXPECT_FALSE(res2->has_header("Content-Range"));
  19369. // Range request with non-matching If-Range (ETag): should get 200 (full
  19370. // content)
  19371. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  19372. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  19373. ASSERT_TRUE(res3);
  19374. EXPECT_EQ(200, res3->status);
  19375. EXPECT_EQ(content, res3->body);
  19376. EXPECT_FALSE(res3->has_header("Content-Range"));
  19377. // Range request with strong ETag (hypothetical - our server doesn't generate
  19378. // strong ETags, but if client sends a strong ETag that doesn't match, it
  19379. // should return full content)
  19380. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19381. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19382. ASSERT_TRUE(res4);
  19383. EXPECT_EQ(200, res4->status);
  19384. EXPECT_EQ(content, res4->body);
  19385. EXPECT_FALSE(res4->has_header("Content-Range"));
  19386. svr.stop();
  19387. t.join();
  19388. std::remove(fname);
  19389. }
  19390. TEST(ETagTest, IfRangeWithDate) {
  19391. using namespace httplib;
  19392. // Create a test file
  19393. const char *fname = "if_range_date_testfile.txt";
  19394. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  19395. {
  19396. std::ofstream ofs(fname);
  19397. ofs << content;
  19398. ASSERT_TRUE(ofs.good());
  19399. }
  19400. Server svr;
  19401. svr.set_mount_point("/static", ".");
  19402. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19403. svr.wait_until_ready();
  19404. Client cli(HOST, PORT);
  19405. // First request: get Last-Modified
  19406. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  19407. ASSERT_TRUE(res1);
  19408. ASSERT_EQ(200, res1->status);
  19409. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19410. std::string last_modified = res1->get_header_value("Last-Modified");
  19411. // Range request with matching If-Range (date): should get 206
  19412. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19413. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19414. ASSERT_TRUE(res2);
  19415. EXPECT_EQ(206, res2->status);
  19416. EXPECT_EQ("FGHIJ", res2->body);
  19417. // Range request with old If-Range date: should get 200 (full content)
  19418. Headers h3 = {{"Range", "bytes=5-9"},
  19419. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19420. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19421. ASSERT_TRUE(res3);
  19422. EXPECT_EQ(200, res3->status);
  19423. EXPECT_EQ(content, res3->body);
  19424. // Range request with future If-Range date: should get 206
  19425. Headers h4 = {{"Range", "bytes=0-4"},
  19426. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19427. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19428. ASSERT_TRUE(res4);
  19429. EXPECT_EQ(206, res4->status);
  19430. EXPECT_EQ("ABCDE", res4->body);
  19431. svr.stop();
  19432. t.join();
  19433. std::remove(fname);
  19434. }
  19435. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19436. using namespace httplib;
  19437. const char *fname = "etag_malformed.txt";
  19438. const char *content = "malformed-etag";
  19439. {
  19440. std::ofstream ofs(fname);
  19441. ofs << content;
  19442. ASSERT_TRUE(ofs.good());
  19443. }
  19444. Server svr;
  19445. svr.set_mount_point("/static", ".");
  19446. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19447. svr.wait_until_ready();
  19448. Client cli(HOST, PORT);
  19449. // baseline: should get 200 and an ETag
  19450. auto res1 = cli.Get("/static/etag_malformed.txt");
  19451. ASSERT_TRUE(res1);
  19452. ASSERT_EQ(200, res1->status);
  19453. ASSERT_TRUE(res1->has_header("ETag"));
  19454. // Malformed ETag value (missing quotes) should be treated as non-matching
  19455. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19456. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19457. ASSERT_TRUE(res_bad);
  19458. EXPECT_EQ(200, res_bad->status);
  19459. // Whitespace-only header value should be considered invalid / non-matching
  19460. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19461. "Host: localhost\r\n"
  19462. "If-None-Match: \r\n"
  19463. "Connection: close\r\n"
  19464. "\r\n";
  19465. std::string out;
  19466. ASSERT_TRUE(send_request(5, raw_req, &out));
  19467. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19468. svr.stop();
  19469. t.join();
  19470. std::remove(fname);
  19471. }
  19472. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19473. using namespace httplib;
  19474. const char *fname = "ims_invalid_format.txt";
  19475. const char *content = "ims-bad-format";
  19476. {
  19477. std::ofstream ofs(fname);
  19478. ofs << content;
  19479. ASSERT_TRUE(ofs.good());
  19480. }
  19481. Server svr;
  19482. svr.set_mount_point("/static", ".");
  19483. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19484. svr.wait_until_ready();
  19485. Client cli(HOST, PORT);
  19486. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19487. ASSERT_TRUE(res1);
  19488. ASSERT_EQ(200, res1->status);
  19489. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19490. // If-Modified-Since with invalid format should not result in 304
  19491. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19492. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19493. ASSERT_TRUE(res_bad);
  19494. EXPECT_EQ(200, res_bad->status);
  19495. // If-Range with invalid date format should be treated as mismatch -> full
  19496. // content (200)
  19497. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19498. {"If-Range", "invalid-date"}};
  19499. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19500. ASSERT_TRUE(res_ifrange);
  19501. EXPECT_EQ(200, res_ifrange->status);
  19502. svr.stop();
  19503. t.join();
  19504. std::remove(fname);
  19505. }
  19506. TEST(ETagTest, IfRangeWithMalformedETag) {
  19507. using namespace httplib;
  19508. const char *fname = "ifrange_malformed.txt";
  19509. const std::string content = "0123456789";
  19510. {
  19511. std::ofstream ofs(fname);
  19512. ofs << content;
  19513. ASSERT_TRUE(ofs.good());
  19514. }
  19515. Server svr;
  19516. svr.set_mount_point("/static", ".");
  19517. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19518. svr.wait_until_ready();
  19519. Client cli(HOST, PORT);
  19520. // First request: get ETag
  19521. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19522. ASSERT_TRUE(res1);
  19523. ASSERT_EQ(200, res1->status);
  19524. ASSERT_TRUE(res1->has_header("ETag"));
  19525. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19526. // full content (200)
  19527. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19528. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19529. ASSERT_TRUE(res2);
  19530. EXPECT_EQ(200, res2->status);
  19531. EXPECT_EQ(content, res2->body);
  19532. svr.stop();
  19533. t.join();
  19534. std::remove(fname);
  19535. }
  19536. TEST(ETagTest, ExtremeLargeDateValues) {
  19537. using namespace httplib;
  19538. const char *fname = "ims_extreme_date.txt";
  19539. const char *content = "ims-extreme-date";
  19540. {
  19541. std::ofstream ofs(fname);
  19542. ofs << content;
  19543. ASSERT_TRUE(ofs.good());
  19544. }
  19545. Server svr;
  19546. svr.set_mount_point("/static", ".");
  19547. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19548. svr.wait_until_ready();
  19549. Client cli(HOST, PORT);
  19550. auto res1 = cli.Get(std::string("/static/") + fname);
  19551. ASSERT_TRUE(res1);
  19552. ASSERT_EQ(200, res1->status);
  19553. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19554. // Extremely large year that may overflow date parsing routines.
  19555. Headers h_large_date = {
  19556. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19557. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19558. ASSERT_TRUE(res_bad);
  19559. // Expect server to treat this as invalid/mismatch and return full content
  19560. EXPECT_EQ(200, res_bad->status);
  19561. // If-Range with extremely large date should be treated as mismatch -> full
  19562. // content (200)
  19563. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19564. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19565. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19566. ASSERT_TRUE(res_ifrange);
  19567. EXPECT_EQ(200, res_ifrange->status);
  19568. svr.stop();
  19569. t.join();
  19570. std::remove(fname);
  19571. }
  19572. TEST(ETagTest, NegativeFileModificationTime) {
  19573. using namespace httplib;
  19574. const char *fname = "ims_negative_mtime.txt";
  19575. const std::string content = "negative-mtime";
  19576. {
  19577. std::ofstream ofs(fname);
  19578. ofs << content;
  19579. ASSERT_TRUE(ofs.good());
  19580. }
  19581. // Try to set file mtime to a negative value. This may fail on some
  19582. // platforms/filesystems; if it fails, the test will still verify server
  19583. // behaves safely by performing a regular conditional request.
  19584. #if defined(__APPLE__) || defined(__linux__)
  19585. bool set_negative = false;
  19586. do {
  19587. struct timeval times[2];
  19588. // access time: now
  19589. times[0].tv_sec = time(nullptr);
  19590. times[0].tv_usec = 0;
  19591. // modification time: negative (e.g., -1)
  19592. times[1].tv_sec = -1;
  19593. times[1].tv_usec = 0;
  19594. if (utimes(fname, times) == 0) { set_negative = true; }
  19595. } while (0);
  19596. #else
  19597. bool set_negative = false;
  19598. #endif
  19599. Server svr;
  19600. svr.set_mount_point("/static", ".");
  19601. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19602. svr.wait_until_ready();
  19603. Client cli(HOST, PORT);
  19604. auto res1 = cli.Get(std::string("/static/") + fname);
  19605. ASSERT_TRUE(res1);
  19606. ASSERT_EQ(200, res1->status);
  19607. bool has_last_modified = res1->has_header("Last-Modified");
  19608. std::string last_modified;
  19609. if (has_last_modified) {
  19610. last_modified = res1->get_header_value("Last-Modified");
  19611. }
  19612. if (set_negative) {
  19613. // If we successfully set a negative mtime, ensure server returns a
  19614. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  19615. // with an old date and ensure server handles it without crash.
  19616. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  19617. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  19618. ASSERT_TRUE(res2);
  19619. // Behavior may vary; at minimum ensure server responds (200 or 304).
  19620. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  19621. } else {
  19622. // Could not set negative mtime on this platform; fall back to verifying
  19623. // that normal invalid/malformed dates are treated safely (non-304).
  19624. Headers h_bad_date = {
  19625. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19626. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  19627. ASSERT_TRUE(res_bad);
  19628. EXPECT_EQ(200, res_bad->status);
  19629. }
  19630. svr.stop();
  19631. t.join();
  19632. std::remove(fname);
  19633. }
  19634. //==============================================================================
  19635. // Integration Tests with Server
  19636. //==============================================================================
  19637. class SSEIntegrationTest : public ::testing::Test {
  19638. protected:
  19639. void SetUp() override {
  19640. stop_server_.store(false);
  19641. events_.clear();
  19642. server_ = httplib::detail::make_unique<Server>();
  19643. setup_server();
  19644. start_server();
  19645. }
  19646. void TearDown() override {
  19647. stop_server_.store(true);
  19648. event_cv_.notify_all();
  19649. server_->stop();
  19650. if (server_thread_.joinable()) { server_thread_.join(); }
  19651. }
  19652. void setup_server() {
  19653. // Simple SSE endpoint
  19654. server_->Get("/events", [this](const Request &req, Response &res) {
  19655. auto last_id = req.get_header_value("Last-Event-ID");
  19656. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  19657. res.set_chunked_content_provider(
  19658. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  19659. std::unique_lock<std::mutex> lock(event_mutex_);
  19660. if (event_cv_.wait_for(
  19661. lock, std::chrono::milliseconds(200), [this] {
  19662. return !events_.empty() || stop_server_.load();
  19663. })) {
  19664. if (stop_server_.load()) { return false; }
  19665. if (!events_.empty()) {
  19666. std::string event = events_.front();
  19667. events_.erase(events_.begin());
  19668. sink.write(event.data(), event.size());
  19669. return true;
  19670. }
  19671. }
  19672. return !stop_server_.load();
  19673. });
  19674. });
  19675. // Endpoint that returns error
  19676. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  19677. res.status = 500;
  19678. res.set_content("Internal Server Error", "text/plain");
  19679. });
  19680. // Endpoint for custom event types
  19681. server_->Get("/custom-events", [](const Request &, Response &res) {
  19682. res.set_chunked_content_provider(
  19683. "text/event-stream", [](size_t offset, DataSink &sink) {
  19684. if (offset == 0) {
  19685. std::string event = "event: update\ndata: updated\n\n"
  19686. "event: delete\ndata: deleted\n\n";
  19687. sink.write(event.data(), event.size());
  19688. }
  19689. return false; // End stream after sending
  19690. });
  19691. });
  19692. }
  19693. void start_server() {
  19694. port_ = server_->bind_to_any_port(HOST);
  19695. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19696. // Wait for server to start
  19697. while (!server_->is_running()) {
  19698. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19699. }
  19700. }
  19701. int get_port() const { return port_; }
  19702. void send_event(const std::string &event) {
  19703. std::lock_guard<std::mutex> lock(event_mutex_);
  19704. events_.push_back(event);
  19705. event_cv_.notify_all();
  19706. }
  19707. std::unique_ptr<Server> server_;
  19708. std::thread server_thread_;
  19709. std::mutex event_mutex_;
  19710. std::condition_variable event_cv_;
  19711. std::vector<std::string> events_;
  19712. std::atomic<bool> stop_server_{false};
  19713. std::string last_received_event_id_;
  19714. int port_ = 0;
  19715. };
  19716. //==============================================================================
  19717. // SSE Parsing Tests
  19718. //==============================================================================
  19719. class SSEParsingTest : public SSEIntegrationTest {
  19720. protected:
  19721. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  19722. // A trailing sentinel event tells when the whole stream has been parsed.
  19723. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  19724. auto body = stream + "event: end\ndata: end\n\n";
  19725. server_->Get("/parse", [body](const Request &, Response &res) {
  19726. res.set_content(body, "text/event-stream");
  19727. });
  19728. return collect("/parse");
  19729. }
  19730. // Runs SSEClient against path until an "end" event arrives and returns the
  19731. // messages dispatched before it
  19732. std::vector<sse::SSEMessage> collect(const std::string &path) {
  19733. Client client(HOST, get_port());
  19734. sse::SSEClient sse(client, path);
  19735. std::mutex mutex;
  19736. std::condition_variable cv;
  19737. std::vector<sse::SSEMessage> messages;
  19738. auto done = false;
  19739. sse.on_message([&](const sse::SSEMessage &msg) {
  19740. std::lock_guard<std::mutex> lock(mutex);
  19741. // Ignore a replay from a reconnect that races with stop()
  19742. if (!done) { messages.push_back(msg); }
  19743. });
  19744. sse.on_event("end", [&](const sse::SSEMessage &) {
  19745. std::lock_guard<std::mutex> lock(mutex);
  19746. done = true;
  19747. cv.notify_all();
  19748. });
  19749. sse.set_reconnect_interval(100);
  19750. sse.start_async();
  19751. {
  19752. std::unique_lock<std::mutex> lock(mutex);
  19753. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  19754. }
  19755. sse.stop();
  19756. EXPECT_TRUE(done);
  19757. return messages;
  19758. }
  19759. };
  19760. TEST_F(SSEParsingTest, SingleLineData) {
  19761. auto msgs = parse("data: hello\n\n");
  19762. ASSERT_EQ(msgs.size(), 1u);
  19763. EXPECT_EQ(msgs[0].data, "hello");
  19764. EXPECT_EQ(msgs[0].event, "message");
  19765. }
  19766. TEST_F(SSEParsingTest, MultiLineData) {
  19767. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  19768. ASSERT_EQ(msgs.size(), 1u);
  19769. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  19770. }
  19771. TEST_F(SSEParsingTest, CustomEventType) {
  19772. auto msgs = parse("event: update\ndata: payload\n\n");
  19773. ASSERT_EQ(msgs.size(), 1u);
  19774. EXPECT_EQ(msgs[0].event, "update");
  19775. EXPECT_EQ(msgs[0].data, "payload");
  19776. }
  19777. TEST_F(SSEParsingTest, EventIdHandling) {
  19778. auto msgs = parse("id: 12345\ndata: test\n\n");
  19779. ASSERT_EQ(msgs.size(), 1u);
  19780. EXPECT_EQ(msgs[0].id, "12345");
  19781. }
  19782. TEST_F(SSEParsingTest, EmptyEventId) {
  19783. auto msgs = parse("id:\ndata: test\n\n");
  19784. ASSERT_EQ(msgs.size(), 1u);
  19785. EXPECT_EQ(msgs[0].id, "");
  19786. }
  19787. TEST_F(SSEParsingTest, CommentsIgnored) {
  19788. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  19789. ASSERT_EQ(msgs.size(), 1u);
  19790. EXPECT_EQ(msgs[0].data, "hello");
  19791. EXPECT_EQ(msgs[0].event, "message");
  19792. }
  19793. TEST_F(SSEParsingTest, ColonInValue) {
  19794. auto msgs = parse("data: hello:world:test\n\n");
  19795. ASSERT_EQ(msgs.size(), 1u);
  19796. EXPECT_EQ(msgs[0].data, "hello:world:test");
  19797. }
  19798. TEST_F(SSEParsingTest, FieldNameOnly) {
  19799. // A line without a colon is a field name with an empty value
  19800. auto msgs = parse("data\n\n");
  19801. ASSERT_EQ(msgs.size(), 1u);
  19802. EXPECT_EQ(msgs[0].data, "");
  19803. }
  19804. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  19805. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  19806. ASSERT_EQ(msgs.size(), 1u);
  19807. EXPECT_EQ(msgs[0].event, "update");
  19808. EXPECT_EQ(msgs[0].data, "hello");
  19809. }
  19810. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  19811. auto msgs = parse("data\r\n\r\n");
  19812. ASSERT_EQ(msgs.size(), 1u);
  19813. EXPECT_EQ(msgs[0].data, "");
  19814. }
  19815. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  19816. auto msgs = parse("event: update\rdata: hello\r\r");
  19817. ASSERT_EQ(msgs.size(), 1u);
  19818. EXPECT_EQ(msgs[0].event, "update");
  19819. EXPECT_EQ(msgs[0].data, "hello");
  19820. }
  19821. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  19822. // Chunk boundaries fall inside every \r\n and right before the first one
  19823. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  19824. "\n\r", "\nevent: end\ndata: end\n\n"};
  19825. server_->Get("/split", [chunks](const Request &, Response &res) {
  19826. auto i = std::make_shared<size_t>(0);
  19827. res.set_chunked_content_provider(
  19828. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  19829. if (*i == chunks.size()) {
  19830. sink.done();
  19831. } else {
  19832. sink.write(chunks[*i].data(), chunks[*i].size());
  19833. (*i)++;
  19834. }
  19835. return true;
  19836. });
  19837. });
  19838. auto msgs = collect("/split");
  19839. ASSERT_EQ(msgs.size(), 1u);
  19840. EXPECT_EQ(msgs[0].event, "update");
  19841. EXPECT_EQ(msgs[0].data, "hello");
  19842. }
  19843. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  19844. // Only a BOM at the start of the stream is ignored
  19845. auto msgs = parse("\xEF\xBB\xBF"
  19846. "data: first\n\n"
  19847. "\xEF\xBB\xBF"
  19848. "data: second\n\n");
  19849. ASSERT_EQ(msgs.size(), 1u);
  19850. EXPECT_EQ(msgs[0].data, "first");
  19851. }
  19852. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  19853. auto msgs = parse("unknown: value\ndata: hello\n\n");
  19854. ASSERT_EQ(msgs.size(), 1u);
  19855. EXPECT_EQ(msgs[0].data, "hello");
  19856. EXPECT_EQ(msgs[0].event, "message");
  19857. }
  19858. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  19859. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  19860. ASSERT_EQ(msgs.size(), 2u);
  19861. EXPECT_EQ(msgs[0].data, "hello");
  19862. EXPECT_EQ(msgs[1].data, "hello");
  19863. }
  19864. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  19865. // An event without data is not dispatched, and its type must not leak
  19866. // into the next event
  19867. auto msgs = parse("event: update\n\ndata: hello\n\n");
  19868. ASSERT_EQ(msgs.size(), 1u);
  19869. EXPECT_EQ(msgs[0].event, "message");
  19870. EXPECT_EQ(msgs[0].data, "hello");
  19871. }
  19872. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  19873. // The first connection sends only an id; the second echoes back the
  19874. // Last-Event-ID it was reconnected with
  19875. std::atomic<int> connection_count{0};
  19876. server_->Get("/id-only", [&](const Request &req, Response &res) {
  19877. if (connection_count++ == 0) {
  19878. res.set_content("id: 42\n\n", "text/event-stream");
  19879. } else {
  19880. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19881. "\n\nevent: end\ndata: end\n\n",
  19882. "text/event-stream");
  19883. }
  19884. });
  19885. auto msgs = collect("/id-only");
  19886. ASSERT_EQ(msgs.size(), 1u);
  19887. EXPECT_EQ(msgs[0].data, "42");
  19888. }
  19889. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  19890. // The first connection sets an id and then clears it with an empty one; the
  19891. // second reports whether it was reconnected with a Last-Event-ID
  19892. std::atomic<int> connection_count{0};
  19893. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  19894. if (connection_count++ == 0) {
  19895. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  19896. "text/event-stream");
  19897. } else {
  19898. res.set_content(
  19899. std::string("data: ") +
  19900. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  19901. "\n\nevent: end\ndata: end\n\n",
  19902. "text/event-stream");
  19903. }
  19904. });
  19905. auto msgs = collect("/id-clear");
  19906. ASSERT_EQ(msgs.size(), 3u);
  19907. EXPECT_EQ(msgs[0].id, "1");
  19908. EXPECT_EQ(msgs[1].id, "");
  19909. EXPECT_EQ(msgs[2].data, "not sent");
  19910. }
  19911. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  19912. // The first connection sets an id and then sends ids that cannot be carried
  19913. // in a header; the second echoes back the Last-Event-ID it was reconnected
  19914. // with
  19915. std::atomic<int> connection_count{0};
  19916. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  19917. if (connection_count++ == 0) {
  19918. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  19919. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  19920. "text/event-stream");
  19921. } else {
  19922. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19923. "\n\nevent: end\ndata: end\n\n",
  19924. "text/event-stream");
  19925. }
  19926. });
  19927. auto msgs = collect("/id-unsendable");
  19928. ASSERT_EQ(msgs.size(), 1u);
  19929. EXPECT_EQ(msgs[0].data, "42");
  19930. }
  19931. TEST_F(SSEParsingTest, CompleteEventParsing) {
  19932. auto msgs = parse("event: notification\nid: evt-42\n"
  19933. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  19934. ASSERT_EQ(msgs.size(), 1u);
  19935. EXPECT_EQ(msgs[0].event, "notification");
  19936. EXPECT_EQ(msgs[0].id, "evt-42");
  19937. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  19938. }
  19939. TEST(SSEMessageTest, Clear) {
  19940. sse::SSEMessage msg;
  19941. msg.event = "custom";
  19942. msg.data = "some data";
  19943. msg.id = "123";
  19944. msg.clear();
  19945. EXPECT_EQ(msg.event, "message");
  19946. EXPECT_EQ(msg.data, "");
  19947. EXPECT_EQ(msg.id, "");
  19948. }
  19949. //==============================================================================
  19950. // SSE Integration Tests
  19951. //==============================================================================
  19952. // Test: Successful connection and on_open callback
  19953. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  19954. // Add a simple endpoint that sends one event and closes
  19955. server_->Get("/simple-event", [](const Request &, Response &res) {
  19956. res.set_chunked_content_provider(
  19957. "text/event-stream", [](size_t offset, DataSink &sink) {
  19958. if (offset == 0) {
  19959. std::string event = "data: hello\n\n";
  19960. sink.write(event.data(), event.size());
  19961. }
  19962. return false; // Close stream after sending
  19963. });
  19964. });
  19965. Client client("localhost", get_port());
  19966. sse::SSEClient sse(client, "/simple-event");
  19967. std::atomic<bool> open_called{false};
  19968. std::atomic<bool> message_received{false};
  19969. sse.on_open([&open_called]() { open_called.store(true); });
  19970. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  19971. if (msg.data == "hello") { message_received.store(true); }
  19972. });
  19973. sse.set_reconnect_interval(100);
  19974. sse.set_max_reconnect_attempts(1);
  19975. // Start async
  19976. sse.start_async();
  19977. // Wait for message to be processed
  19978. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19979. sse.stop();
  19980. EXPECT_TRUE(open_called.load());
  19981. EXPECT_TRUE(message_received.load());
  19982. }
  19983. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  19984. // A data line that never ends.
  19985. server_->Get("/endless-line", [](const Request &, Response &res) {
  19986. res.set_chunked_content_provider(
  19987. "text/event-stream", [](size_t offset, DataSink &sink) {
  19988. if (offset == 0) { sink.write("data: ", 6); }
  19989. std::string chunk(64 * 1024, 'A');
  19990. return sink.write(chunk.data(), chunk.size());
  19991. });
  19992. });
  19993. Client client("localhost", get_port());
  19994. // A stream that may run forever, so that only the event is bounded.
  19995. client.set_payload_max_length(0);
  19996. sse::SSEClient sse(client, "/endless-line");
  19997. std::atomic<bool> too_long{false};
  19998. sse.on_error([&](Error err) {
  19999. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  20000. });
  20001. sse.set_max_reconnect_attempts(1);
  20002. sse.start_async();
  20003. for (int i = 0; i < 500 && !too_long; i++) {
  20004. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20005. }
  20006. sse.stop();
  20007. EXPECT_TRUE(too_long);
  20008. }
  20009. // Test: on_message callback
  20010. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  20011. // Endpoint that sends multiple events then closes
  20012. server_->Get("/multi-event", [](const Request &, Response &res) {
  20013. res.set_chunked_content_provider(
  20014. "text/event-stream", [](size_t offset, DataSink &sink) {
  20015. if (offset == 0) {
  20016. std::string events = "data: message1\n\ndata: message2\n\n";
  20017. sink.write(events.data(), events.size());
  20018. }
  20019. return false;
  20020. });
  20021. });
  20022. Client client("localhost", get_port());
  20023. sse::SSEClient sse(client, "/multi-event");
  20024. std::vector<std::string> received_messages;
  20025. std::mutex messages_mutex;
  20026. sse.on_message([&](const sse::SSEMessage &msg) {
  20027. std::lock_guard<std::mutex> lock(messages_mutex);
  20028. received_messages.push_back(msg.data);
  20029. });
  20030. sse.set_reconnect_interval(100);
  20031. sse.set_max_reconnect_attempts(1);
  20032. sse.start_async();
  20033. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20034. sse.stop();
  20035. std::lock_guard<std::mutex> lock(messages_mutex);
  20036. EXPECT_GE(received_messages.size(), 2u);
  20037. if (received_messages.size() >= 2) {
  20038. EXPECT_EQ(received_messages[0], "message1");
  20039. EXPECT_EQ(received_messages[1], "message2");
  20040. }
  20041. }
  20042. // Test: on_event for specific types
  20043. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  20044. Client client("localhost", get_port());
  20045. sse::SSEClient sse(client, "/custom-events");
  20046. std::atomic<bool> update_received{false};
  20047. std::atomic<bool> delete_received{false};
  20048. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  20049. if (msg.data == "updated") { update_received.store(true); }
  20050. });
  20051. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  20052. if (msg.data == "deleted") { delete_received.store(true); }
  20053. });
  20054. sse.set_max_reconnect_attempts(1);
  20055. sse.start_async();
  20056. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  20057. sse.stop();
  20058. EXPECT_TRUE(update_received.load());
  20059. EXPECT_TRUE(delete_received.load());
  20060. }
  20061. // Test: on_error callback on connection failure
  20062. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  20063. // Connect to a non-existent port
  20064. Client client("localhost", 59999);
  20065. sse::SSEClient sse(client, "/events");
  20066. std::atomic<bool> error_called{false};
  20067. Error received_error = Error::Success;
  20068. sse.on_error([&](Error err) {
  20069. error_called.store(true);
  20070. received_error = err;
  20071. });
  20072. sse.set_reconnect_interval(50);
  20073. sse.set_max_reconnect_attempts(1);
  20074. sse.start_async();
  20075. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20076. sse.stop();
  20077. EXPECT_TRUE(error_called.load());
  20078. EXPECT_NE(received_error, Error::Success);
  20079. }
  20080. // Test: Last-Event-ID header sent on reconnect
  20081. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  20082. // Endpoint that sends event with ID
  20083. server_->Get("/event-with-id", [](const Request &, Response &res) {
  20084. res.set_chunked_content_provider(
  20085. "text/event-stream", [](size_t offset, DataSink &sink) {
  20086. if (offset == 0) {
  20087. std::string event = "id: evt-123\ndata: test\n\n";
  20088. sink.write(event.data(), event.size());
  20089. }
  20090. return false;
  20091. });
  20092. });
  20093. Client client("localhost", get_port());
  20094. sse::SSEClient sse(client, "/event-with-id");
  20095. std::atomic<bool> id_received{false};
  20096. sse.on_message([&](const sse::SSEMessage &msg) {
  20097. if (!msg.id.empty()) { id_received.store(true); }
  20098. });
  20099. sse.set_reconnect_interval(100);
  20100. sse.set_max_reconnect_attempts(1);
  20101. sse.start_async();
  20102. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20103. sse.stop();
  20104. EXPECT_TRUE(id_received.load());
  20105. EXPECT_EQ(sse.last_event_id(), "evt-123");
  20106. }
  20107. // Test: Manual stop
  20108. TEST_F(SSEIntegrationTest, ManualStop) {
  20109. // Endpoint that sends one event and stays open briefly
  20110. std::atomic<bool> handler_running{true};
  20111. server_->Get("/stay-open", [&handler_running](const Request &,
  20112. Response &res) {
  20113. res.set_chunked_content_provider(
  20114. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  20115. if (offset == 0) {
  20116. std::string event = "data: connected\n\n";
  20117. sink.write(event.data(), event.size());
  20118. }
  20119. // Keep connection open while handler_running is true
  20120. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  20121. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20122. }
  20123. return false;
  20124. });
  20125. });
  20126. Client client("localhost", get_port());
  20127. sse::SSEClient sse(client, "/stay-open");
  20128. std::atomic<bool> connected{false};
  20129. sse.on_open([&connected]() { connected.store(true); });
  20130. sse.set_reconnect_interval(100);
  20131. sse.set_max_reconnect_attempts(1);
  20132. sse.start_async();
  20133. // Wait for connection to establish
  20134. for (int i = 0; i < 20 && !connected.load(); ++i) {
  20135. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20136. }
  20137. EXPECT_TRUE(connected.load());
  20138. EXPECT_TRUE(sse.is_connected());
  20139. // Signal handler to stop
  20140. handler_running.store(false);
  20141. // Stop SSE client
  20142. sse.stop();
  20143. EXPECT_FALSE(sse.is_connected());
  20144. }
  20145. // Test: SSEClient with custom headers
  20146. TEST_F(SSEIntegrationTest, CustomHeaders) {
  20147. // Setup a server endpoint that checks for custom header
  20148. std::atomic<bool> header_received{false};
  20149. server_->Get("/header-check", [&](const Request &req, Response &res) {
  20150. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  20151. header_received.store(true);
  20152. }
  20153. res.set_chunked_content_provider("text/event-stream",
  20154. [](size_t, DataSink &) { return false; });
  20155. });
  20156. Client client("localhost", get_port());
  20157. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20158. sse::SSEClient sse(client, "/header-check", headers);
  20159. sse.set_max_reconnect_attempts(1);
  20160. sse.start_async();
  20161. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20162. sse.stop();
  20163. EXPECT_TRUE(header_received.load());
  20164. }
  20165. // Test: Reconnect interval configuration
  20166. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  20167. Client client("localhost", get_port());
  20168. sse::SSEClient sse(client, "/events");
  20169. auto &result = sse.set_reconnect_interval(500);
  20170. // Builder pattern should return reference to self
  20171. EXPECT_EQ(&result, &sse);
  20172. }
  20173. // Test: Max reconnect attempts
  20174. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  20175. // Connect to non-existent port to force reconnects
  20176. Client client("localhost", 59998);
  20177. sse::SSEClient sse(client, "/events");
  20178. std::atomic<int> error_count{0};
  20179. sse.on_error([&](Error) { error_count.fetch_add(1); });
  20180. sse.set_reconnect_interval(50);
  20181. sse.set_max_reconnect_attempts(2);
  20182. auto start = std::chrono::steady_clock::now();
  20183. sse.start(); // Blocking call
  20184. auto end = std::chrono::steady_clock::now();
  20185. // Should have stopped after 2 failed attempts
  20186. EXPECT_GE(error_count.load(), 2);
  20187. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  20188. auto duration =
  20189. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  20190. #ifdef _WIN32
  20191. // Windows is much slower for socket connection failures
  20192. EXPECT_LT(duration.count(), 7000);
  20193. #else
  20194. EXPECT_LT(duration.count(), 1000);
  20195. #endif
  20196. }
  20197. // Test: Multi-line data in integration
  20198. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  20199. // Endpoint with multi-line data
  20200. server_->Get("/multiline-data", [](const Request &, Response &res) {
  20201. res.set_chunked_content_provider(
  20202. "text/event-stream", [](size_t offset, DataSink &sink) {
  20203. if (offset == 0) {
  20204. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  20205. sink.write(event.data(), event.size());
  20206. }
  20207. return false;
  20208. });
  20209. });
  20210. Client client("localhost", get_port());
  20211. sse::SSEClient sse(client, "/multiline-data");
  20212. std::string received_data;
  20213. std::mutex data_mutex;
  20214. sse.on_message([&](const sse::SSEMessage &msg) {
  20215. std::lock_guard<std::mutex> lock(data_mutex);
  20216. received_data = msg.data;
  20217. });
  20218. sse.set_reconnect_interval(100);
  20219. sse.set_max_reconnect_attempts(1);
  20220. sse.start_async();
  20221. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20222. sse.stop();
  20223. std::lock_guard<std::mutex> lock(data_mutex);
  20224. EXPECT_EQ(received_data, "line1\nline2\nline3");
  20225. }
  20226. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  20227. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  20228. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  20229. DataSink &sink) {
  20230. if (offset == 0) {
  20231. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  20232. sink.write(events.data(), events.size());
  20233. }
  20234. return false;
  20235. });
  20236. });
  20237. Client client("localhost", get_port());
  20238. sse::SSEClient sse(client, "/empty-data-lines");
  20239. std::mutex mutex;
  20240. std::condition_variable cv;
  20241. std::vector<std::string> received;
  20242. sse.on_message([&](const sse::SSEMessage &msg) {
  20243. std::lock_guard<std::mutex> lock(mutex);
  20244. received.push_back(msg.data);
  20245. cv.notify_all();
  20246. });
  20247. sse.set_max_reconnect_attempts(1);
  20248. sse.start_async();
  20249. {
  20250. std::unique_lock<std::mutex> lock(mutex);
  20251. cv.wait_for(lock, std::chrono::seconds(2),
  20252. [&] { return received.size() >= 3; });
  20253. }
  20254. sse.stop();
  20255. ASSERT_GE(received.size(), 3u);
  20256. EXPECT_EQ(received[0], "");
  20257. EXPECT_EQ(received[1], "\nhello");
  20258. EXPECT_EQ(received[2], "");
  20259. }
  20260. // Test: Auto-reconnect after server disconnection
  20261. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  20262. std::atomic<int> connection_count{0};
  20263. std::atomic<int> message_count{0};
  20264. // Endpoint that sends one event and closes, forcing reconnect
  20265. server_->Get("/reconnect-test",
  20266. [&connection_count](const Request &, Response &res) {
  20267. connection_count.fetch_add(1);
  20268. res.set_chunked_content_provider(
  20269. "text/event-stream", [](size_t offset, DataSink &sink) {
  20270. if (offset == 0) {
  20271. std::string event = "data: hello\n\n";
  20272. sink.write(event.data(), event.size());
  20273. }
  20274. return false; // Close connection after sending
  20275. });
  20276. });
  20277. Client client("localhost", get_port());
  20278. sse::SSEClient sse(client, "/reconnect-test");
  20279. sse.on_message([&message_count](const sse::SSEMessage &) {
  20280. message_count.fetch_add(1);
  20281. });
  20282. sse.set_reconnect_interval(100);
  20283. sse.set_max_reconnect_attempts(3);
  20284. sse.start_async();
  20285. // Wait long enough for multiple reconnects
  20286. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20287. sse.stop();
  20288. // Should have connected multiple times (initial + reconnects)
  20289. EXPECT_GE(connection_count.load(), 2);
  20290. // Should have received messages from multiple connections
  20291. EXPECT_GE(message_count.load(), 2);
  20292. }
  20293. // Test: A retry field that is not all ASCII digits is ignored
  20294. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  20295. std::atomic<int> connection_count{0};
  20296. server_->Get("/bad-retry",
  20297. [&connection_count](const Request &, Response &res) {
  20298. connection_count.fetch_add(1);
  20299. res.set_chunked_content_provider(
  20300. "text/event-stream", [](size_t offset, DataSink &sink) {
  20301. if (offset == 0) {
  20302. std::string event = "retry: -1\ndata: hello\n\n";
  20303. sink.write(event.data(), event.size());
  20304. }
  20305. return false;
  20306. });
  20307. });
  20308. Client client("localhost", get_port());
  20309. sse::SSEClient sse(client, "/bad-retry");
  20310. sse.set_reconnect_interval(10000);
  20311. sse.start_async();
  20312. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20313. sse.stop();
  20314. EXPECT_EQ(connection_count.load(), 1);
  20315. }
  20316. // Test: A retry field of all ASCII digits sets the reconnection time
  20317. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  20318. std::mutex mutex;
  20319. std::condition_variable cv;
  20320. std::vector<std::chrono::steady_clock::time_point> connected_at;
  20321. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  20322. {
  20323. std::lock_guard<std::mutex> lock(mutex);
  20324. connected_at.push_back(std::chrono::steady_clock::now());
  20325. cv.notify_all();
  20326. }
  20327. res.set_chunked_content_provider(
  20328. "text/event-stream", [](size_t offset, DataSink &sink) {
  20329. if (offset == 0) {
  20330. std::string event = "retry: 0\ndata: hello\n\n";
  20331. sink.write(event.data(), event.size());
  20332. }
  20333. return false;
  20334. });
  20335. });
  20336. Client client("localhost", get_port());
  20337. sse::SSEClient sse(client, "/zero-retry");
  20338. sse.set_reconnect_interval(10000);
  20339. sse.start_async();
  20340. {
  20341. std::unique_lock<std::mutex> lock(mutex);
  20342. cv.wait_for(lock, std::chrono::seconds(5),
  20343. [&] { return connected_at.size() >= 2; });
  20344. }
  20345. sse.stop();
  20346. // The server-supplied interval is applied, but never below 100ms, so
  20347. // "retry: 0" does not cause a busy reconnect loop
  20348. std::lock_guard<std::mutex> lock(mutex);
  20349. ASSERT_GE(connected_at.size(), 2u);
  20350. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  20351. connected_at[1] - connected_at[0])
  20352. .count();
  20353. EXPECT_GE(interval_ms, 100);
  20354. }
  20355. // Test: Last-Event-ID sent on reconnect
  20356. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  20357. std::atomic<int> connection_count{0};
  20358. std::vector<std::string> received_last_event_ids;
  20359. std::mutex id_mutex;
  20360. // Endpoint that checks Last-Event-ID header and sends event with ID
  20361. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  20362. int conn = connection_count.fetch_add(1);
  20363. // Capture the Last-Event-ID header from each connection
  20364. {
  20365. std::lock_guard<std::mutex> lock(id_mutex);
  20366. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  20367. }
  20368. res.set_chunked_content_provider(
  20369. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  20370. if (offset == 0) {
  20371. std::string event =
  20372. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  20373. sink.write(event.data(), event.size());
  20374. }
  20375. return false;
  20376. });
  20377. });
  20378. Client client("localhost", get_port());
  20379. sse::SSEClient sse(client, "/reconnect-with-id");
  20380. sse.set_reconnect_interval(100);
  20381. sse.set_max_reconnect_attempts(3);
  20382. sse.start_async();
  20383. // Wait for at least 2 connections
  20384. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20385. sse.stop();
  20386. // Verify behavior
  20387. std::lock_guard<std::mutex> lock(id_mutex);
  20388. EXPECT_GE(received_last_event_ids.size(), 2u);
  20389. // First connection should have no Last-Event-ID
  20390. if (!received_last_event_ids.empty()) {
  20391. EXPECT_EQ(received_last_event_ids[0], "");
  20392. }
  20393. // Second connection should have Last-Event-ID from first connection
  20394. if (received_last_event_ids.size() >= 2) {
  20395. EXPECT_EQ(received_last_event_ids[1], "event-0");
  20396. }
  20397. }
  20398. // Test: set_headers updates headers used on reconnect
  20399. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  20400. std::vector<std::string> received_tokens;
  20401. std::mutex token_mutex;
  20402. // Endpoint that captures Authorization header
  20403. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  20404. {
  20405. std::lock_guard<std::mutex> lock(token_mutex);
  20406. received_tokens.push_back(req.get_header_value("Authorization"));
  20407. }
  20408. res.set_chunked_content_provider(
  20409. "text/event-stream", [](size_t offset, DataSink &sink) {
  20410. if (offset == 0) {
  20411. std::string event = "data: hello\n\n";
  20412. sink.write(event.data(), event.size());
  20413. }
  20414. return false; // Close connection to trigger reconnect
  20415. });
  20416. });
  20417. Client client("localhost", get_port());
  20418. Headers headers = {{"Authorization", "Bearer old-token"}};
  20419. sse::SSEClient sse(client, "/auth-check", headers);
  20420. // Update headers on each successful connection
  20421. sse.on_open(
  20422. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  20423. sse.set_reconnect_interval(100);
  20424. sse.set_max_reconnect_attempts(3);
  20425. sse.start_async();
  20426. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20427. sse.stop();
  20428. std::lock_guard<std::mutex> lock(token_mutex);
  20429. ASSERT_GE(received_tokens.size(), 2u);
  20430. // First connection uses original header
  20431. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  20432. // Second connection uses updated header from set_headers
  20433. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20434. }
  20435. // Test: 401 allows reconnection (so on_error can refresh headers)
  20436. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20437. std::atomic<int> connection_count{0};
  20438. // Endpoint: returns 401 on first attempt, 200 on second
  20439. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20440. int conn = connection_count.fetch_add(1);
  20441. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20442. res.status = StatusCode::Unauthorized_401;
  20443. res.set_content("Unauthorized", "text/plain");
  20444. return;
  20445. }
  20446. res.set_chunked_content_provider(
  20447. "text/event-stream", [](size_t offset, DataSink &sink) {
  20448. if (offset == 0) {
  20449. std::string event = "data: authenticated\n\n";
  20450. sink.write(event.data(), event.size());
  20451. }
  20452. return false;
  20453. });
  20454. });
  20455. Client client("localhost", get_port());
  20456. Headers headers = {{"Authorization", "Bearer expired"}};
  20457. sse::SSEClient sse(client, "/auth-retry", headers);
  20458. std::atomic<bool> message_received{false};
  20459. // Refresh token on error
  20460. sse.on_error(
  20461. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20462. sse.on_message([&](const sse::SSEMessage &msg) {
  20463. if (msg.data == "authenticated") { message_received.store(true); }
  20464. });
  20465. sse.set_reconnect_interval(100);
  20466. sse.set_max_reconnect_attempts(3);
  20467. sse.start_async();
  20468. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20469. sse.stop();
  20470. // Should have reconnected after 401 and succeeded with new token
  20471. EXPECT_GE(connection_count.load(), 2);
  20472. EXPECT_TRUE(message_received.load());
  20473. }
  20474. TEST(Issue2318Test, EmptyHostString) {
  20475. {
  20476. httplib::Client cli_empty("", PORT);
  20477. auto res = cli_empty.Get("/");
  20478. ASSERT_FALSE(res);
  20479. EXPECT_EQ(httplib::Error::Connection, res.error());
  20480. }
  20481. {
  20482. httplib::Client cli(" ", PORT);
  20483. auto res = cli.Get("/");
  20484. ASSERT_FALSE(res);
  20485. EXPECT_EQ(httplib::Error::Connection, res.error());
  20486. }
  20487. }
  20488. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20489. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20490. Server svr;
  20491. // Set a small payload limit (1KB)
  20492. svr.set_payload_max_length(1024);
  20493. svr.Post("/test", [&](const Request &req, Response &res) {
  20494. res.set_content("Body size: " + std::to_string(req.body.size()),
  20495. "text/plain");
  20496. });
  20497. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20498. auto se = detail::scope_exit([&] {
  20499. svr.stop();
  20500. listen_thread.join();
  20501. });
  20502. svr.wait_until_ready();
  20503. // Create data that compresses well but exceeds limit when decompressed
  20504. // 8KB of repeated null bytes compresses to a very small size
  20505. std::string original_data(8 * 1024, '\0');
  20506. // Compress the data using gzip
  20507. std::string compressed_data;
  20508. detail::gzip_compressor compressor;
  20509. compressor.compress(original_data.data(), original_data.size(), true,
  20510. [&](const char *data, size_t size) {
  20511. compressed_data.append(data, size);
  20512. return true;
  20513. });
  20514. // Verify compression worked (compressed should be much smaller)
  20515. ASSERT_LT(compressed_data.size(), original_data.size());
  20516. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20517. // Send compressed data with Content-Encoding: gzip
  20518. Client cli(HOST, PORT);
  20519. Headers headers = {{"Content-Encoding", "gzip"}};
  20520. auto res =
  20521. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20522. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20524. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20525. }
  20526. #endif
  20527. // ============================================================================
  20528. // OpenSSL-Specific Tests
  20529. // ============================================================================
  20530. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20531. X509 *readCertificate(const std::string &strFileName) {
  20532. std::ifstream inStream(strFileName);
  20533. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20534. std::istreambuf_iterator<char>());
  20535. if (strCertPEM.empty()) return (nullptr);
  20536. BIO *pbCert = BIO_new(BIO_s_mem());
  20537. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20538. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20539. BIO_free(pbCert);
  20540. return (pCert);
  20541. }
  20542. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20543. std::ifstream inStream(strFileName);
  20544. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20545. std::istreambuf_iterator<char>());
  20546. if (strPrivateKeyPEM.empty()) return (nullptr);
  20547. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20548. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20549. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20550. BIO_free(pbPrivKey);
  20551. return (pPrivateKey);
  20552. }
  20553. TEST(BindServerTest, UpdateCerts) {
  20554. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20555. int port = svr.bind_to_any_port("0.0.0.0");
  20556. ASSERT_TRUE(svr.is_valid());
  20557. ASSERT_TRUE(port > 0);
  20558. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20559. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20560. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20561. ASSERT_TRUE(cert != nullptr);
  20562. ASSERT_TRUE(ca_cert != nullptr);
  20563. ASSERT_TRUE(key != nullptr);
  20564. X509_STORE *cert_store = X509_STORE_new();
  20565. X509_STORE_add_cert(cert_store, ca_cert);
  20566. // svr.update_certs(cert, key, cert_store); // deprecated
  20567. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20568. CLIENT_CA_CERT_FILE);
  20569. ASSERT_TRUE(svr.is_valid());
  20570. svr.stop();
  20571. X509_STORE_free(cert_store);
  20572. X509_free(cert);
  20573. X509_free(ca_cert);
  20574. EVP_PKEY_free(key);
  20575. }
  20576. // Test that update_certs() updates client CA list correctly
  20577. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  20578. // Start with file-based constructor
  20579. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20580. ASSERT_TRUE(svr.is_valid());
  20581. // Initially no client CA list should be set
  20582. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20583. ASSERT_TRUE(ssl_ctx != nullptr);
  20584. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  20585. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  20586. EXPECT_EQ(0, count_before);
  20587. // Now update with client CA (PEM string)
  20588. std::string cert_pem, key_pem, ca_pem;
  20589. read_file(SERVER_CERT_FILE, cert_pem);
  20590. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  20591. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  20592. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  20593. ASSERT_TRUE(svr.is_valid());
  20594. // Now client CA list should be set
  20595. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  20596. ASSERT_TRUE(ca_list_after != nullptr);
  20597. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  20598. }
  20599. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  20600. // Test that the file-path SSLServer constructor properly sets the client CA
  20601. // list that is sent to clients during the TLS handshake (CertificateRequest)
  20602. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20603. ASSERT_TRUE(svr.is_valid());
  20604. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20605. ASSERT_TRUE(ssl_ctx != nullptr);
  20606. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  20607. ASSERT_TRUE(ca_list != nullptr);
  20608. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  20609. }
  20610. #endif
  20611. // ============================================================================
  20612. // MbedTLS-Specific Tests
  20613. // ============================================================================
  20614. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  20615. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  20616. using namespace httplib::tls;
  20617. // Track if callback was invoked
  20618. bool callback_invoked = false;
  20619. // The callback receives void* ctx which is actually MbedTlsContext*
  20620. // We can access the mbedtls_ssl_config via the context
  20621. auto setup_callback = [&callback_invoked](void *ctx) {
  20622. callback_invoked = true;
  20623. // Cast to MbedTlsContext* to access the ssl config
  20624. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  20625. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  20626. // Use static variables to hold certificate data (simplified for test)
  20627. static mbedtls_x509_crt own_cert;
  20628. static mbedtls_pk_context own_key;
  20629. static mbedtls_x509_crt ca_chain;
  20630. static bool initialized = false;
  20631. if (!initialized) {
  20632. mbedtls_x509_crt_init(&own_cert);
  20633. mbedtls_pk_init(&own_key);
  20634. mbedtls_x509_crt_init(&ca_chain);
  20635. // Load server certificate
  20636. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  20637. return false;
  20638. }
  20639. // Load server private key.
  20640. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  20641. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  20642. #if MBEDTLS_VERSION_MAJOR == 3
  20643. ,
  20644. mbedtls_ctr_drbg_random, nullptr
  20645. #endif
  20646. ) != 0) {
  20647. return false;
  20648. }
  20649. // Load CA chain for client verification
  20650. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  20651. return false;
  20652. }
  20653. initialized = true;
  20654. }
  20655. // Configure the SSL config
  20656. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  20657. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  20658. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  20659. // Set minimum TLS version using mbedTLS native API
  20660. #if MBEDTLS_VERSION_MAJOR >= 3
  20661. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  20662. #else
  20663. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  20664. MBEDTLS_SSL_MINOR_VERSION_3);
  20665. #endif
  20666. return true;
  20667. };
  20668. SSLServer svr(setup_callback);
  20669. ASSERT_TRUE(svr.is_valid());
  20670. ASSERT_TRUE(callback_invoked);
  20671. svr.Get("/test", [&](const Request &req, Response &res) {
  20672. res.set_content("test", "text/plain");
  20673. auto cert = req.peer_cert();
  20674. ASSERT_TRUE(static_cast<bool>(cert));
  20675. auto common_name = cert.subject_cn();
  20676. EXPECT_EQ("Common Name", common_name);
  20677. });
  20678. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20679. auto se = detail::scope_exit([&] {
  20680. svr.stop();
  20681. t.join();
  20682. ASSERT_FALSE(svr.is_running());
  20683. });
  20684. svr.wait_until_ready();
  20685. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  20686. cli.enable_server_certificate_verification(false);
  20687. cli.set_connection_timeout(30);
  20688. auto res = cli.Get("/test");
  20689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20690. ASSERT_EQ(StatusCode::OK_200, res->status);
  20691. }
  20692. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  20693. // context (owning mbedtls_ssl_config) before shutting down a still-open
  20694. // keep-alive SSL session, which reads through that config in
  20695. // mbedtls_ssl_close_notify.
  20696. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  20697. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20698. ASSERT_TRUE(svr.is_valid());
  20699. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  20700. res.set_content("test", "text/plain");
  20701. });
  20702. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20703. auto se = detail::scope_exit([&] {
  20704. svr.stop();
  20705. t.join();
  20706. ASSERT_FALSE(svr.is_running());
  20707. });
  20708. svr.wait_until_ready();
  20709. {
  20710. SSLClient cli(HOST, PORT);
  20711. cli.enable_server_certificate_verification(false);
  20712. cli.set_keep_alive(true);
  20713. auto res = cli.Get("/test");
  20714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20715. ASSERT_EQ(StatusCode::OK_200, res->status);
  20716. // cli is destructed here with the keep-alive SSL session still open.
  20717. }
  20718. }
  20719. #endif
  20720. // WebSocket Tests
  20721. TEST(WebSocketTest, RSVBitsMustBeZero) {
  20722. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  20723. // defining the meaning of these bits has been negotiated.
  20724. auto make_frame = [](uint8_t first_byte) {
  20725. std::string frame;
  20726. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  20727. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  20728. frame += "Hello";
  20729. return frame;
  20730. };
  20731. // RSV1 set (0x40)
  20732. {
  20733. detail::BufferStream strm;
  20734. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  20735. ws::Opcode opcode;
  20736. std::string payload;
  20737. bool fin;
  20738. EXPECT_EQ(
  20739. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20740. ws::impl::FrameRead::Fail);
  20741. }
  20742. // RSV2 set (0x20)
  20743. {
  20744. detail::BufferStream strm;
  20745. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  20746. ws::Opcode opcode;
  20747. std::string payload;
  20748. bool fin;
  20749. EXPECT_EQ(
  20750. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20751. ws::impl::FrameRead::Fail);
  20752. }
  20753. // RSV3 set (0x10)
  20754. {
  20755. detail::BufferStream strm;
  20756. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  20757. ws::Opcode opcode;
  20758. std::string payload;
  20759. bool fin;
  20760. EXPECT_EQ(
  20761. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20762. ws::impl::FrameRead::Fail);
  20763. }
  20764. // No RSV bits set - should succeed
  20765. {
  20766. detail::BufferStream strm;
  20767. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  20768. ws::Opcode opcode;
  20769. std::string payload;
  20770. bool fin;
  20771. EXPECT_EQ(
  20772. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20773. ws::impl::FrameRead::Ok);
  20774. EXPECT_EQ(ws::Opcode::Text, opcode);
  20775. EXPECT_EQ("Hello", payload);
  20776. EXPECT_TRUE(fin);
  20777. }
  20778. }
  20779. TEST(WebSocketTest, ControlFrameValidation) {
  20780. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  20781. // payload length <= 125.
  20782. // Ping with FIN=0 - must be rejected
  20783. {
  20784. detail::BufferStream strm;
  20785. std::string frame;
  20786. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  20787. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20788. strm.write(frame.data(), frame.size());
  20789. ws::Opcode opcode;
  20790. std::string payload;
  20791. bool fin;
  20792. EXPECT_EQ(
  20793. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20794. ws::impl::FrameRead::Fail);
  20795. }
  20796. // Close with FIN=0 - must be rejected
  20797. {
  20798. detail::BufferStream strm;
  20799. std::string frame;
  20800. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  20801. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20802. strm.write(frame.data(), frame.size());
  20803. ws::Opcode opcode;
  20804. std::string payload;
  20805. bool fin;
  20806. EXPECT_EQ(
  20807. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20808. ws::impl::FrameRead::Fail);
  20809. }
  20810. // Ping with payload_len=126 (extended length) - must be rejected
  20811. {
  20812. detail::BufferStream strm;
  20813. std::string frame;
  20814. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20815. frame += static_cast<char>(126); // payload_len=126 (>125)
  20816. frame += static_cast<char>(0x00); // extended length high byte
  20817. frame += static_cast<char>(126); // extended length low byte
  20818. frame += std::string(126, 'x');
  20819. strm.write(frame.data(), frame.size());
  20820. ws::Opcode opcode;
  20821. std::string payload;
  20822. bool fin;
  20823. EXPECT_EQ(
  20824. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20825. ws::impl::FrameRead::Fail);
  20826. }
  20827. // Ping with FIN=1 and payload_len=125 - should succeed
  20828. {
  20829. detail::BufferStream strm;
  20830. std::string frame;
  20831. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20832. frame += static_cast<char>(125); // payload_len=125
  20833. frame += std::string(125, 'x');
  20834. strm.write(frame.data(), frame.size());
  20835. ws::Opcode opcode;
  20836. std::string payload;
  20837. bool fin;
  20838. EXPECT_EQ(
  20839. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20840. ws::impl::FrameRead::Ok);
  20841. EXPECT_EQ(ws::Opcode::Ping, opcode);
  20842. EXPECT_EQ(125u, payload.size());
  20843. EXPECT_TRUE(fin);
  20844. }
  20845. }
  20846. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  20847. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  20848. // length MUST be 0.
  20849. // MSB set - must be rejected
  20850. {
  20851. detail::BufferStream strm;
  20852. std::string frame;
  20853. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20854. frame += static_cast<char>(127); // 64-bit extended length
  20855. frame += static_cast<char>(0x80); // MSB set (invalid)
  20856. frame += std::string(7, '\0'); // remaining 7 bytes of length
  20857. strm.write(frame.data(), frame.size());
  20858. ws::Opcode opcode;
  20859. std::string payload;
  20860. bool fin;
  20861. EXPECT_EQ(
  20862. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20863. ws::impl::FrameRead::Fail);
  20864. }
  20865. // MSB clear - should pass length parsing (will be rejected by max_len,
  20866. // but that's a different check; use a small length to verify)
  20867. {
  20868. detail::BufferStream strm;
  20869. std::string frame;
  20870. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20871. frame += static_cast<char>(127); // 64-bit extended length
  20872. frame += std::string(7, '\0'); // high bytes = 0
  20873. frame += static_cast<char>(0x03); // length = 3
  20874. frame += "abc";
  20875. strm.write(frame.data(), frame.size());
  20876. ws::Opcode opcode;
  20877. std::string payload;
  20878. bool fin;
  20879. EXPECT_EQ(
  20880. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20881. ws::impl::FrameRead::Ok);
  20882. EXPECT_EQ(ws::Opcode::Text, opcode);
  20883. EXPECT_EQ("abc", payload);
  20884. }
  20885. }
  20886. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  20887. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  20888. // Valid UTF-8
  20889. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  20890. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  20891. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  20892. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  20893. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  20894. // Invalid UTF-8
  20895. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  20896. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  20897. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  20898. EXPECT_FALSE(
  20899. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  20900. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  20901. }
  20902. TEST(WebSocketTest, ConnectAndDisconnect) {
  20903. Server svr;
  20904. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20905. std::string msg;
  20906. while (ws.read(msg)) {}
  20907. });
  20908. auto port = svr.bind_to_any_port(HOST);
  20909. std::thread t([&]() { svr.listen_after_bind(); });
  20910. svr.wait_until_ready();
  20911. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20912. auto res = client.connect();
  20913. ASSERT_TRUE(res);
  20914. EXPECT_EQ(Error::Success, res.error());
  20915. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  20916. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  20917. EXPECT_TRUE(client.is_open());
  20918. client.close();
  20919. EXPECT_FALSE(client.is_open());
  20920. svr.stop();
  20921. t.join();
  20922. }
  20923. TEST(WebSocketTest, ValidURL) {
  20924. ws::WebSocketClient ws1("ws://localhost:8080/path");
  20925. EXPECT_TRUE(ws1.is_valid());
  20926. ws::WebSocketClient ws2("ws://example.com/path");
  20927. EXPECT_TRUE(ws2.is_valid());
  20928. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  20929. EXPECT_TRUE(ws3.is_valid());
  20930. #ifdef CPPHTTPLIB_SSL_ENABLED
  20931. ws::WebSocketClient wss1("wss://example.com/path");
  20932. EXPECT_TRUE(wss1.is_valid());
  20933. ws::WebSocketClient wss2("wss://example.com:443/path");
  20934. EXPECT_TRUE(wss2.is_valid());
  20935. #endif
  20936. }
  20937. TEST(WebSocketTest, InvalidURL) {
  20938. // No scheme
  20939. ws::WebSocketClient ws1("localhost:8080/path");
  20940. EXPECT_FALSE(ws1.is_valid());
  20941. // No path
  20942. ws::WebSocketClient ws2("ws://localhost:8080");
  20943. EXPECT_FALSE(ws2.is_valid());
  20944. // Empty string
  20945. ws::WebSocketClient ws3("");
  20946. EXPECT_FALSE(ws3.is_valid());
  20947. // Missing host
  20948. ws::WebSocketClient ws4("ws://:8080/path");
  20949. EXPECT_FALSE(ws4.is_valid());
  20950. // Port number overflow — should not crash
  20951. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  20952. EXPECT_FALSE(ws5.is_valid());
  20953. // Port out of range
  20954. ws::WebSocketClient ws6("ws://localhost:99999/path");
  20955. EXPECT_FALSE(ws6.is_valid());
  20956. }
  20957. TEST(WebSocketTest, UnsupportedScheme) {
  20958. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  20959. ws::WebSocketClient ws1("http://localhost:8080/path");
  20960. EXPECT_FALSE(ws1.is_valid());
  20961. ws::WebSocketClient ws2("https://localhost:8080/path");
  20962. EXPECT_FALSE(ws2.is_valid());
  20963. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  20964. EXPECT_FALSE(ws3.is_valid());
  20965. #else
  20966. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  20967. std::invalid_argument);
  20968. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  20969. std::invalid_argument);
  20970. #endif
  20971. }
  20972. TEST(WebSocketTest, ConnectWhenInvalid) {
  20973. ws::WebSocketClient ws("not a valid url");
  20974. EXPECT_FALSE(ws.is_valid());
  20975. auto res = ws.connect();
  20976. EXPECT_FALSE(res);
  20977. EXPECT_EQ(Error::Connection, res.error());
  20978. EXPECT_EQ(-1, res.status());
  20979. }
  20980. TEST(WebSocketTest, ConnectRefusedReportsError) {
  20981. // Grab a port that is free, then close it again so nothing listens there
  20982. Server svr;
  20983. auto port = svr.bind_to_any_port(HOST);
  20984. svr.stop();
  20985. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20986. auto res = client.connect();
  20987. ASSERT_FALSE(res);
  20988. EXPECT_EQ(Error::Connection, res.error());
  20989. EXPECT_EQ(-1, res.status());
  20990. }
  20991. TEST(WebSocketTest, DefaultPort) {
  20992. ws::WebSocketClient ws1("ws://example.com/path");
  20993. EXPECT_TRUE(ws1.is_valid());
  20994. // ws:// defaults to port 80 (verified by successful parse)
  20995. #ifdef CPPHTTPLIB_SSL_ENABLED
  20996. ws::WebSocketClient ws2("wss://example.com/path");
  20997. EXPECT_TRUE(ws2.is_valid());
  20998. // wss:// defaults to port 443 (verified by successful parse)
  20999. #endif
  21000. }
  21001. TEST(WebSocketTest, IPv6LiteralAddress) {
  21002. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  21003. EXPECT_TRUE(ws1.is_valid());
  21004. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  21005. EXPECT_TRUE(ws2.is_valid());
  21006. }
  21007. TEST(WebSocketTest, ComplexPath) {
  21008. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  21009. EXPECT_TRUE(ws1.is_valid());
  21010. ws::WebSocketClient ws2("ws://localhost:8080/");
  21011. EXPECT_TRUE(ws2.is_valid());
  21012. }
  21013. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  21014. Server svr;
  21015. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21016. std::string msg;
  21017. while (ws.read(msg)) {}
  21018. });
  21019. auto port = svr.bind_to_any_port(HOST);
  21020. std::thread t([&]() { svr.listen_after_bind(); });
  21021. svr.wait_until_ready();
  21022. auto another_host = "example.com";
  21023. auto wrong_ip = "192.0.2.1";
  21024. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21025. client.set_hostname_addr_map({{another_host, wrong_ip}});
  21026. ASSERT_TRUE(client.connect());
  21027. EXPECT_TRUE(client.is_open());
  21028. client.close();
  21029. svr.stop();
  21030. t.join();
  21031. }
  21032. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  21033. Server svr;
  21034. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21035. std::string msg;
  21036. while (ws.read(msg)) {}
  21037. });
  21038. auto port = svr.bind_to_any_port(HOST);
  21039. std::thread t([&]() { svr.listen_after_bind(); });
  21040. svr.wait_until_ready();
  21041. auto wrong_ip = "192.0.2.1";
  21042. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21043. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  21044. client.set_connection_timeout(1);
  21045. client.set_read_timeout(1);
  21046. client.set_write_timeout(1);
  21047. EXPECT_FALSE(client.connect());
  21048. EXPECT_FALSE(client.is_open());
  21049. svr.stop();
  21050. t.join();
  21051. }
  21052. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  21053. // A mapped value that is not an IP literal must be resolved. HOST resolves
  21054. // from the hosts file, so this test needs no external DNS. "target.invalid"
  21055. // (RFC 6761) is only a map key and the Host header value.
  21056. auto host = "target.invalid";
  21057. Server svr;
  21058. std::string received_host;
  21059. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21060. received_host = req.get_header_value("Host");
  21061. std::string msg;
  21062. while (ws.read(msg)) {}
  21063. });
  21064. auto port = svr.bind_to_any_port(HOST);
  21065. std::thread t([&]() { svr.listen_after_bind(); });
  21066. // ASSERT_* below returns from the test body, which would leave t joinable
  21067. // and make ~thread call std::terminate.
  21068. auto se = detail::scope_exit([&] {
  21069. svr.stop();
  21070. if (t.joinable()) { t.join(); }
  21071. });
  21072. svr.wait_until_ready();
  21073. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  21074. std::to_string(port) + "/ws");
  21075. client.set_hostname_addr_map({{host, HOST}});
  21076. ASSERT_TRUE(client.connect());
  21077. EXPECT_TRUE(client.is_open());
  21078. client.close();
  21079. svr.stop();
  21080. t.join();
  21081. // The mapping only redirects the connection; the identity stays host_.
  21082. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  21083. }
  21084. class WebSocketIntegrationTest : public ::testing::Test {
  21085. protected:
  21086. void SetUp() override {
  21087. server_ = httplib::detail::make_unique<Server>();
  21088. setup_server();
  21089. start_server();
  21090. }
  21091. void TearDown() override {
  21092. server_->stop();
  21093. if (server_thread_.joinable()) { server_thread_.join(); }
  21094. }
  21095. void setup_server() {
  21096. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21097. std::string msg;
  21098. ws::ReadResult ret;
  21099. while ((ret = ws.read(msg))) {
  21100. if (ret == ws::Binary) {
  21101. ws.send(msg.data(), msg.size());
  21102. } else {
  21103. ws.send(msg);
  21104. }
  21105. }
  21106. });
  21107. server_->WebSocket("/ws-echo-string",
  21108. [](const Request &, ws::WebSocket &ws) {
  21109. std::string msg;
  21110. while (ws.read(msg)) {
  21111. ws.send("echo: " + msg);
  21112. }
  21113. });
  21114. server_->WebSocket(
  21115. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  21116. // Echo back request metadata
  21117. ws.send("path:" + req.path);
  21118. ws.send("header:" + req.get_header_value("X-Test-Header"));
  21119. std::string msg;
  21120. while (ws.read(msg)) {}
  21121. });
  21122. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  21123. std::string msg;
  21124. ws.read(msg); // wait for a message
  21125. ws.close();
  21126. });
  21127. server_->WebSocket("/ws-close-status",
  21128. [](const Request &, ws::WebSocket &ws) {
  21129. std::string msg;
  21130. ws.read(msg); // wait for a message
  21131. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  21132. });
  21133. server_->WebSocket(
  21134. "/ws-subprotocol",
  21135. [](const Request &, ws::WebSocket &ws) {
  21136. std::string msg;
  21137. while (ws.read(msg)) {
  21138. ws.send(msg);
  21139. }
  21140. },
  21141. [](const std::vector<std::string> &protocols) -> std::string {
  21142. for (const auto &p : protocols) {
  21143. if (p == "graphql-ws") { return p; }
  21144. }
  21145. return "";
  21146. });
  21147. server_->WebSocket(
  21148. "/ws-subprotocol-unoffered",
  21149. [](const Request &, ws::WebSocket &ws) {
  21150. std::string msg;
  21151. while (ws.read(msg)) {
  21152. ws.send(msg);
  21153. }
  21154. },
  21155. [](const std::vector<std::string> &) -> std::string {
  21156. return "admin";
  21157. });
  21158. }
  21159. void start_server() {
  21160. port_ = server_->bind_to_any_port(HOST);
  21161. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21162. server_->wait_until_ready();
  21163. }
  21164. std::unique_ptr<Server> server_;
  21165. std::thread server_thread_;
  21166. int port_ = 0;
  21167. };
  21168. TEST_F(WebSocketIntegrationTest, TextEcho) {
  21169. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21170. "/ws-echo");
  21171. ASSERT_TRUE(client.connect());
  21172. ASSERT_TRUE(client.is_open());
  21173. ASSERT_TRUE(client.send("Hello WebSocket"));
  21174. std::string msg;
  21175. EXPECT_EQ(ws::Text, client.read(msg));
  21176. EXPECT_EQ("Hello WebSocket", msg);
  21177. client.close();
  21178. }
  21179. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  21180. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21181. "/ws-echo");
  21182. ASSERT_TRUE(client.connect());
  21183. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  21184. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  21185. std::string msg;
  21186. EXPECT_EQ(ws::Binary, client.read(msg));
  21187. EXPECT_EQ(binary_data, msg);
  21188. client.close();
  21189. }
  21190. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  21191. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21192. "/ws-echo");
  21193. ASSERT_TRUE(client.connect());
  21194. for (int i = 0; i < 10; i++) {
  21195. auto text = "message " + std::to_string(i);
  21196. ASSERT_TRUE(client.send(text));
  21197. std::string msg;
  21198. ASSERT_TRUE(client.read(msg));
  21199. EXPECT_EQ(text, msg);
  21200. }
  21201. client.close();
  21202. }
  21203. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  21204. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21205. "/ws-close");
  21206. ASSERT_TRUE(client.connect());
  21207. // Send a message to trigger the server to close
  21208. ASSERT_TRUE(client.send("trigger close"));
  21209. // The server will close, so read should return false
  21210. std::string msg;
  21211. EXPECT_FALSE(client.read(msg));
  21212. EXPECT_FALSE(client.is_open());
  21213. }
  21214. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  21215. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21216. "/ws-echo");
  21217. ASSERT_TRUE(client.connect());
  21218. // 128KB message
  21219. std::string large_data(128 * 1024, 'X');
  21220. ASSERT_TRUE(client.send(large_data));
  21221. std::string msg;
  21222. ASSERT_TRUE(client.read(msg));
  21223. EXPECT_EQ(large_data, msg);
  21224. client.close();
  21225. }
  21226. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  21227. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21228. "/ws-echo");
  21229. ASSERT_TRUE(client.connect());
  21230. const int num_threads = 4;
  21231. std::vector<std::thread> threads;
  21232. std::atomic<int> send_count{0};
  21233. for (int t = 0; t < num_threads; t++) {
  21234. threads.emplace_back([&client, &send_count, t]() {
  21235. for (int i = 0; i < 5; i++) {
  21236. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  21237. if (client.send(text)) { send_count++; }
  21238. }
  21239. });
  21240. }
  21241. for (auto &th : threads) {
  21242. th.join();
  21243. }
  21244. int received = 0;
  21245. std::string msg;
  21246. while (received < send_count.load()) {
  21247. if (!client.read(msg)) { break; }
  21248. received++;
  21249. }
  21250. EXPECT_EQ(send_count.load(), received);
  21251. client.close();
  21252. }
  21253. TEST_F(WebSocketIntegrationTest, ReadString) {
  21254. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21255. "/ws-echo-string");
  21256. ASSERT_TRUE(client.connect());
  21257. ASSERT_TRUE(client.send("hello"));
  21258. std::string msg;
  21259. ASSERT_TRUE(client.read(msg));
  21260. EXPECT_EQ("echo: hello", msg);
  21261. ASSERT_TRUE(client.send("world"));
  21262. ASSERT_TRUE(client.read(msg));
  21263. EXPECT_EQ("echo: world", msg);
  21264. client.close();
  21265. }
  21266. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  21267. Headers headers = {{"X-Test-Header", "test-value"}};
  21268. ws::WebSocketClient client(
  21269. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  21270. ASSERT_TRUE(client.connect());
  21271. std::string msg;
  21272. ASSERT_TRUE(client.read(msg));
  21273. EXPECT_EQ("path:/ws-request-info", msg);
  21274. ASSERT_TRUE(client.read(msg));
  21275. EXPECT_EQ("header:test-value", msg);
  21276. client.close();
  21277. }
  21278. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  21279. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21280. "/ws-echo");
  21281. client.set_read_timeout(1, 0); // 1 second
  21282. ASSERT_TRUE(client.connect());
  21283. // Don't send anything — server echo handler waits for a message, so read()
  21284. // should time out. The connection survives it: nothing was consumed.
  21285. std::string msg;
  21286. EXPECT_EQ(client.read(msg), ws::Timeout);
  21287. EXPECT_TRUE(client.is_open());
  21288. // And it is still usable afterwards.
  21289. EXPECT_TRUE(client.send("after timeout"));
  21290. EXPECT_EQ(client.read(msg), ws::Text);
  21291. EXPECT_EQ(msg, "after timeout");
  21292. }
  21293. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  21294. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21295. "/ws-echo");
  21296. client.set_read_timeout(1, 0);
  21297. ASSERT_TRUE(client.connect());
  21298. ASSERT_TRUE(client.send("first"));
  21299. std::string msg;
  21300. ASSERT_EQ(client.read(msg), ws::Text);
  21301. ASSERT_EQ(msg, "first");
  21302. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  21303. // not be used with a read timeout: it would reprocess the previous message.
  21304. EXPECT_EQ(client.read(msg), ws::Timeout);
  21305. EXPECT_EQ(msg, "first");
  21306. }
  21307. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  21308. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21309. "/ws-echo");
  21310. ASSERT_TRUE(client.connect());
  21311. // Setting it once the connection is open reaches the live stream, not just
  21312. // the seed for the next connect().
  21313. client.set_read_timeout(1, 0);
  21314. std::string msg;
  21315. EXPECT_EQ(client.read(msg), ws::Timeout);
  21316. EXPECT_TRUE(client.is_open());
  21317. }
  21318. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  21319. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21320. "/ws-echo");
  21321. client.set_read_timeout(5, 0);
  21322. ASSERT_TRUE(client.connect());
  21323. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21324. // The server should reject it and close the connection.
  21325. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  21326. client.send(oversized);
  21327. // The server's read() should have failed due to payload limit,
  21328. // so our read() should return false (connection closed).
  21329. std::string msg;
  21330. EXPECT_FALSE(client.read(msg));
  21331. }
  21332. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  21333. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21334. "/ws-echo");
  21335. client.set_read_timeout(10, 0);
  21336. ASSERT_TRUE(client.connect());
  21337. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21338. // This should succeed.
  21339. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  21340. ASSERT_TRUE(client.send(at_limit));
  21341. std::string msg;
  21342. ASSERT_TRUE(client.read(msg));
  21343. EXPECT_EQ(at_limit.size(), msg.size());
  21344. client.close();
  21345. }
  21346. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  21347. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21348. "/nonexistent");
  21349. auto res = client.connect();
  21350. EXPECT_FALSE(res);
  21351. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21352. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  21353. EXPECT_FALSE(client.is_open());
  21354. }
  21355. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  21356. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21357. "/ws-echo");
  21358. ASSERT_TRUE(client.connect());
  21359. ASSERT_TRUE(client.send(""));
  21360. std::string msg;
  21361. EXPECT_EQ(ws::Text, client.read(msg));
  21362. EXPECT_EQ("", msg);
  21363. client.close();
  21364. }
  21365. TEST_F(WebSocketIntegrationTest, Reconnect) {
  21366. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21367. "/ws-echo");
  21368. // First connection
  21369. ASSERT_TRUE(client.connect());
  21370. ASSERT_TRUE(client.send("first"));
  21371. std::string msg;
  21372. ASSERT_TRUE(client.read(msg));
  21373. EXPECT_EQ("first", msg);
  21374. client.close();
  21375. EXPECT_FALSE(client.is_open());
  21376. // Reconnect using the same client object
  21377. ASSERT_TRUE(client.connect());
  21378. ASSERT_TRUE(client.is_open());
  21379. ASSERT_TRUE(client.send("second"));
  21380. ASSERT_TRUE(client.read(msg));
  21381. EXPECT_EQ("second", msg);
  21382. client.close();
  21383. }
  21384. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  21385. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21386. "/ws-close-status");
  21387. ASSERT_TRUE(client.connect());
  21388. // Trigger the server to close with GoingAway status
  21389. ASSERT_TRUE(client.send("trigger"));
  21390. // read() should return false after receiving the close frame
  21391. std::string msg;
  21392. EXPECT_FALSE(client.read(msg));
  21393. EXPECT_FALSE(client.is_open());
  21394. }
  21395. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  21396. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21397. "/ws-echo");
  21398. ASSERT_TRUE(client.connect());
  21399. client.close(ws::CloseStatus::GoingAway, "client leaving");
  21400. EXPECT_FALSE(client.is_open());
  21401. }
  21402. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  21403. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  21404. ws::WebSocketClient client(
  21405. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21406. ASSERT_TRUE(client.connect());
  21407. // Server should have selected graphql-ws
  21408. EXPECT_EQ("graphql-ws", client.subprotocol());
  21409. client.close();
  21410. }
  21411. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  21412. Headers headers;
  21413. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  21414. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  21415. ws::WebSocketClient client(
  21416. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21417. ASSERT_TRUE(client.connect());
  21418. // The offer on the second field line counts too, so graphql-ws is selected
  21419. EXPECT_EQ("graphql-ws", client.subprotocol());
  21420. client.close();
  21421. }
  21422. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  21423. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  21424. ws::WebSocketClient client(
  21425. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21426. ASSERT_TRUE(client.connect());
  21427. // Server should not have selected any subprotocol
  21428. EXPECT_TRUE(client.subprotocol().empty());
  21429. client.close();
  21430. }
  21431. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  21432. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21433. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21434. "/ws-subprotocol-unoffered",
  21435. headers);
  21436. ASSERT_TRUE(client.connect());
  21437. EXPECT_TRUE(client.subprotocol().empty());
  21438. client.close();
  21439. }
  21440. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21441. // Connect without requesting any subprotocol
  21442. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21443. "/ws-subprotocol");
  21444. ASSERT_TRUE(client.connect());
  21445. EXPECT_TRUE(client.subprotocol().empty());
  21446. client.close();
  21447. }
  21448. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21449. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21450. "/ws-echo");
  21451. client.set_tcp_nodelay(true);
  21452. client.set_connection_timeout(3, 0);
  21453. bool socket_options_called = false;
  21454. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21455. ASSERT_TRUE(client.connect());
  21456. ASSERT_TRUE(client.is_open());
  21457. EXPECT_TRUE(socket_options_called);
  21458. ASSERT_TRUE(client.send("hello"));
  21459. std::string msg;
  21460. auto result = client.read(msg);
  21461. EXPECT_EQ(result, ws::ReadResult::Text);
  21462. EXPECT_EQ(msg, "hello");
  21463. client.close();
  21464. }
  21465. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21466. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21467. "/ws-echo");
  21468. client.set_connection_timeout(std::chrono::seconds(3));
  21469. client.set_write_timeout(std::chrono::seconds(3));
  21470. // A sub-second remainder exercises the seconds/microseconds split.
  21471. client.set_read_timeout(std::chrono::milliseconds(1500));
  21472. ASSERT_TRUE(client.connect());
  21473. auto start = std::chrono::steady_clock::now();
  21474. std::string msg;
  21475. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21476. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21477. std::chrono::steady_clock::now() - start)
  21478. .count();
  21479. // Above 1s so that dropping the microseconds half of the split fails here.
  21480. // Ignoring the setter altogether would not reach this line at all: a client
  21481. // waits forever by default.
  21482. EXPECT_GE(elapsed, 1400);
  21483. EXPECT_LT(elapsed, 30000);
  21484. }
  21485. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21486. Server svr;
  21487. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21488. if (!req.has_header("Authorization")) {
  21489. res.status = StatusCode::Unauthorized_401;
  21490. res.set_content("Unauthorized", "text/plain");
  21491. return Server::HandlerResponse::Handled;
  21492. }
  21493. return Server::HandlerResponse::Unhandled;
  21494. });
  21495. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21496. std::string msg;
  21497. while (ws.read(msg)) {
  21498. ws.send(msg);
  21499. }
  21500. });
  21501. auto port = svr.bind_to_any_port("localhost");
  21502. std::thread t([&]() { svr.listen_after_bind(); });
  21503. svr.wait_until_ready();
  21504. // Without Authorization header - should be rejected before upgrade
  21505. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21506. EXPECT_FALSE(client1.connect());
  21507. // The rejection is framed like any other HTTP response
  21508. {
  21509. Client cli("localhost", port);
  21510. Headers headers = {{"Upgrade", "websocket"},
  21511. {"Connection", "Upgrade"},
  21512. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21513. {"Sec-WebSocket-Version", "13"}};
  21514. auto res = cli.Get("/ws", headers);
  21515. ASSERT_TRUE(res);
  21516. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21517. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21518. EXPECT_EQ("Unauthorized", res->body);
  21519. }
  21520. // With Authorization header - should succeed
  21521. Headers headers = {{"Authorization", "Bearer token123"}};
  21522. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21523. headers);
  21524. ASSERT_TRUE(client2.connect());
  21525. ASSERT_TRUE(client2.send("hello"));
  21526. std::string msg;
  21527. ASSERT_TRUE(client2.read(msg));
  21528. EXPECT_EQ("hello", msg);
  21529. client2.close();
  21530. svr.stop();
  21531. t.join();
  21532. }
  21533. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21534. Server svr;
  21535. std::atomic<int> pre_request_calls{0};
  21536. std::atomic<bool> route_matched{false};
  21537. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21538. pre_request_calls++;
  21539. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21540. if (req.get_header_value("Authorization") != "Bearer token123") {
  21541. res.status = StatusCode::Unauthorized_401;
  21542. res.set_content("Unauthorized", "text/plain");
  21543. return Server::HandlerResponse::Handled;
  21544. }
  21545. return Server::HandlerResponse::Unhandled;
  21546. });
  21547. std::atomic<bool> handler_called{false};
  21548. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21549. handler_called = true;
  21550. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21551. });
  21552. auto port = svr.bind_to_any_port("localhost");
  21553. std::thread t([&]() { svr.listen_after_bind(); });
  21554. svr.wait_until_ready();
  21555. // Without Authorization header - should be rejected before upgrade
  21556. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21557. "/ws/1");
  21558. EXPECT_FALSE(client1.connect());
  21559. EXPECT_FALSE(handler_called);
  21560. EXPECT_EQ(1, pre_request_calls);
  21561. EXPECT_TRUE(route_matched);
  21562. // The rejection is an ordinary HTTP response, not a protocol switch
  21563. {
  21564. Client cli("localhost", port);
  21565. Headers headers = {{"Upgrade", "websocket"},
  21566. {"Connection", "Upgrade"},
  21567. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21568. {"Sec-WebSocket-Version", "13"}};
  21569. auto res = cli.Get("/ws/1", headers);
  21570. ASSERT_TRUE(res);
  21571. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21572. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21573. EXPECT_EQ("Unauthorized", res->body);
  21574. }
  21575. EXPECT_FALSE(handler_called);
  21576. // With Authorization header - should succeed
  21577. Headers headers = {{"Authorization", "Bearer token123"}};
  21578. ws::WebSocketClient client2(
  21579. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  21580. ASSERT_TRUE(client2.connect());
  21581. std::string msg;
  21582. ASSERT_TRUE(client2.read(msg));
  21583. EXPECT_EQ("/ws/:id 2", msg);
  21584. EXPECT_TRUE(handler_called);
  21585. client2.close();
  21586. svr.stop();
  21587. t.join();
  21588. }
  21589. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  21590. Server svr;
  21591. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21592. // A read timeout is how a handler gets control back. Without it, a handler
  21593. // parked in read() can never write on the connection it is reading.
  21594. ws.set_read_timeout(std::chrono::milliseconds(100));
  21595. std::string msg;
  21596. while (ws.is_open()) {
  21597. auto r = ws.read(msg);
  21598. if (r == httplib::ws::Timeout) {
  21599. ws.send("tick");
  21600. continue;
  21601. }
  21602. if (r == httplib::ws::Fail) { break; }
  21603. ws.send(msg);
  21604. }
  21605. });
  21606. auto port = svr.bind_to_any_port("localhost");
  21607. std::thread t([&]() { svr.listen_after_bind(); });
  21608. svr.wait_until_ready();
  21609. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21610. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  21611. ASSERT_TRUE(client.connect());
  21612. // The client sends nothing, so anything it receives came out of the
  21613. // handler's timeout path.
  21614. std::string msg;
  21615. ASSERT_EQ(client.read(msg), ws::Text);
  21616. EXPECT_EQ("tick", msg);
  21617. client.close();
  21618. svr.stop();
  21619. t.join();
  21620. }
  21621. // Stream::read may return fewer bytes than asked for. This is that contract at
  21622. // its worst -- one byte per call -- which is what a frame header straddling a
  21623. // read buffer's boundary looks like to the frame parser.
  21624. class WsByteAtATimeStream : public Stream {
  21625. public:
  21626. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  21627. bool is_readable() const override { return true; }
  21628. bool wait_readable() const override { return true; }
  21629. bool wait_writable() const override { return true; }
  21630. ssize_t read(char *ptr, size_t size) override {
  21631. if (size == 0 || pos_ >= data_.size()) { return 0; }
  21632. *ptr = data_[pos_++];
  21633. return 1;
  21634. }
  21635. ssize_t write(const char *, size_t size) override {
  21636. return static_cast<ssize_t>(size);
  21637. }
  21638. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  21639. ip = "127.0.0.1";
  21640. port = 0;
  21641. }
  21642. void get_local_ip_and_port(std::string &ip, int &port) const override {
  21643. ip = "127.0.0.1";
  21644. port = 0;
  21645. }
  21646. socket_t socket() const override { return INVALID_SOCKET; }
  21647. time_t duration() const override { return 0; }
  21648. private:
  21649. std::string data_;
  21650. size_t pos_ = 0;
  21651. };
  21652. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  21653. // The payload uses the 16-bit extended length, so the header, the length
  21654. // and the mask key are all multi-byte fields here. Each used to be read
  21655. // with a single read() call, which fails as soon as one is split. The
  21656. // payload is also a little over one read chunk, so it is read in two.
  21657. std::string body;
  21658. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  21659. body += static_cast<char>(i % 251);
  21660. }
  21661. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  21662. std::string frame;
  21663. frame += static_cast<char>(0x81); // FIN + Text
  21664. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  21665. frame += static_cast<char>(body.size() >> 8);
  21666. frame += static_cast<char>(body.size() & 0xff);
  21667. for (size_t i = 0; i < 4; i++) {
  21668. frame += static_cast<char>(mask[i]);
  21669. }
  21670. for (size_t i = 0; i < body.size(); i++) {
  21671. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  21672. }
  21673. WsByteAtATimeStream strm(frame);
  21674. ws::Opcode opcode;
  21675. std::string payload;
  21676. bool fin = false;
  21677. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  21678. /*expect_masked=*/true, body.size()),
  21679. ws::impl::FrameRead::Ok);
  21680. EXPECT_TRUE(fin);
  21681. EXPECT_EQ(opcode, ws::Opcode::Text);
  21682. EXPECT_EQ(payload, body);
  21683. }
  21684. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  21685. std::string body(2000, 'x');
  21686. std::string frame;
  21687. frame += static_cast<char>(0x82); // FIN + Binary
  21688. frame += static_cast<char>(126); // 16-bit length follows
  21689. frame += static_cast<char>(body.size() >> 8);
  21690. frame += static_cast<char>(body.size() & 0xff);
  21691. frame += body;
  21692. detail::BufferStream strm;
  21693. strm.write(frame.data(), frame.size());
  21694. ws::Opcode opcode;
  21695. std::string payload;
  21696. bool fin;
  21697. EXPECT_EQ(
  21698. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  21699. ws::impl::FrameRead::Ok);
  21700. EXPECT_EQ(body, payload);
  21701. }
  21702. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  21703. // The header announces the largest payload allowed, and only 3 bytes of it
  21704. // ever arrive.
  21705. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  21706. std::string frame;
  21707. frame += static_cast<char>(0x82); // FIN + Binary
  21708. frame += static_cast<char>(127); // 64-bit length follows
  21709. for (int shift = 56; shift >= 0; shift -= 8) {
  21710. frame += static_cast<char>((len >> shift) & 0xff);
  21711. }
  21712. frame += "abc";
  21713. detail::BufferStream strm;
  21714. strm.write(frame.data(), frame.size());
  21715. ws::Opcode opcode;
  21716. std::string payload;
  21717. bool fin;
  21718. EXPECT_EQ(
  21719. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  21720. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  21721. ws::impl::FrameRead::Fail);
  21722. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  21723. }
  21724. TEST(WebSocketTest, QueryStringInHandshake) {
  21725. Server svr;
  21726. std::mutex mtx;
  21727. std::string received_target;
  21728. std::string received_token;
  21729. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21730. {
  21731. std::lock_guard<std::mutex> lock(mtx);
  21732. received_target = req.target;
  21733. if (req.has_param("token")) {
  21734. received_token = req.get_param_value("token");
  21735. }
  21736. }
  21737. std::string msg;
  21738. while (ws.read(msg)) {
  21739. ws.send(msg);
  21740. }
  21741. });
  21742. auto port = svr.bind_to_any_port("localhost");
  21743. std::thread t([&]() { svr.listen_after_bind(); });
  21744. svr.wait_until_ready();
  21745. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  21746. "/ws?token=ABC&session=123");
  21747. ASSERT_TRUE(client.connect());
  21748. // Round-trip ensures the handler has run and captured the request.
  21749. ASSERT_TRUE(client.send("hello"));
  21750. std::string msg;
  21751. ASSERT_TRUE(client.read(msg));
  21752. EXPECT_EQ("hello", msg);
  21753. client.close();
  21754. {
  21755. std::lock_guard<std::mutex> lock(mtx);
  21756. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  21757. EXPECT_EQ("ABC", received_token);
  21758. }
  21759. svr.stop();
  21760. t.join();
  21761. }
  21762. // Run a handshake against a throwaway server and hand the request the server
  21763. // received back to the caller, so tests can assert on the headers the client
  21764. // actually put on the wire.
  21765. static void capture_websocket_handshake_request(
  21766. const Headers &client_headers,
  21767. std::function<void(const Request &, int port)> verify) {
  21768. Server svr;
  21769. std::mutex mtx;
  21770. Request received;
  21771. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21772. {
  21773. std::lock_guard<std::mutex> lock(mtx);
  21774. received = req;
  21775. }
  21776. std::string msg;
  21777. while (ws.read(msg)) {
  21778. ws.send(msg);
  21779. }
  21780. });
  21781. auto port = svr.bind_to_any_port("localhost");
  21782. std::thread t([&]() { svr.listen_after_bind(); });
  21783. auto se = detail::scope_exit([&] {
  21784. svr.stop();
  21785. t.join();
  21786. });
  21787. svr.wait_until_ready();
  21788. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  21789. client_headers);
  21790. ASSERT_TRUE(client.connect());
  21791. ASSERT_TRUE(client.send("hello"));
  21792. std::string msg;
  21793. ASSERT_TRUE(client.read(msg));
  21794. client.close();
  21795. {
  21796. std::lock_guard<std::mutex> lock(mtx);
  21797. verify(received, port);
  21798. }
  21799. }
  21800. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  21801. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  21802. // Non-default port must be present in the Host header. Default ports
  21803. // (80/443) are omitted; that logic is covered by
  21804. // MakeHostAndPortStringTest.
  21805. EXPECT_EQ("localhost:" + std::to_string(port),
  21806. req.get_header_value("Host"));
  21807. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  21808. req.get_header_value("User-Agent"));
  21809. EXPECT_FALSE(req.has_header("Accept"));
  21810. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  21811. EXPECT_FALSE(req.has_header("Content-Length"));
  21812. });
  21813. }
  21814. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  21815. capture_websocket_handshake_request(
  21816. {{"Host", "example.com"},
  21817. {"User-Agent", "custom-agent"},
  21818. {"X-Custom", "value"}},
  21819. [](const Request &req, int) {
  21820. EXPECT_EQ("example.com", req.get_header_value("Host"));
  21821. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  21822. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  21823. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  21824. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  21825. });
  21826. }
  21827. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  21828. capture_websocket_handshake_request(
  21829. {{"Upgrade", "bogus"},
  21830. {"Connection", "close"},
  21831. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  21832. {"Sec-WebSocket-Version", "8"}},
  21833. [](const Request &req, int) {
  21834. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  21835. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  21836. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  21837. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  21838. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  21839. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  21840. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  21841. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  21842. req.get_header_value("Sec-WebSocket-Key"));
  21843. });
  21844. }
  21845. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  21846. // A header the client refuses to send must abort the handshake before any
  21847. // part of it reaches the wire; a lone request line would otherwise sit in
  21848. // the peer's buffer as a truncated request.
  21849. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21850. ASSERT_NE(INVALID_SOCKET, srv);
  21851. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  21852. sockaddr_in addr{};
  21853. addr.sin_family = AF_INET;
  21854. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  21855. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21856. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  21857. ASSERT_EQ(0, ::listen(srv, 1));
  21858. sockaddr_in bound{};
  21859. socklen_t bound_len = sizeof(bound);
  21860. ASSERT_EQ(
  21861. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  21862. auto port = ntohs(bound.sin_port);
  21863. ssize_t received = -1;
  21864. std::thread t([&] {
  21865. // Bound every blocking call so a regression fails the test with a bad
  21866. // value instead of hanging the suite.
  21867. fd_set rfds;
  21868. FD_ZERO(&rfds);
  21869. FD_SET(srv, &rfds);
  21870. timeval tv{5, 0};
  21871. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  21872. 0) {
  21873. return;
  21874. }
  21875. sockaddr_in cli_addr{};
  21876. socklen_t cli_len = sizeof(cli_addr);
  21877. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21878. if (cli == INVALID_SOCKET) { return; }
  21879. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  21880. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21881. char buf[4096];
  21882. received = ::recv(cli, buf, sizeof(buf), 0);
  21883. });
  21884. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  21885. // connect() has already shut the socket down by the time it returns false,
  21886. // so the peer sees EOF without waiting for the client to be destroyed.
  21887. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  21888. {{"X-Bad", "a\r\nInjected: 1"}});
  21889. EXPECT_FALSE(client.connect());
  21890. t.join();
  21891. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  21892. EXPECT_EQ(0, received);
  21893. }
  21894. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  21895. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  21896. // contains "upgrade" as a substring is a different token and must not
  21897. // start a WebSocket handshake.
  21898. auto make_request = [](const std::vector<std::string> &connection_values) {
  21899. Request req;
  21900. req.method = "GET";
  21901. req.headers.emplace("Upgrade", "websocket");
  21902. for (const auto &value : connection_values) {
  21903. req.headers.emplace("Connection", value);
  21904. }
  21905. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21906. req.headers.emplace("Sec-WebSocket-Version", "13");
  21907. return req;
  21908. };
  21909. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  21910. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  21911. EXPECT_TRUE(
  21912. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  21913. EXPECT_TRUE(
  21914. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  21915. EXPECT_TRUE(
  21916. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  21917. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  21918. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  21919. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  21920. EXPECT_FALSE(
  21921. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  21922. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  21923. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21924. }
  21925. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  21926. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  21927. // asks recipients to match each protocol-name case-insensitively, and RFC
  21928. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  21929. // client naming websocket alongside another protocol, or on a second field
  21930. // line, is offering websocket; a value that merely contains "websocket" as a
  21931. // substring is a different protocol name and is not.
  21932. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  21933. Request req;
  21934. req.method = "GET";
  21935. for (const auto &value : upgrade_values) {
  21936. req.headers.emplace("Upgrade", value);
  21937. }
  21938. req.headers.emplace("Connection", "Upgrade");
  21939. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21940. req.headers.emplace("Sec-WebSocket-Version", "13");
  21941. return req;
  21942. };
  21943. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  21944. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  21945. EXPECT_TRUE(
  21946. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  21947. EXPECT_TRUE(
  21948. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  21949. EXPECT_TRUE(
  21950. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  21951. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  21952. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  21953. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  21954. EXPECT_FALSE(
  21955. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  21956. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  21957. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21958. }
  21959. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  21960. Server svr;
  21961. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  21962. auto port = svr.bind_to_any_port("localhost");
  21963. std::thread t([&]() { svr.listen_after_bind(); });
  21964. auto se = detail::scope_exit([&] {
  21965. svr.stop();
  21966. t.join();
  21967. });
  21968. svr.wait_until_ready();
  21969. Headers headers = {{"Upgrade", "websocket"},
  21970. {"Connection", "notupgrade"},
  21971. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21972. {"Sec-WebSocket-Version", "13"}};
  21973. Client cli("localhost", port);
  21974. auto res = cli.Get("/ws", headers);
  21975. // The route exists only as a WebSocket route, so a request that fails the
  21976. // handshake check falls through to ordinary routing.
  21977. ASSERT_TRUE(res);
  21978. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  21979. }
  21980. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  21981. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  21982. // Connection value is the only thing left for the client to reject.
  21983. Server svr;
  21984. svr.Get("/ws", [](const Request &req, Response &res) {
  21985. res.status = StatusCode::SwitchingProtocol_101;
  21986. res.set_header("Upgrade", "websocket");
  21987. res.set_header("Connection", "notupgrade");
  21988. res.set_header("Sec-WebSocket-Accept",
  21989. detail::websocket_accept_key(
  21990. req.get_header_value("Sec-WebSocket-Key")));
  21991. });
  21992. auto port = svr.bind_to_any_port("localhost");
  21993. std::thread t([&]() { svr.listen_after_bind(); });
  21994. auto se = detail::scope_exit([&] {
  21995. svr.stop();
  21996. t.join();
  21997. });
  21998. svr.wait_until_ready();
  21999. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22000. auto res = client.connect();
  22001. EXPECT_FALSE(res);
  22002. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22003. EXPECT_FALSE(client.is_open());
  22004. }
  22005. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  22006. Server svr;
  22007. svr.Get("/ws", [](const Request &req, Response &res) {
  22008. res.status = StatusCode::SwitchingProtocol_101;
  22009. res.set_header("Upgrade", "websocket");
  22010. res.set_header("Connection", "Upgrade");
  22011. res.set_header("Sec-WebSocket-Accept",
  22012. detail::websocket_accept_key(
  22013. req.get_header_value("Sec-WebSocket-Key")));
  22014. res.set_header("Sec-WebSocket-Protocol", "admin");
  22015. });
  22016. auto port = svr.bind_to_any_port("localhost");
  22017. std::thread t([&]() { svr.listen_after_bind(); });
  22018. auto se = detail::scope_exit([&] {
  22019. svr.stop();
  22020. t.join();
  22021. });
  22022. svr.wait_until_ready();
  22023. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  22024. // Server selects a subprotocol the client never offered
  22025. {
  22026. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22027. ws::WebSocketClient client(url, headers);
  22028. auto res = client.connect();
  22029. EXPECT_FALSE(res);
  22030. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22031. EXPECT_FALSE(client.is_open());
  22032. EXPECT_TRUE(client.subprotocol().empty());
  22033. }
  22034. // Client offered none but the server named one anyway
  22035. {
  22036. ws::WebSocketClient client(url);
  22037. auto res = client.connect();
  22038. EXPECT_FALSE(res);
  22039. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22040. EXPECT_FALSE(client.is_open());
  22041. EXPECT_TRUE(client.subprotocol().empty());
  22042. }
  22043. }
  22044. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  22045. // The socket path doubles as the URL host, so it must not contain '/'.
  22046. const char *shard = getenv("GTEST_SHARD_INDEX");
  22047. const std::string sock_path =
  22048. shard ? std::string("httplib-ws-") + shard + ".sock"
  22049. : std::string("httplib-ws.sock");
  22050. std::remove(sock_path.c_str());
  22051. Server svr;
  22052. std::mutex mtx;
  22053. std::string received_host;
  22054. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22055. {
  22056. std::lock_guard<std::mutex> lock(mtx);
  22057. received_host = req.get_header_value("Host");
  22058. }
  22059. std::string msg;
  22060. while (ws.read(msg)) {
  22061. ws.send(msg);
  22062. }
  22063. });
  22064. svr.set_address_family(AF_UNIX);
  22065. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  22066. auto se = detail::scope_exit([&] {
  22067. svr.stop();
  22068. t.join();
  22069. std::remove(sock_path.c_str());
  22070. });
  22071. svr.wait_until_ready();
  22072. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  22073. client.set_address_family(AF_UNIX);
  22074. ASSERT_TRUE(client.connect());
  22075. ASSERT_TRUE(client.send("hello"));
  22076. std::string msg;
  22077. ASSERT_TRUE(client.read(msg));
  22078. client.close();
  22079. {
  22080. std::lock_guard<std::mutex> lock(mtx);
  22081. // There is no host:port for a Unix socket, so the same "localhost"
  22082. // placeholder the HTTP client uses is expected.
  22083. EXPECT_EQ("localhost", received_host);
  22084. }
  22085. }
  22086. // Two threads must never parse WebSocket frames from the same stream.
  22087. // close() used to read the peer's Close reply with its own frame read, so it
  22088. // raced a reader thread that was in the middle of a payload: the payload loop
  22089. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  22090. // so bytes taken by close() were replaced with bytes from further along the
  22091. // stream. The message kept its length and silently changed content.
  22092. //
  22093. // The raw peer below sends a frame header plus part of the payload, waits for
  22094. // the handler to call close(), and only then sends the rest. Whichever thread
  22095. // would win the race for those bytes, the message must arrive intact, because
  22096. // close() must not touch the stream while read() owns it.
  22097. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  22098. #ifndef _WIN32
  22099. signal(SIGPIPE, SIG_IGN);
  22100. #endif
  22101. const size_t payload_len = 120; // fits the 7-bit length field
  22102. const size_t prefix_len = 8;
  22103. const int attempts = 8;
  22104. std::string expected(payload_len, '\0');
  22105. for (size_t i = 0; i < payload_len; i++) {
  22106. expected[i] = static_cast<char>('a' + i % 26);
  22107. }
  22108. std::atomic<bool> peer_stalled{false};
  22109. std::atomic<bool> handler_done{false};
  22110. std::mutex received_mutex;
  22111. std::vector<std::string> received;
  22112. // Bound every wait, so a regression fails the test instead of hanging the
  22113. // suite.
  22114. auto wait_for = [](const std::atomic<bool> &flag) {
  22115. for (int i = 0; i < 500 && !flag; i++) {
  22116. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22117. }
  22118. };
  22119. Server svr;
  22120. svr.set_websocket_ping_interval(0);
  22121. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22122. std::thread reader([&]() {
  22123. std::string msg;
  22124. while (ws.read(msg)) {
  22125. std::lock_guard<std::mutex> guard(received_mutex);
  22126. received.push_back(msg);
  22127. }
  22128. });
  22129. // Wait until the peer stalls mid-payload, so the reader thread is parked
  22130. // inside read_websocket_frame() when close() runs.
  22131. wait_for(peer_stalled);
  22132. ws.close();
  22133. reader.join();
  22134. handler_done = true;
  22135. });
  22136. auto port = svr.bind_to_any_port("127.0.0.1");
  22137. std::thread t([&]() { svr.listen_after_bind(); });
  22138. auto se = detail::scope_exit([&] {
  22139. svr.stop();
  22140. t.join();
  22141. });
  22142. svr.wait_until_ready();
  22143. auto send_bytes = [](socket_t s, const std::string &data) {
  22144. #ifdef _WIN32
  22145. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  22146. #else
  22147. auto n = ::send(s, data.data(), data.size(), 0);
  22148. #endif
  22149. return n == static_cast<decltype(n)>(data.size());
  22150. };
  22151. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  22152. // Every length used here fits the 7-bit length field.
  22153. auto masked_header = [](uint8_t first_byte, size_t len) {
  22154. std::string h;
  22155. h += static_cast<char>(first_byte);
  22156. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  22157. h.append(4, '\0'); // mask key
  22158. return h;
  22159. };
  22160. for (int attempt = 0; attempt < attempts; attempt++) {
  22161. peer_stalled = false;
  22162. handler_done = false;
  22163. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22164. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  22165. auto se_sock = detail::scope_exit([&] {
  22166. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  22167. });
  22168. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22169. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  22170. sockaddr_in addr{};
  22171. addr.sin_family = AF_INET;
  22172. addr.sin_port = htons(static_cast<uint16_t>(port));
  22173. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22174. ASSERT_EQ(
  22175. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  22176. << "attempt " << attempt;
  22177. ASSERT_TRUE(send_bytes(sock,
  22178. "GET /ws HTTP/1.1\r\n"
  22179. "Host: 127.0.0.1\r\n"
  22180. "Upgrade: websocket\r\n"
  22181. "Connection: Upgrade\r\n"
  22182. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22183. "Sec-WebSocket-Version: 13\r\n"
  22184. "\r\n"))
  22185. << "attempt " << attempt;
  22186. std::string response;
  22187. while (response.find("\r\n\r\n") == std::string::npos) {
  22188. char buf[512];
  22189. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  22190. if (n <= 0) { break; }
  22191. response.append(buf, static_cast<size_t>(n));
  22192. }
  22193. ASSERT_NE(std::string::npos, response.find(" 101 "))
  22194. << "attempt " << attempt;
  22195. // Send the header of a Binary message but only the first prefix_len bytes
  22196. // of its payload, leaving the reader thread stalled inside the payload.
  22197. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  22198. expected.substr(0, prefix_len)))
  22199. << "attempt " << attempt;
  22200. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22201. peer_stalled = true;
  22202. // Let close() send its Close frame and park in its own read before the
  22203. // rest of the payload arrives, so both threads are waiting for it.
  22204. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22205. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  22206. close_frame += static_cast<char>(0x03); // status 1000
  22207. close_frame += static_cast<char>(0xE8);
  22208. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  22209. << "attempt " << attempt;
  22210. // Closing the peer releases the reader thread even on the buggy path,
  22211. // where it waits for bytes another thread already consumed.
  22212. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22213. detail::close_socket(sock);
  22214. sock = INVALID_SOCKET;
  22215. wait_for(handler_done);
  22216. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  22217. }
  22218. std::lock_guard<std::mutex> guard(received_mutex);
  22219. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  22220. << "a message in flight when close() ran was dropped";
  22221. for (size_t i = 0; i < received.size(); i++) {
  22222. EXPECT_EQ(expected, received[i]) << "message " << i;
  22223. }
  22224. }
  22225. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  22226. std::atomic<bool> done{false};
  22227. std::string received;
  22228. Server svr;
  22229. svr.set_websocket_ping_interval(0);
  22230. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22231. std::string msg;
  22232. if (ws.read(msg) == ws::Binary) { received = msg; }
  22233. done = true;
  22234. });
  22235. auto port = svr.bind_to_any_port("127.0.0.1");
  22236. std::thread t([&]() { svr.listen_after_bind(); });
  22237. auto se = detail::scope_exit([&] {
  22238. svr.stop();
  22239. t.join();
  22240. });
  22241. svr.wait_until_ready();
  22242. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22243. ASSERT_NE(INVALID_SOCKET, sock);
  22244. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  22245. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22246. sockaddr_in addr{};
  22247. addr.sin_family = AF_INET;
  22248. addr.sin_port = htons(static_cast<uint16_t>(port));
  22249. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22250. ASSERT_EQ(0,
  22251. ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  22252. // Frames with an all-zero mask key, so the payload goes out verbatim.
  22253. auto frame = [](uint8_t first_byte, const std::string &payload) {
  22254. std::string f;
  22255. f += static_cast<char>(first_byte);
  22256. f += static_cast<char>(0x80 | payload.size());
  22257. f.append(4, '\0');
  22258. return f + payload;
  22259. };
  22260. std::string data = "GET /ws HTTP/1.1\r\n"
  22261. "Host: 127.0.0.1\r\n"
  22262. "Upgrade: websocket\r\n"
  22263. "Connection: Upgrade\r\n"
  22264. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22265. "Sec-WebSocket-Version: 13\r\n"
  22266. "\r\n";
  22267. data += frame(0x02, "Hel"); // Binary, more to come
  22268. data += frame(0x89, "p"); // FIN + Ping
  22269. data += frame(0x80, "lo"); // FIN + Continuation
  22270. #ifdef _WIN32
  22271. ::send(sock, data.data(), static_cast<int>(data.size()), 0);
  22272. #else
  22273. ::send(sock, data.data(), data.size(), 0);
  22274. #endif
  22275. for (int i = 0; i < 500 && !done; i++) {
  22276. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22277. }
  22278. ASSERT_TRUE(done);
  22279. EXPECT_EQ("Hello", received);
  22280. }
  22281. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22282. class WebSocketSSLIntegrationTest : public ::testing::Test {
  22283. protected:
  22284. void SetUp() override {
  22285. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  22286. SERVER_PRIVATE_KEY_FILE);
  22287. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22288. std::string msg;
  22289. ws::ReadResult ret;
  22290. while ((ret = ws.read(msg))) {
  22291. if (ret == ws::Binary) {
  22292. ws.send(msg.data(), msg.size());
  22293. } else {
  22294. ws.send(msg);
  22295. }
  22296. }
  22297. });
  22298. port_ = server_->bind_to_any_port(HOST);
  22299. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22300. server_->wait_until_ready();
  22301. }
  22302. void TearDown() override {
  22303. server_->stop();
  22304. if (server_thread_.joinable()) { server_thread_.join(); }
  22305. }
  22306. std::unique_ptr<SSLServer> server_;
  22307. std::thread server_thread_;
  22308. int port_ = 0;
  22309. };
  22310. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  22311. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22312. "/ws-echo");
  22313. client.enable_server_certificate_verification(false);
  22314. ASSERT_TRUE(client.connect());
  22315. ASSERT_TRUE(client.is_open());
  22316. ASSERT_TRUE(client.send("Hello WSS"));
  22317. std::string msg;
  22318. EXPECT_EQ(ws::Text, client.read(msg));
  22319. EXPECT_EQ("Hello WSS", msg);
  22320. client.close();
  22321. }
  22322. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  22323. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  22324. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  22325. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  22326. // client (without calling close() first) is the only path that runs
  22327. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  22328. // bug exactly.
  22329. //
  22330. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  22331. // when linked against an instrumented libssl; run under Valgrind to catch it
  22332. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  22333. // suite (the freed session otherwise stalls on the close handshake) — this test
  22334. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  22335. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  22336. {
  22337. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22338. "/ws-echo");
  22339. client.enable_server_certificate_verification(false);
  22340. client.set_read_timeout(2, 0);
  22341. client.set_write_timeout(2, 0);
  22342. ASSERT_TRUE(client.connect());
  22343. ASSERT_TRUE(client.is_open());
  22344. ASSERT_TRUE(client.send("still open"));
  22345. // Intentionally do NOT call client.close(): leaving scope runs
  22346. // shutdown_and_close() with the WebSocket still open, which must send the
  22347. // close frame while the TLS session is still alive.
  22348. }
  22349. }
  22350. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  22351. // shutdown_and_close() at the start of connect(), reproducing the same
  22352. // use-after-free within the test body rather than at scope exit. The second
  22353. // connect must succeed and echo, proving the close handshake ran over a live
  22354. // session. See the note above about memory-tool requirements.
  22355. TEST_F(WebSocketSSLIntegrationTest,
  22356. ReconnectWhileOpenSendsCloseOverLiveSession) {
  22357. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22358. "/ws-echo");
  22359. client.enable_server_certificate_verification(false);
  22360. client.set_read_timeout(2, 0);
  22361. client.set_write_timeout(2, 0);
  22362. ASSERT_TRUE(client.connect());
  22363. ASSERT_TRUE(client.is_open());
  22364. ASSERT_TRUE(client.send("still open"));
  22365. // Reconnect without closing first: connect() calls shutdown_and_close() on
  22366. // the still-open connection, which must not touch a freed TLS session.
  22367. ASSERT_TRUE(client.connect());
  22368. ASSERT_TRUE(client.is_open());
  22369. ASSERT_TRUE(client.send("after reconnect"));
  22370. std::string msg;
  22371. EXPECT_EQ(ws::Text, client.read(msg));
  22372. EXPECT_EQ("after reconnect", msg);
  22373. client.close();
  22374. }
  22375. #endif
  22376. #ifdef CPPHTTPLIB_SSL_ENABLED
  22377. class WebSocketSSLCATest : public ::testing::Test {
  22378. protected:
  22379. void SetUp() override {
  22380. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  22381. SERVER_PRIVATE_KEY_FILE);
  22382. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22383. std::string msg;
  22384. while (ws.read(msg)) {
  22385. ws.send(msg);
  22386. }
  22387. });
  22388. port_ = server_->bind_to_any_port("127.0.0.1");
  22389. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22390. server_->wait_until_ready();
  22391. }
  22392. void TearDown() override {
  22393. server_->stop();
  22394. if (server_thread_.joinable()) { server_thread_.join(); }
  22395. }
  22396. std::string url() const {
  22397. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  22398. }
  22399. std::unique_ptr<SSLServer> server_;
  22400. std::thread server_thread_;
  22401. int port_ = 0;
  22402. };
  22403. // A custom CA loaded as PEM verifies the server with full certificate
  22404. // verification enabled
  22405. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  22406. ws::WebSocketClient client(url());
  22407. std::string cert;
  22408. read_file(SERVER_CERT2_FILE, cert);
  22409. client.load_ca_cert_store(cert.c_str(), cert.size());
  22410. ASSERT_TRUE(client.connect());
  22411. ASSERT_TRUE(client.send("hello"));
  22412. std::string msg;
  22413. EXPECT_EQ(ws::Text, client.read(msg));
  22414. EXPECT_EQ("hello", msg);
  22415. client.close();
  22416. }
  22417. // A custom CA that does not cover the server must fail verification (the
  22418. // custom CA is exclusive; system certs are not loaded alongside it)
  22419. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  22420. ws::WebSocketClient client(url());
  22421. std::string cert;
  22422. read_file(CLIENT_CA_CERT_FILE, cert);
  22423. client.load_ca_cert_store(cert.c_str(), cert.size());
  22424. auto res = client.connect();
  22425. ASSERT_FALSE(res);
  22426. EXPECT_EQ(Error::SSLServerVerification, res.error());
  22427. EXPECT_EQ(-1, res.status());
  22428. EXPECT_NE(0u, res.ssl_backend_error());
  22429. }
  22430. // The same CA as a file path rather than PEM in memory
  22431. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  22432. ws::WebSocketClient client(url());
  22433. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22434. ASSERT_TRUE(client.connect());
  22435. ASSERT_TRUE(client.send("hello"));
  22436. std::string msg;
  22437. EXPECT_EQ(ws::Text, client.read(msg));
  22438. EXPECT_EQ("hello", msg);
  22439. client.close();
  22440. }
  22441. // ...and a CA file that does not cover the server still fails, so it is the
  22442. // path above that decides the outcome
  22443. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  22444. ws::WebSocketClient client(url());
  22445. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22446. ASSERT_FALSE(client.connect());
  22447. }
  22448. // Regression test: reconnecting with a native custom CA store used to reuse
  22449. // a store handle the previous TLS context had already freed (use-after-free
  22450. // under the OpenSSL backend). The context now lives as long as the client.
  22451. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  22452. ws::WebSocketClient client(url());
  22453. std::string cert;
  22454. read_file(SERVER_CERT2_FILE, cert);
  22455. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  22456. ASSERT_TRUE(client.connect());
  22457. client.close();
  22458. ASSERT_TRUE(client.connect());
  22459. ASSERT_TRUE(client.send("again"));
  22460. std::string msg;
  22461. EXPECT_EQ(ws::Text, client.read(msg));
  22462. EXPECT_EQ("again", msg);
  22463. client.close();
  22464. }
  22465. // Regression test: a certificate with a trusted chain but no identity match
  22466. // for the server IP must be rejected. The Mbed TLS backend used to skip
  22467. // verification entirely for IP hosts, so this connection succeeded there.
  22468. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  22469. // chain verification while the identity check must still fail.
  22470. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  22471. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22472. ASSERT_TRUE(svr.is_valid());
  22473. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22474. std::string msg;
  22475. while (ws.read(msg)) {
  22476. ws.send(msg);
  22477. }
  22478. });
  22479. auto port = svr.bind_to_any_port("127.0.0.1");
  22480. auto t = std::thread([&]() { svr.listen_after_bind(); });
  22481. auto se = detail::scope_exit([&] {
  22482. svr.stop();
  22483. t.join();
  22484. });
  22485. svr.wait_until_ready();
  22486. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  22487. "/echo");
  22488. std::string cert;
  22489. read_file(SERVER_CERT_FILE, cert);
  22490. client.load_ca_cert_store(cert.c_str(), cert.size());
  22491. ASSERT_FALSE(client.connect());
  22492. }
  22493. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  22494. // SNI, so nothing binds the host name to the TLS session. These bind the
  22495. // server to "localhost" instead, the only shape that exercises the SNI and
  22496. // hostname-verification path with certificate verification left enabled.
  22497. class WebSocketSSLDnsHostTest : public ::testing::Test {
  22498. protected:
  22499. void Start(const char *cert_file) {
  22500. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  22501. SERVER_PRIVATE_KEY_FILE);
  22502. ASSERT_TRUE(server_->is_valid());
  22503. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22504. std::string msg;
  22505. while (ws.read(msg)) {
  22506. ws.send(msg);
  22507. }
  22508. });
  22509. port_ = server_->bind_to_any_port("localhost");
  22510. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22511. server_->wait_until_ready();
  22512. }
  22513. void TearDown() override {
  22514. if (server_) { server_->stop(); }
  22515. if (server_thread_.joinable()) { server_thread_.join(); }
  22516. }
  22517. std::string url() const {
  22518. return "wss://localhost:" + std::to_string(port_) + "/echo";
  22519. }
  22520. std::unique_ptr<SSLServer> server_;
  22521. std::thread server_thread_;
  22522. int port_ = 0;
  22523. };
  22524. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  22525. // out and the connection is usable
  22526. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  22527. Start(SERVER_CERT2_FILE);
  22528. ws::WebSocketClient client(url());
  22529. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22530. ASSERT_TRUE(client.connect());
  22531. ASSERT_TRUE(client.send("hello"));
  22532. std::string msg;
  22533. EXPECT_EQ(ws::Text, client.read(msg));
  22534. EXPECT_EQ("hello", msg);
  22535. client.close();
  22536. }
  22537. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  22538. // while the identity check must still reject "localhost"
  22539. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  22540. Start(SERVER_CERT_FILE);
  22541. ws::WebSocketClient client(url());
  22542. client.set_ca_cert_path(SERVER_CERT_FILE);
  22543. auto res = client.connect();
  22544. ASSERT_FALSE(res);
  22545. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  22546. EXPECT_EQ(-1, res.status());
  22547. }
  22548. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  22549. // disabled: the chain is still checked, only the identity check is skipped
  22550. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  22551. Start(SERVER_CERT_FILE);
  22552. ws::WebSocketClient client(url());
  22553. client.set_ca_cert_path(SERVER_CERT_FILE);
  22554. client.enable_server_hostname_verification(false);
  22555. ASSERT_TRUE(client.connect());
  22556. ASSERT_TRUE(client.send("hello"));
  22557. std::string msg;
  22558. EXPECT_EQ(ws::Text, client.read(msg));
  22559. EXPECT_EQ("hello", msg);
  22560. client.close();
  22561. }
  22562. // A CA that did not sign the server certificate fails the chain, even though
  22563. // the name would match
  22564. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  22565. Start(SERVER_CERT2_FILE);
  22566. ws::WebSocketClient client(url());
  22567. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22568. ASSERT_FALSE(client.connect());
  22569. }
  22570. // With verification disabled, neither the chain nor the name is checked
  22571. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  22572. Start(SERVER_CERT_FILE);
  22573. ws::WebSocketClient client(url());
  22574. client.enable_server_certificate_verification(false);
  22575. ASSERT_TRUE(client.connect());
  22576. ASSERT_TRUE(client.send("hello"));
  22577. std::string msg;
  22578. EXPECT_EQ(ws::Text, client.read(msg));
  22579. EXPECT_EQ("hello", msg);
  22580. client.close();
  22581. }
  22582. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  22583. protected:
  22584. void SetUp() override {
  22585. server_ = httplib::detail::make_unique<SSLServer>(
  22586. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22587. ASSERT_TRUE(server_->is_valid());
  22588. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22589. std::string msg;
  22590. while (ws.read(msg)) {
  22591. ws.send(msg);
  22592. }
  22593. });
  22594. port_ = server_->bind_to_any_port("localhost");
  22595. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22596. server_->wait_until_ready();
  22597. }
  22598. void TearDown() override {
  22599. server_->stop();
  22600. if (server_thread_.joinable()) { server_thread_.join(); }
  22601. }
  22602. std::string url() const {
  22603. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22604. }
  22605. void ConnectWithClientCert(const std::string &client_cert_file,
  22606. const std::string &client_private_key_file,
  22607. const char *private_key_password) {
  22608. std::string cert_pem, key_pem;
  22609. read_file(client_cert_file, cert_pem);
  22610. read_file(client_private_key_file, key_pem);
  22611. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  22612. key_pem.c_str(), key_pem.size(),
  22613. private_key_password};
  22614. ws::WebSocketClient client(url(), pem);
  22615. ASSERT_TRUE(client.is_valid());
  22616. client.enable_server_certificate_verification(false);
  22617. ASSERT_TRUE(client.connect());
  22618. ASSERT_TRUE(client.send("hello"));
  22619. std::string msg;
  22620. EXPECT_EQ(ws::Text, client.read(msg));
  22621. EXPECT_EQ("hello", msg);
  22622. client.close();
  22623. }
  22624. std::unique_ptr<SSLServer> server_;
  22625. std::thread server_thread_;
  22626. int port_ = 0;
  22627. };
  22628. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  22629. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  22630. }
  22631. // Control for the tests above: the fixture's server really does require a
  22632. // client certificate, so it is the PEM the constructor installed that decides
  22633. // the outcome.
  22634. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  22635. ws::WebSocketClient client(url());
  22636. ASSERT_TRUE(client.is_valid());
  22637. client.enable_server_certificate_verification(false);
  22638. EXPECT_FALSE(client.connect());
  22639. }
  22640. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  22641. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  22642. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  22643. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  22644. }
  22645. #endif
  22646. #if !defined(_WIN32)
  22647. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  22648. auto secret_dir = std::string("./symlink_test_secret");
  22649. auto served_dir = std::string("./symlink_test_served");
  22650. auto secret_file = secret_dir + "/secret.txt";
  22651. auto symlink_path = served_dir + "/escape";
  22652. // Setup: create directories and files
  22653. mkdir(secret_dir.c_str(), 0755);
  22654. mkdir(served_dir.c_str(), 0755);
  22655. {
  22656. std::ofstream ofs(secret_file);
  22657. ofs << "SECRET_DATA";
  22658. }
  22659. // Create symlink using absolute path so it resolves correctly
  22660. #ifdef PATH_MAX
  22661. char abs_secret[PATH_MAX];
  22662. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  22663. #else
  22664. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  22665. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  22666. ASSERT_NE(nullptr, abs_secret);
  22667. #endif
  22668. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  22669. auto se = detail::scope_exit([&] {
  22670. unlink(symlink_path.c_str());
  22671. unlink(secret_file.c_str());
  22672. rmdir(served_dir.c_str());
  22673. rmdir(secret_dir.c_str());
  22674. });
  22675. Server svr;
  22676. svr.set_mount_point("/", served_dir);
  22677. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  22678. auto se2 = detail::scope_exit([&] {
  22679. svr.stop();
  22680. listen_thread.join();
  22681. });
  22682. svr.wait_until_ready();
  22683. Client cli("localhost", PORT);
  22684. // Symlink pointing outside base dir should be blocked
  22685. auto res = cli.Get("/escape/secret.txt");
  22686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22687. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  22688. }
  22689. #endif
  22690. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  22691. // "GET /smuggled" request), reads the first response, and only then sends the
  22692. // embedded request as the body. Returns how many times /smuggled ran.
  22693. //
  22694. // The body is sent AFTER receiving the first response (as in the original
  22695. // PoC) so that the stream_line_reader cannot buffer it together with the
  22696. // headers of the first request.
  22697. static int count_smuggled_requests(const std::string &outer_head,
  22698. std::string &first_response) {
  22699. Server svr;
  22700. svr.set_mount_point("/", "./www");
  22701. std::atomic<int> smuggled_count(0);
  22702. svr.Get("/smuggled", [&](const Request &, Response &res) {
  22703. smuggled_count++;
  22704. res.set_content("oops", "text/plain");
  22705. });
  22706. svr.Post("/post", [&](const Request &req, Response &res) {
  22707. res.set_content(req.body, "text/plain");
  22708. });
  22709. auto port = svr.bind_to_any_port("localhost");
  22710. thread t = thread([&] { svr.listen_after_bind(); });
  22711. auto se = detail::scope_exit([&] {
  22712. svr.stop();
  22713. t.join();
  22714. });
  22715. svr.wait_until_ready();
  22716. auto error = Error::Success;
  22717. auto sock = detail::create_client_socket(
  22718. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  22719. /*connection_timeout_sec=*/2, 0,
  22720. /*read_timeout_sec=*/2, 0,
  22721. /*write_timeout_sec=*/2, 0, std::string(), error);
  22722. EXPECT_NE(INVALID_SOCKET, sock);
  22723. if (sock == INVALID_SOCKET) { return -1; }
  22724. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22725. // The "smuggled" request will be sent as the body of the outer request
  22726. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  22727. "Host: localhost\r\n"
  22728. "Connection: close\r\n"
  22729. "\r\n";
  22730. auto head = outer_head;
  22731. auto len = std::to_string(smuggled.size());
  22732. for (auto pos = head.find("{len}"); pos != std::string::npos;
  22733. pos = head.find("{len}", pos + len.size())) {
  22734. head.replace(pos, 5, len);
  22735. }
  22736. // Step 1: Send only the outer request headers (no body yet)
  22737. auto sent = send(sock, head.data(), head.size(), 0);
  22738. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  22739. // Step 2: Read the first response
  22740. char buf[4096];
  22741. for (;;) {
  22742. auto n = recv(sock, buf, sizeof(buf), 0);
  22743. if (n <= 0) break;
  22744. first_response.append(buf, static_cast<size_t>(n));
  22745. // Stop once we have a complete response (headers + body)
  22746. auto hdr_end = first_response.find("\r\n\r\n");
  22747. if (hdr_end != std::string::npos) {
  22748. // Check for Content-Length to know when the body is complete
  22749. auto cl_pos = first_response.find("Content-Length:");
  22750. if (cl_pos != std::string::npos) {
  22751. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  22752. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  22753. auto cl = std::stoul(
  22754. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  22755. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  22756. } else {
  22757. break; // No Content-Length, assume headers-only response
  22758. }
  22759. }
  22760. }
  22761. // Step 3: Now send the body, which looks like a new HTTP request. On a
  22762. // vulnerable server the keep-alive loop reads this as a second request. The
  22763. // server may already have closed the connection, so the result is ignored.
  22764. send(sock, smuggled.data(), smuggled.size(), 0);
  22765. // Half-close so that a server which drained the body sees EOF and closes,
  22766. // instead of the read below waiting for the read timeout.
  22767. #ifdef _WIN32
  22768. ::shutdown(sock, SD_SEND);
  22769. #else
  22770. ::shutdown(sock, SHUT_WR);
  22771. #endif
  22772. // Step 4: Read until the server closes the connection
  22773. for (;;) {
  22774. auto n = recv(sock, buf, sizeof(buf), 0);
  22775. if (n <= 0) break;
  22776. }
  22777. return smuggled_count.load();
  22778. }
  22779. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  22780. // A GET request with Content-Length to a static file handler must have its
  22781. // body drained before the keep-alive connection is reused. Otherwise the
  22782. // unread body bytes are interpreted as the next HTTP request.
  22783. std::string first_response;
  22784. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22785. "Host: localhost\r\n"
  22786. "Content-Length: {len}\r\n"
  22787. "\r\n",
  22788. first_response));
  22789. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  22790. }
  22791. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  22792. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  22793. // be answered with 400 and the connection closed. Treating it as "no body"
  22794. // leaves the body to be parsed as the next request.
  22795. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  22796. const char *targets[] = {
  22797. "GET /file", // handler that never reads the body
  22798. "GET /not-found", // no handler matches (404)
  22799. "POST /post", // handler that reads the body
  22800. };
  22801. for (auto target : targets) {
  22802. for (auto value : values) {
  22803. std::string first_response;
  22804. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  22805. " HTTP/1.1\r\n"
  22806. "Host: localhost\r\n"
  22807. "Content-Length: " +
  22808. value + "\r\n\r\n",
  22809. first_response))
  22810. << target << " with Content-Length: " << value;
  22811. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  22812. << target << " with Content-Length: " << value;
  22813. }
  22814. }
  22815. }
  22816. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  22817. // A 400 for an unparseable request line leaves the rest of the message
  22818. // unread, so the connection must be closed rather than reused.
  22819. std::string first_response;
  22820. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  22821. "Host: localhost\r\n"
  22822. "Content-Length: {len}\r\n"
  22823. "\r\n",
  22824. first_response));
  22825. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22826. }
  22827. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  22828. // Same as above for a header block that fails to parse.
  22829. std::string first_response;
  22830. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22831. "Host: localhost\r\n"
  22832. "Bad Header\r\n"
  22833. "Content-Length: {len}\r\n"
  22834. "\r\n",
  22835. first_response));
  22836. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22837. }
  22838. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  22839. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  22840. // server must not read another request on that connection, even when the
  22841. // request had no body to drain.
  22842. std::string first_response;
  22843. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  22844. "Host: localhost\r\n"
  22845. "\r\n",
  22846. first_response));
  22847. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  22848. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  22849. }
  22850. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  22851. // A content reader that stops early leaves the stream inside the body.
  22852. // Draining the whole Content-Length from there, or reading the body again,
  22853. // reads into the next request, and whatever follows is parsed as a request
  22854. // of its own.
  22855. Server svr;
  22856. std::atomic<int> smuggled_count(0);
  22857. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  22858. svr.Post("/upload", [](const Request &req, Response &res,
  22859. const ContentReader &content_reader) {
  22860. // Stop at the last chunk, so the whole body has been read however it
  22861. // arrives.
  22862. auto length = req.get_header_value_u64("Content-Length");
  22863. size_t total = 0;
  22864. auto consumed = content_reader([&](const char *, size_t n) {
  22865. total += n;
  22866. return total < length;
  22867. });
  22868. EXPECT_FALSE(consumed);
  22869. if (req.has_param("retry")) {
  22870. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  22871. }
  22872. // Replace the 400 the aborted read set, which would close the connection.
  22873. res.set_redirect("/done");
  22874. });
  22875. auto port = svr.bind_to_any_port(HOST);
  22876. thread t = thread([&] { svr.listen_after_bind(); });
  22877. auto se = detail::scope_exit([&] {
  22878. svr.stop();
  22879. t.join();
  22880. });
  22881. svr.wait_until_ready();
  22882. // A front end sees the second request as a POST whose body is the GET. The
  22883. // first body is as long as the POST's headers, so draining it again reads
  22884. // exactly those and leaves the GET to be parsed next.
  22885. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  22886. "Host: localhost\r\n"
  22887. "\r\n";
  22888. std::string second_head = "POST /post HTTP/1.1\r\n"
  22889. "Host: localhost\r\n"
  22890. "Content-Length: " +
  22891. std::to_string(inner.size()) +
  22892. "\r\n"
  22893. "\r\n";
  22894. for (auto target : {"/upload", "/upload?retry"}) {
  22895. smuggled_count = 0;
  22896. std::string request = "POST " + std::string(target) +
  22897. " HTTP/1.1\r\n"
  22898. "Host: localhost\r\n"
  22899. "Content-Length: " +
  22900. std::to_string(second_head.size()) +
  22901. "\r\n"
  22902. "\r\n" +
  22903. std::string(second_head.size(), 'A') + second_head +
  22904. inner;
  22905. std::string response;
  22906. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  22907. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  22908. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  22909. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  22910. EXPECT_EQ(0, smuggled_count.load()) << target;
  22911. }
  22912. }
  22913. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  22914. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  22915. // must be rejected with 400 Bad Request.
  22916. Server svr;
  22917. svr.Post("/test", [&](const Request &, Response &res) {
  22918. res.set_content("ok", "text/plain");
  22919. });
  22920. thread t = thread([&] { svr.listen(HOST, PORT); });
  22921. auto se = detail::scope_exit([&] {
  22922. svr.stop();
  22923. t.join();
  22924. ASSERT_FALSE(svr.is_running());
  22925. });
  22926. svr.wait_until_ready();
  22927. // Exact "chunked"
  22928. {
  22929. auto req = "POST /test HTTP/1.1\r\n"
  22930. "Host: localhost\r\n"
  22931. "Content-Length: 5\r\n"
  22932. "Transfer-Encoding: chunked\r\n"
  22933. "Connection: close\r\n"
  22934. "\r\n"
  22935. "hello";
  22936. std::string response;
  22937. ASSERT_TRUE(send_request(1, req, &response));
  22938. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22939. response.substr(0, response.find("\r\n")));
  22940. }
  22941. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  22942. {
  22943. auto req = "POST /test HTTP/1.1\r\n"
  22944. "Host: localhost\r\n"
  22945. "Content-Length: 5\r\n"
  22946. "Transfer-Encoding: gzip, chunked\r\n"
  22947. "Connection: close\r\n"
  22948. "\r\n"
  22949. "hello";
  22950. std::string response;
  22951. ASSERT_TRUE(send_request(1, req, &response));
  22952. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22953. response.substr(0, response.find("\r\n")));
  22954. }
  22955. }
  22956. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  22957. Server svr;
  22958. svr.Post("/test", [&](const Request &, Response &res) {
  22959. res.set_content("ok", "text/plain");
  22960. });
  22961. thread t = thread([&] { svr.listen(HOST, PORT); });
  22962. auto se = detail::scope_exit([&] {
  22963. svr.stop();
  22964. t.join();
  22965. ASSERT_FALSE(svr.is_running());
  22966. });
  22967. svr.wait_until_ready();
  22968. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  22969. // length cannot be determined, so the server must answer 400 and close
  22970. // rather than treat the request as bodyless and leave the body in the
  22971. // socket for the next request to pick up.
  22972. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  22973. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  22974. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  22975. std::string response;
  22976. ASSERT_TRUE(send_request(1, req, &response));
  22977. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22978. response.substr(0, response.find("\r\n")))
  22979. << transfer_encoding;
  22980. }
  22981. // RFC 9110 5.3: the codings may also be split across several
  22982. // Transfer-Encoding lines, which combine in the order they were received.
  22983. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  22984. // just like the single-line "chunked, gzip" above.
  22985. {
  22986. auto req = "POST /test HTTP/1.1\r\n"
  22987. "Host: localhost\r\n"
  22988. "Transfer-Encoding: chunked\r\n"
  22989. "Transfer-Encoding: gzip\r\n"
  22990. "\r\n"
  22991. "0\r\n\r\n";
  22992. std::string response;
  22993. ASSERT_TRUE(send_request(1, req, &response));
  22994. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22995. response.substr(0, response.find("\r\n")));
  22996. }
  22997. // A sequence ending in chunked stays valid.
  22998. auto req = "POST /test HTTP/1.1\r\n"
  22999. "Host: localhost\r\n"
  23000. "Transfer-Encoding: gzip, chunked\r\n"
  23001. "Connection: close\r\n"
  23002. "\r\n"
  23003. "0\r\n\r\n";
  23004. std::string response;
  23005. ASSERT_TRUE(send_request(1, req, &response));
  23006. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  23007. // ...including when it is spread over several lines.
  23008. auto split_req = "POST /test HTTP/1.1\r\n"
  23009. "Host: localhost\r\n"
  23010. "Transfer-Encoding: gzip\r\n"
  23011. "Transfer-Encoding: chunked\r\n"
  23012. "Connection: close\r\n"
  23013. "\r\n"
  23014. "0\r\n\r\n";
  23015. std::string split_response;
  23016. ASSERT_TRUE(send_request(1, split_req, &split_response));
  23017. EXPECT_EQ("HTTP/1.1 200 OK",
  23018. split_response.substr(0, split_response.find("\r\n")));
  23019. }
  23020. // Regression for issue #2450: a DELETE without Content-Length on a
  23021. // keep-alive connection must not let the post-response drain consume the
  23022. // next request's bytes.
  23023. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  23024. Server svr;
  23025. std::atomic<int> delete_count(0);
  23026. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  23027. delete_count++;
  23028. res.status = StatusCode::NoContent_204;
  23029. });
  23030. auto port = svr.bind_to_any_port(HOST);
  23031. thread t = thread([&] { svr.listen_after_bind(); });
  23032. auto se = detail::scope_exit([&] {
  23033. svr.stop();
  23034. t.join();
  23035. });
  23036. svr.wait_until_ready();
  23037. auto error = Error::Success;
  23038. auto sock = detail::create_client_socket(
  23039. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23040. /*connection_timeout_sec=*/2, 0,
  23041. /*read_timeout_sec=*/2, 0,
  23042. /*write_timeout_sec=*/2, 0, std::string(), error);
  23043. ASSERT_NE(INVALID_SOCKET, sock);
  23044. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23045. auto send_request_and_read_response = [&](const std::string &req,
  23046. std::string &out) -> bool {
  23047. auto sent = send(sock, req.data(), req.size(), 0);
  23048. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  23049. char buf[4096];
  23050. for (;;) {
  23051. auto n = recv(sock, buf, sizeof(buf), 0);
  23052. if (n <= 0) { return !out.empty(); }
  23053. out.append(buf, static_cast<size_t>(n));
  23054. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  23055. }
  23056. };
  23057. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  23058. "Host: localhost\r\n"
  23059. "\r\n";
  23060. std::string resp1;
  23061. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  23062. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  23063. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  23064. "Host: localhost\r\n"
  23065. "Connection: close\r\n"
  23066. "\r\n";
  23067. std::string resp2;
  23068. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  23069. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  23070. EXPECT_EQ(2, delete_count.load());
  23071. }
  23072. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  23073. Server svr;
  23074. svr.Post("/ingest", [&](const Request &, Response &res,
  23075. const ContentReader &content_reader) {
  23076. auto consumed = content_reader([](const char *, size_t) { return false; });
  23077. EXPECT_FALSE(consumed);
  23078. res.status = StatusCode::Conflict_409;
  23079. res.set_header("Connection", "close");
  23080. });
  23081. auto port = svr.bind_to_any_port(HOST);
  23082. thread t = thread([&] { svr.listen_after_bind(); });
  23083. auto se = detail::scope_exit([&] {
  23084. svr.stop();
  23085. t.join();
  23086. });
  23087. svr.wait_until_ready();
  23088. auto error = Error::Success;
  23089. auto sock = detail::create_client_socket(
  23090. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23091. /*connection_timeout_sec=*/2, 0,
  23092. /*read_timeout_sec=*/1, 0,
  23093. /*write_timeout_sec=*/2, 0, std::string(), error);
  23094. ASSERT_NE(INVALID_SOCKET, sock);
  23095. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23096. std::string request = "POST /ingest HTTP/1.1\r\n"
  23097. "Host: localhost\r\n"
  23098. "Transfer-Encoding: chunked\r\n"
  23099. "\r\n"
  23100. "4\r\n"
  23101. "data\r\n";
  23102. auto sent = send(sock, request.data(), request.size(), 0);
  23103. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  23104. std::string response;
  23105. ssize_t received = 0;
  23106. do {
  23107. char buf[4096];
  23108. received = recv(sock, buf, sizeof(buf), 0);
  23109. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  23110. } while (received > 0);
  23111. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  23112. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  23113. EXPECT_EQ(0, received);
  23114. }
  23115. namespace no_proxy_test {
  23116. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  23117. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  23118. // calling listen().
  23119. class ScopedServer {
  23120. public:
  23121. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  23122. ~ScopedServer() {
  23123. svr_.stop();
  23124. if (th_.joinable()) { th_.join(); }
  23125. }
  23126. Server &svr() { return svr_; }
  23127. int port() const { return port_; }
  23128. void listen() {
  23129. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23130. svr_.wait_until_ready();
  23131. }
  23132. private:
  23133. Server svr_;
  23134. std::thread th_;
  23135. int port_ = 0;
  23136. };
  23137. class ProxyAndTargetServers {
  23138. public:
  23139. ProxyAndTargetServers() {
  23140. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  23141. proxy_hits_++;
  23142. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23143. res.set_content("via-proxy", "text/plain");
  23144. });
  23145. target_.Get(".*", [this](const Request &req, Response &res) {
  23146. target_hits_++;
  23147. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23148. res.set_content("direct", "text/plain");
  23149. });
  23150. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  23151. target_port_ = target_.bind_to_any_port("127.0.0.1");
  23152. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  23153. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  23154. proxy_mock_.wait_until_ready();
  23155. target_.wait_until_ready();
  23156. }
  23157. ~ProxyAndTargetServers() {
  23158. proxy_mock_.stop();
  23159. target_.stop();
  23160. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  23161. if (target_thread_.joinable()) { target_thread_.join(); }
  23162. }
  23163. Server &proxy_mock() { return proxy_mock_; }
  23164. Server &target() { return target_; }
  23165. int proxy_port() const { return proxy_port_; }
  23166. int target_port() const { return target_port_; }
  23167. int proxy_hits() const { return proxy_hits_.load(); }
  23168. int target_hits() const { return target_hits_.load(); }
  23169. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  23170. void reset_counters() {
  23171. proxy_hits_ = 0;
  23172. target_hits_ = 0;
  23173. last_had_proxy_authz_ = false;
  23174. }
  23175. private:
  23176. Server proxy_mock_;
  23177. Server target_;
  23178. std::thread proxy_thread_;
  23179. std::thread target_thread_;
  23180. int proxy_port_ = 0;
  23181. int target_port_ = 0;
  23182. std::atomic<int> proxy_hits_{0};
  23183. std::atomic<int> target_hits_{0};
  23184. std::atomic<bool> last_had_proxy_authz_{false};
  23185. };
  23186. inline std::unique_ptr<Client> make_client(const std::string &host,
  23187. ProxyAndTargetServers &s) {
  23188. auto cli = detail::make_unique<Client>(host, s.target_port());
  23189. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  23190. cli->set_proxy("127.0.0.1", s.proxy_port());
  23191. return cli;
  23192. }
  23193. } // namespace no_proxy_test
  23194. using no_proxy_test::make_client;
  23195. using no_proxy_test::ProxyAndTargetServers;
  23196. TEST(NoProxyTest, ExactHostnameBypasses) {
  23197. ProxyAndTargetServers s;
  23198. auto cli = make_client("example.com", s);
  23199. cli->set_no_proxy({"example.com"});
  23200. auto res = cli->Get("/");
  23201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23202. EXPECT_EQ(0, s.proxy_hits());
  23203. EXPECT_EQ(1, s.target_hits());
  23204. }
  23205. TEST(NoProxyTest, SubdomainBypasses) {
  23206. ProxyAndTargetServers s;
  23207. auto cli = make_client("foo.example.com", s);
  23208. cli->set_no_proxy({"example.com"});
  23209. auto res = cli->Get("/");
  23210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23211. EXPECT_EQ(0, s.proxy_hits());
  23212. EXPECT_EQ(1, s.target_hits());
  23213. }
  23214. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  23215. // Regression guard: "evilexample.com" must not be considered a subdomain
  23216. // of "example.com". Without the dot-boundary rule, a naive endsWith
  23217. // check would let traffic bypass the proxy and leak credentials direct
  23218. // to the attacker host.
  23219. ProxyAndTargetServers s;
  23220. auto cli = make_client("evilexample.com", s);
  23221. cli->set_no_proxy({"example.com"});
  23222. auto res = cli->Get("/");
  23223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23224. EXPECT_GE(s.proxy_hits(), 1);
  23225. EXPECT_EQ(0, s.target_hits());
  23226. }
  23227. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  23228. ProxyAndTargetServers s;
  23229. auto cli = make_client("example.com.evil.com", s);
  23230. cli->set_no_proxy({"example.com"});
  23231. auto res = cli->Get("/");
  23232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23233. EXPECT_GE(s.proxy_hits(), 1);
  23234. EXPECT_EQ(0, s.target_hits());
  23235. }
  23236. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  23237. ProxyAndTargetServers s;
  23238. auto cli = make_client("example.com", s);
  23239. cli->set_no_proxy({".example.com"});
  23240. auto res = cli->Get("/");
  23241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23242. EXPECT_EQ(0, s.proxy_hits());
  23243. EXPECT_EQ(1, s.target_hits());
  23244. }
  23245. TEST(NoProxyTest, CaseInsensitiveHostname) {
  23246. ProxyAndTargetServers s;
  23247. auto cli = make_client("Example.COM", s);
  23248. cli->set_no_proxy({"EXAMPLE.com"});
  23249. auto res = cli->Get("/");
  23250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23251. EXPECT_EQ(0, s.proxy_hits());
  23252. EXPECT_EQ(1, s.target_hits());
  23253. }
  23254. TEST(NoProxyTest, TrailingDotIsNormalized) {
  23255. ProxyAndTargetServers s;
  23256. auto cli = make_client("example.com.", s);
  23257. cli->set_no_proxy({"example.com"});
  23258. auto res = cli->Get("/");
  23259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23260. EXPECT_EQ(0, s.proxy_hits());
  23261. EXPECT_EQ(1, s.target_hits());
  23262. }
  23263. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  23264. // Trailing dots must be normalized on BOTH sides — host and entry.
  23265. // An implementation that only strips the host-side trailing dot would
  23266. // fail to match host "example.com" against entry "example.com." because
  23267. // a literal substring search would compare 11 chars against 12.
  23268. ProxyAndTargetServers s;
  23269. auto cli = make_client("example.com", s);
  23270. cli->set_no_proxy({"example.com."});
  23271. auto res = cli->Get("/");
  23272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23273. EXPECT_EQ(0, s.proxy_hits());
  23274. EXPECT_EQ(1, s.target_hits());
  23275. }
  23276. TEST(NoProxyTest, WildcardBypassesEverything) {
  23277. ProxyAndTargetServers s;
  23278. auto cli = make_client("anything.invalid.test", s);
  23279. cli->set_no_proxy({"*"});
  23280. auto res = cli->Get("/");
  23281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23282. EXPECT_EQ(0, s.proxy_hits());
  23283. EXPECT_EQ(1, s.target_hits());
  23284. }
  23285. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  23286. ProxyAndTargetServers s;
  23287. Client cli("127.0.0.1", s.target_port());
  23288. cli.set_proxy("127.0.0.1", s.proxy_port());
  23289. cli.set_no_proxy({"127.0.0.1"});
  23290. auto res = cli.Get("/");
  23291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23292. EXPECT_EQ(0, s.proxy_hits());
  23293. EXPECT_EQ(1, s.target_hits());
  23294. }
  23295. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  23296. ProxyAndTargetServers s;
  23297. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  23298. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  23299. cli.set_proxy("127.0.0.1", s.proxy_port());
  23300. cli.set_no_proxy({"::1"});
  23301. auto res = cli.Get("/");
  23302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23303. EXPECT_EQ(0, s.proxy_hits());
  23304. EXPECT_EQ(1, s.target_hits());
  23305. }
  23306. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  23307. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  23308. // must still be recognized as IPv6 for CIDR matching. Implementations
  23309. // that detect IPv6 only when the host begins with '[' would parse the
  23310. // host as a hostname and miss the match.
  23311. ProxyAndTargetServers s;
  23312. Client cli("fe80::1", s.target_port());
  23313. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23314. cli.set_proxy("127.0.0.1", s.proxy_port());
  23315. cli.set_no_proxy({"fe80::/10"});
  23316. auto res = cli.Get("/");
  23317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23318. EXPECT_EQ(0, s.proxy_hits());
  23319. EXPECT_EQ(1, s.target_hits());
  23320. }
  23321. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  23322. ProxyAndTargetServers s;
  23323. Client cli("::1", s.target_port());
  23324. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  23325. cli.set_proxy("127.0.0.1", s.proxy_port());
  23326. cli.set_no_proxy({"[::1]"});
  23327. auto res = cli.Get("/");
  23328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23329. EXPECT_EQ(0, s.proxy_hits());
  23330. EXPECT_EQ(1, s.target_hits());
  23331. }
  23332. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  23333. ProxyAndTargetServers s;
  23334. Client cli("fe80::1", s.target_port());
  23335. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23336. cli.set_proxy("127.0.0.1", s.proxy_port());
  23337. cli.set_no_proxy({"[fe80::]/10"});
  23338. auto res = cli.Get("/");
  23339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23340. EXPECT_EQ(0, s.proxy_hits());
  23341. EXPECT_EQ(1, s.target_hits());
  23342. }
  23343. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  23344. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  23345. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  23346. // tricks via address-family conversion.
  23347. ProxyAndTargetServers s;
  23348. Client cli("::ffff:127.0.0.1", s.target_port());
  23349. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  23350. cli.set_proxy("127.0.0.1", s.proxy_port());
  23351. cli.set_no_proxy({"127.0.0.1"});
  23352. auto res = cli.Get("/");
  23353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23354. EXPECT_GE(s.proxy_hits(), 1);
  23355. EXPECT_EQ(0, s.target_hits());
  23356. }
  23357. TEST(NoProxyTest, IPv4CidrMatch) {
  23358. ProxyAndTargetServers s;
  23359. Client cli("127.0.0.1", s.target_port());
  23360. cli.set_proxy("127.0.0.1", s.proxy_port());
  23361. cli.set_no_proxy({"127.0.0.0/8"});
  23362. auto res = cli.Get("/");
  23363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23364. EXPECT_EQ(0, s.proxy_hits());
  23365. EXPECT_EQ(1, s.target_hits());
  23366. }
  23367. TEST(NoProxyTest, IPv4CidrNonMatch) {
  23368. ProxyAndTargetServers s;
  23369. Client cli("127.0.0.1", s.target_port());
  23370. cli.set_proxy("127.0.0.1", s.proxy_port());
  23371. cli.set_no_proxy({"10.0.0.0/8"});
  23372. auto res = cli.Get("/");
  23373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23374. EXPECT_GE(s.proxy_hits(), 1);
  23375. EXPECT_EQ(0, s.target_hits());
  23376. }
  23377. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  23378. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  23379. // IPv4 target matches.
  23380. ProxyAndTargetServers s;
  23381. Client cli("127.0.0.1", s.target_port());
  23382. cli.set_proxy("127.0.0.1", s.proxy_port());
  23383. cli.set_no_proxy({"0.0.0.0/0"});
  23384. auto res = cli.Get("/");
  23385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23386. EXPECT_EQ(0, s.proxy_hits());
  23387. EXPECT_EQ(1, s.target_hits());
  23388. }
  23389. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  23390. ProxyAndTargetServers s;
  23391. Client cli("127.0.0.1", s.target_port());
  23392. cli.set_proxy("127.0.0.1", s.proxy_port());
  23393. cli.set_no_proxy({"127.0.0.1"});
  23394. auto res = cli.Get("/");
  23395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23396. EXPECT_EQ(0, s.proxy_hits());
  23397. EXPECT_EQ(1, s.target_hits());
  23398. }
  23399. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  23400. ProxyAndTargetServers s;
  23401. Client cli("127.0.0.1", s.target_port());
  23402. cli.set_proxy("127.0.0.1", s.proxy_port());
  23403. cli.set_no_proxy({"127.0.0.0/33"});
  23404. auto res = cli.Get("/");
  23405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23406. EXPECT_GE(s.proxy_hits(), 1);
  23407. EXPECT_EQ(0, s.target_hits());
  23408. }
  23409. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  23410. // Empty prefix after the slash must be rejected, not silently treated as /32.
  23411. ProxyAndTargetServers s;
  23412. Client cli("127.0.0.1", s.target_port());
  23413. cli.set_proxy("127.0.0.1", s.proxy_port());
  23414. cli.set_no_proxy({"127.0.0.1/"});
  23415. auto res = cli.Get("/");
  23416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23417. EXPECT_GE(s.proxy_hits(), 1);
  23418. EXPECT_EQ(0, s.target_hits());
  23419. }
  23420. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  23421. ProxyAndTargetServers s;
  23422. auto cli = make_client("internal.corp", s);
  23423. cli->set_proxy_basic_auth("u", "p");
  23424. cli->set_no_proxy({"internal.corp"});
  23425. auto res = cli->Get("/");
  23426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23427. EXPECT_EQ(1, s.target_hits());
  23428. EXPECT_EQ(0, s.proxy_hits());
  23429. EXPECT_FALSE(s.last_had_proxy_authz())
  23430. << "Proxy-Authorization must not be sent direct to the target";
  23431. }
  23432. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  23433. ProxyAndTargetServers s;
  23434. auto cli = make_client("public.example", s);
  23435. cli->set_proxy_basic_auth("u", "p");
  23436. cli->set_no_proxy({"internal.corp"}); // does not match
  23437. auto res = cli->Get("/");
  23438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23439. EXPECT_GE(s.proxy_hits(), 1);
  23440. EXPECT_TRUE(s.last_had_proxy_authz());
  23441. }
  23442. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  23443. std::atomic<int> hits{0};
  23444. std::atomic<int> hits_with_authz{0};
  23445. no_proxy_test::ScopedServer proxy_mock;
  23446. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23447. hits++;
  23448. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  23449. if (req.target.find("/redir") != std::string::npos) {
  23450. res.set_redirect("http://other.example/landed");
  23451. } else {
  23452. res.set_content("via-proxy", "text/plain");
  23453. }
  23454. });
  23455. proxy_mock.listen();
  23456. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  23457. hits = 0;
  23458. hits_with_authz = 0;
  23459. Client cli("public.example", 80);
  23460. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23461. cli.set_proxy_basic_auth(c.first, c.second);
  23462. cli.set_follow_location(true);
  23463. // The redirect to another host goes through the proxy as well
  23464. auto res = cli.Get("/redir");
  23465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23466. EXPECT_EQ(2, hits.load());
  23467. EXPECT_EQ(2, hits_with_authz.load());
  23468. }
  23469. }
  23470. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  23471. ProxyAndTargetServers s;
  23472. auto cli = make_client("anything.test", s);
  23473. auto res = cli->Get("/");
  23474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23475. EXPECT_GE(s.proxy_hits(), 1);
  23476. EXPECT_EQ(0, s.target_hits());
  23477. }
  23478. TEST(NoProxyTest, PortSpecificEntryRejected) {
  23479. ProxyAndTargetServers s;
  23480. auto cli = make_client("example.com", s);
  23481. cli->set_no_proxy({"example.com:8080"});
  23482. auto res = cli->Get("/");
  23483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23484. EXPECT_GE(s.proxy_hits(), 1);
  23485. EXPECT_EQ(0, s.target_hits());
  23486. }
  23487. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  23488. ProxyAndTargetServers s;
  23489. auto cli = make_client("anything.test", s);
  23490. cli->set_no_proxy({"", " ", "\t"});
  23491. auto res = cli->Get("/");
  23492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23493. EXPECT_GE(s.proxy_hits(), 1);
  23494. EXPECT_EQ(0, s.target_hits());
  23495. }
  23496. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  23497. // An entry with leading/trailing whitespace must still match — env-style
  23498. // values are commonly pasted with stray spaces and an implementation
  23499. // that feeds the raw token directly to inet_pton would fail to match
  23500. // valid CIDRs because of the spaces.
  23501. ProxyAndTargetServers s;
  23502. Client cli("127.0.0.1", s.target_port());
  23503. cli.set_proxy("127.0.0.1", s.proxy_port());
  23504. cli.set_no_proxy({" 127.0.0.0/8 "});
  23505. auto res = cli.Get("/");
  23506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23507. EXPECT_EQ(0, s.proxy_hits());
  23508. EXPECT_EQ(1, s.target_hits());
  23509. }
  23510. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  23511. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  23512. // go direct and must NOT carry Proxy-Authorization.
  23513. std::atomic<int> proxy_hits{0};
  23514. std::atomic<int> target_hits{0};
  23515. std::atomic<bool> target_saw_authz{false};
  23516. no_proxy_test::ScopedServer proxy_mock, target;
  23517. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23518. proxy_hits++;
  23519. res.status = 302;
  23520. res.set_header("Location", "http://127.0.0.1:" +
  23521. std::to_string(target.port()) + "/landed");
  23522. });
  23523. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23524. target_hits++;
  23525. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  23526. res.set_content("direct", "text/plain");
  23527. });
  23528. proxy_mock.listen();
  23529. target.listen();
  23530. Client cli("public.example", target.port());
  23531. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23532. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23533. cli.set_proxy_basic_auth("u", "p");
  23534. cli.set_no_proxy({"127.0.0.1"});
  23535. cli.set_follow_location(true);
  23536. auto res = cli.Get("/redir");
  23537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23538. EXPECT_GE(proxy_hits.load(), 1);
  23539. EXPECT_GE(target_hits.load(), 1);
  23540. EXPECT_FALSE(target_saw_authz.load());
  23541. }
  23542. #ifdef CPPHTTPLIB_SSL_ENABLED
  23543. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  23544. // Direct origin replying 407 must not trigger the digest retry; otherwise
  23545. // proxy creds would be sent to the (possibly hostile) origin.
  23546. std::atomic<int> target_hits{0};
  23547. std::atomic<bool> target_saw_proxy_authz{false};
  23548. no_proxy_test::ScopedServer target;
  23549. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23550. target_hits++;
  23551. if (req.has_header("Proxy-Authorization")) {
  23552. target_saw_proxy_authz = true;
  23553. }
  23554. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23555. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  23556. "nonce=\"abc\", algorithm=MD5");
  23557. });
  23558. target.listen();
  23559. // The proxy address is set to the target's port: the bypass MUST kick in;
  23560. // if it doesn't, the test still routes "via proxy" to the same server and
  23561. // the Proxy-Authorization assertion below catches the leak.
  23562. Client cli("evil.example", target.port());
  23563. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  23564. cli.set_proxy("127.0.0.1", target.port());
  23565. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23566. cli.set_no_proxy({"evil.example"});
  23567. auto res = cli.Get("/x");
  23568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23569. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23570. EXPECT_EQ(1, target_hits.load());
  23571. EXPECT_FALSE(target_saw_proxy_authz.load());
  23572. }
  23573. #endif
  23574. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  23575. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  23576. std::atomic<int> proxy_hits{0};
  23577. std::atomic<int> bypass_hits{0};
  23578. std::atomic<bool> proxy_saw_c_url{false};
  23579. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  23580. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23581. proxy_hits++;
  23582. if (req.path.find("/start") != std::string::npos) {
  23583. res.status = 302;
  23584. res.set_header("Location", "http://127.0.0.1:" +
  23585. std::to_string(bypass_server.port()) +
  23586. "/middle");
  23587. return;
  23588. }
  23589. if (req.path.find("/end") != std::string::npos) {
  23590. proxy_saw_c_url = true;
  23591. res.set_content("c-via-proxy", "text/plain");
  23592. return;
  23593. }
  23594. res.set_content("unexpected", "text/plain");
  23595. });
  23596. // public.example's "advertised" port is arbitrary (the request never lands
  23597. // there — it goes through the proxy), but use a dynamic value to stay
  23598. // friendly with sharded parallel runs.
  23599. int public_port = bypass_server.port();
  23600. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  23601. bypass_hits++;
  23602. res.status = 302;
  23603. res.set_header("Location", "http://public.example:" +
  23604. std::to_string(public_port) + "/end");
  23605. });
  23606. proxy_mock.listen();
  23607. bypass_server.listen();
  23608. Client cli("public.example", public_port);
  23609. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23610. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23611. cli.set_no_proxy({"127.0.0.1"});
  23612. cli.set_follow_location(true);
  23613. auto res = cli.Get("/start");
  23614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23615. EXPECT_EQ(StatusCode::OK_200, res->status);
  23616. EXPECT_EQ("c-via-proxy", res->body);
  23617. EXPECT_GE(proxy_hits.load(), 2);
  23618. EXPECT_GE(bypass_hits.load(), 1);
  23619. EXPECT_TRUE(proxy_saw_c_url.load());
  23620. }
  23621. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  23622. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  23623. // request reconnects to the correct endpoint.
  23624. std::atomic<int> proxy_hits{0};
  23625. std::atomic<int> target_hits{0};
  23626. no_proxy_test::ScopedServer proxy_mock, target;
  23627. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23628. proxy_hits++;
  23629. res.set_content("via-proxy", "text/plain");
  23630. });
  23631. target.svr().Get(".*", [&](const Request &, Response &res) {
  23632. target_hits++;
  23633. res.set_content("direct", "text/plain");
  23634. });
  23635. proxy_mock.listen();
  23636. target.listen();
  23637. Client cli("public.example", target.port());
  23638. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23639. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23640. cli.set_keep_alive(true);
  23641. auto res1 = cli.Get("/a");
  23642. ASSERT_TRUE(res1);
  23643. EXPECT_EQ("via-proxy", res1->body);
  23644. EXPECT_EQ(1, proxy_hits.load());
  23645. EXPECT_EQ(0, target_hits.load());
  23646. cli.set_no_proxy({"public.example"});
  23647. auto res2 = cli.Get("/b");
  23648. ASSERT_TRUE(res2);
  23649. EXPECT_EQ("direct", res2->body);
  23650. EXPECT_EQ(1, proxy_hits.load());
  23651. EXPECT_EQ(1, target_hits.load());
  23652. }
  23653. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  23654. namespace proxy_tunnel_test {
  23655. // SSLServer counterpart to no_proxy_test::ScopedServer.
  23656. class ScopedSSLServer {
  23657. public:
  23658. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  23659. port_ = svr_.bind_to_any_port("127.0.0.1");
  23660. }
  23661. ~ScopedSSLServer() {
  23662. svr_.stop();
  23663. if (th_.joinable()) { th_.join(); }
  23664. }
  23665. SSLServer &svr() { return svr_; }
  23666. int port() const { return port_; }
  23667. void listen() {
  23668. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23669. svr_.wait_until_ready();
  23670. }
  23671. private:
  23672. SSLServer svr_;
  23673. std::thread th_;
  23674. int port_ = 0;
  23675. };
  23676. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  23677. class ScopedConnectProxy {
  23678. public:
  23679. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  23680. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  23681. if (listen_fd_ < 0) { return; }
  23682. int yes = 1;
  23683. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  23684. sockaddr_in a{};
  23685. a.sin_family = AF_INET;
  23686. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23687. a.sin_port = 0;
  23688. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  23689. return;
  23690. }
  23691. socklen_t alen = sizeof(a);
  23692. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  23693. 0) {
  23694. return;
  23695. }
  23696. port_ = ntohs(a.sin_port);
  23697. if (::listen(listen_fd_, 1) != 0) { return; }
  23698. th_ = std::thread([this] { run(); });
  23699. }
  23700. ~ScopedConnectProxy() {
  23701. stop_ = true;
  23702. if (listen_fd_ >= 0) {
  23703. ::shutdown(listen_fd_, SHUT_RDWR);
  23704. ::close(listen_fd_);
  23705. }
  23706. if (th_.joinable()) { th_.join(); }
  23707. }
  23708. int port() const { return port_; }
  23709. int connect_hits() const { return connect_hits_.load(); }
  23710. // Head of the last CONNECT request, as the proxy saw it on the wire.
  23711. std::string connect_request() const {
  23712. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23713. return connect_request_;
  23714. }
  23715. private:
  23716. void run() {
  23717. while (!stop_.load()) {
  23718. fd_set rfds;
  23719. FD_ZERO(&rfds);
  23720. FD_SET(listen_fd_, &rfds);
  23721. timeval tv{0, 100 * 1000};
  23722. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  23723. if (sel <= 0) { continue; }
  23724. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  23725. if (client_fd < 0) { continue; }
  23726. std::string req;
  23727. char buf[2048];
  23728. while (req.find("\r\n\r\n") == std::string::npos) {
  23729. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  23730. if (n <= 0) { break; }
  23731. req.append(buf, static_cast<size_t>(n));
  23732. }
  23733. if (req.compare(0, 7, "CONNECT") != 0) {
  23734. ::close(client_fd);
  23735. continue;
  23736. }
  23737. connect_hits_++;
  23738. {
  23739. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23740. connect_request_ = req;
  23741. }
  23742. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  23743. ::send(client_fd, ok, std::strlen(ok), 0);
  23744. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  23745. sockaddr_in o{};
  23746. o.sin_family = AF_INET;
  23747. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23748. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  23749. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  23750. 0) {
  23751. ::close(client_fd);
  23752. ::close(origin_fd);
  23753. continue;
  23754. }
  23755. auto forward = [](int from, int to) {
  23756. char b[8192];
  23757. for (;;) {
  23758. ssize_t n = ::recv(from, b, sizeof(b), 0);
  23759. if (n <= 0) { break; }
  23760. ssize_t off = 0;
  23761. while (off < n) {
  23762. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  23763. if (s <= 0) {
  23764. off = n;
  23765. break;
  23766. }
  23767. off += s;
  23768. }
  23769. }
  23770. ::shutdown(to, SHUT_WR);
  23771. };
  23772. std::thread t1([&] { forward(client_fd, origin_fd); });
  23773. std::thread t2([&] { forward(origin_fd, client_fd); });
  23774. t1.join();
  23775. t2.join();
  23776. ::close(client_fd);
  23777. ::close(origin_fd);
  23778. }
  23779. }
  23780. int forward_port_ = -1;
  23781. int listen_fd_ = -1;
  23782. int port_ = 0;
  23783. std::thread th_;
  23784. std::atomic<bool> stop_{false};
  23785. std::atomic<int> connect_hits_{0};
  23786. mutable std::mutex connect_request_mutex_;
  23787. std::string connect_request_;
  23788. };
  23789. // Sends one request through the CONNECT proxy to the TLS origin with a
  23790. // credential configured for each hop, and checks that each credential reaches
  23791. // only the hop it was configured for: the proxy's on the CONNECT request, the
  23792. // origin's (every header in origin_headers) on the tunnelled request.
  23793. void CredentialsStayWithTheirHop(
  23794. const std::function<void(SSLClient &)> &set_credentials,
  23795. const std::string &scheme,
  23796. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  23797. std::atomic<int> origin_hits{0};
  23798. std::atomic<bool> origin_saw_proxy_authz{false};
  23799. std::atomic<bool> origin_saw_headers{false};
  23800. ScopedSSLServer origin;
  23801. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23802. origin_hits++;
  23803. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  23804. origin_saw_headers =
  23805. std::all_of(origin_headers.begin(), origin_headers.end(),
  23806. [&](const std::string &h) { return req.has_header(h); });
  23807. res.set_content("ok", "text/plain");
  23808. });
  23809. origin.listen();
  23810. ScopedConnectProxy proxy(origin.port());
  23811. ASSERT_NE(0, proxy.port());
  23812. // Pinned to 127.0.0.1 for the same reason as the test below.
  23813. SSLClient cli("127.0.0.1", origin.port());
  23814. cli.enable_server_certificate_verification(false);
  23815. cli.set_proxy("127.0.0.1", proxy.port());
  23816. set_credentials(cli);
  23817. auto res = cli.Get("/x");
  23818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23819. EXPECT_EQ(StatusCode::OK_200, res->status);
  23820. EXPECT_EQ(1, origin_hits.load());
  23821. EXPECT_EQ(1, proxy.connect_hits());
  23822. EXPECT_TRUE(origin_saw_headers.load());
  23823. EXPECT_FALSE(origin_saw_proxy_authz.load())
  23824. << "Proxy-Authorization must not be sent inside the tunnel";
  23825. auto connect_req = proxy.connect_request();
  23826. EXPECT_NE(std::string::npos,
  23827. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  23828. for (const auto &h : origin_headers) {
  23829. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  23830. << h << " must not be sent to the proxy on CONNECT";
  23831. }
  23832. }
  23833. } // namespace proxy_tunnel_test
  23834. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  23835. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23836. [](SSLClient &cli) {
  23837. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23838. cli.set_basic_auth("origin-user", "origin-pass");
  23839. },
  23840. "Basic");
  23841. }
  23842. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  23843. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23844. [](SSLClient &cli) {
  23845. cli.set_proxy_bearer_token_auth("proxy-token");
  23846. cli.set_bearer_token_auth("origin-token");
  23847. },
  23848. "Bearer");
  23849. }
  23850. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  23851. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23852. [](SSLClient &cli) {
  23853. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23854. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  23855. {"Cookie", "sid=origin-session"},
  23856. {"X-Api-Key", "origin-key"}});
  23857. },
  23858. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  23859. }
  23860. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  23861. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  23862. // retry; otherwise proxy creds would be sent to the origin.
  23863. std::atomic<int> origin_hits{0};
  23864. std::atomic<bool> origin_saw_proxy_authz{false};
  23865. proxy_tunnel_test::ScopedSSLServer origin;
  23866. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23867. origin_hits++;
  23868. if (req.has_header("Proxy-Authorization")) {
  23869. origin_saw_proxy_authz = true;
  23870. }
  23871. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23872. res.set_header("Proxy-Authenticate",
  23873. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  23874. "algorithm=MD5");
  23875. });
  23876. origin.listen();
  23877. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  23878. ASSERT_NE(0, proxy.port());
  23879. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  23880. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  23881. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  23882. // and answer with its own status, making this test flaky.
  23883. SSLClient cli("127.0.0.1", origin.port());
  23884. cli.enable_server_certificate_verification(false);
  23885. cli.set_proxy("127.0.0.1", proxy.port());
  23886. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23887. auto res = cli.Get("/x");
  23888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23889. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23890. EXPECT_EQ(1, origin_hits.load());
  23891. EXPECT_FALSE(origin_saw_proxy_authz.load());
  23892. EXPECT_EQ(1, proxy.connect_hits());
  23893. }
  23894. #endif