test.cc 915 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211
  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. } // namespace detail
  480. } // namespace httplib
  481. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  482. struct {
  483. const char *line;
  484. const char *version;
  485. int status;
  486. const char *reason;
  487. } cases[] = {
  488. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  489. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  490. // The reason phrase may be empty, or left out along with its space.
  491. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  492. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  493. };
  494. for (const auto &c : cases) {
  495. std::string version;
  496. int status = 0;
  497. std::string reason = "unset";
  498. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  499. << c.line;
  500. EXPECT_EQ(c.version, version);
  501. EXPECT_EQ(c.status, status);
  502. EXPECT_EQ(c.reason, reason);
  503. }
  504. }
  505. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  506. const char *lines[] = {
  507. "HTTP/2 200 OK\r\n",
  508. "HTTP/1.2 200 OK\r\n",
  509. "HTTP/1.1 20 OK\r\n",
  510. "HTTP/1.1 2000 OK\r\n",
  511. "HTTP/1.1 2x0 OK\r\n",
  512. "HTTP/1.1 200 OK\r\n",
  513. "HTTP/1.1 200OK\r\n",
  514. "HTTP/1.1 200 O\rK\r\n",
  515. "HTTP/1.1 200 OK",
  516. "HTTP/1.1 200 OK\r\nX",
  517. "",
  518. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  519. "HTTP/1.1 200 OK\n",
  520. #endif
  521. };
  522. for (auto line : lines) {
  523. std::string version;
  524. int status = 0;
  525. std::string reason;
  526. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  527. << line;
  528. }
  529. }
  530. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  531. // Long enough to overflow the stack when matched with std::regex.
  532. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  533. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  534. std::string version;
  535. int status = 0;
  536. std::string reason;
  537. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  538. EXPECT_EQ(200, status);
  539. EXPECT_EQ(long_reason, reason);
  540. }
  541. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  542. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  543. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  544. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  545. EXPECT_EQ("", detail::file_extension("noext"));
  546. EXPECT_EQ("", detail::file_extension("a."));
  547. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  548. EXPECT_EQ("", detail::file_extension("a.b-c"));
  549. // Long enough to overflow the stack when matched with std::regex.
  550. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  551. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  552. }
  553. // Forward declaration: in split builds split.py strips `inline` and moves the
  554. // definition into httplib.cc, so detail::base64_encode is not visible from the
  555. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  556. // in both header-only and split builds.
  557. namespace httplib {
  558. namespace detail {
  559. std::string base64_encode(const std::string &in);
  560. } // namespace detail
  561. } // namespace httplib
  562. TEST(Base64EncodeTest, KnownAnswers) {
  563. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  564. // where the accumulator's top bit is already set before the next shift.
  565. EXPECT_EQ("", detail::base64_encode(""));
  566. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  567. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  568. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  569. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  570. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  571. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  572. // High bytes keep the top bit set across several rounds.
  573. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  574. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  575. }
  576. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  577. string unescapedCharacters = "-_.!~*'()";
  578. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  579. }
  580. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  581. string reservedCharacters = ";,/?:@&=+$";
  582. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  583. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  584. }
  585. TEST(ClientQueryOrder, PreserveOrder) {
  586. // This test reproduces Issue #2259: client may reorder query parameters
  587. // when sending a GET request. The expected behavior is that the client
  588. // preserves the original query string order when the caller supplied it
  589. // as part of the path.
  590. Server svr;
  591. svr.Get("/", [&](const Request &req, Response &res) {
  592. // Echo back the raw target so the test can assert ordering
  593. res.set_content(req.target, "text/plain");
  594. });
  595. std::thread t{[&] { svr.listen(HOST, PORT); }};
  596. auto se = detail::scope_exit([&] {
  597. svr.stop();
  598. t.join();
  599. ASSERT_FALSE(svr.is_running());
  600. });
  601. svr.wait_until_ready();
  602. Client cli(HOST, PORT);
  603. ASSERT_TRUE(cli.is_valid());
  604. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  605. auto res = cli.Get(original);
  606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  607. // Expect the echoed target to exactly match the original path (order
  608. // preserved)
  609. EXPECT_EQ(res->body, original);
  610. }
  611. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  612. string chineseCharacters = U8("中国語");
  613. string russianCharacters = U8("дом");
  614. string brazilianCharacters = U8("óculos");
  615. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  616. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  617. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  618. "%D0%B4%D0%BE%D0%BC");
  619. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  620. }
  621. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  622. string unescapedCharacters = "-_.!~*'()";
  623. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  624. }
  625. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  626. string reservedCharacters = ";,/?:@&=+$";
  627. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  628. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  629. }
  630. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  631. string chineseCharacters = U8("中国語");
  632. string russianCharacters = U8("дом");
  633. string brazilianCharacters = U8("óculos");
  634. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  635. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  636. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  637. "%D0%B4%D0%BE%D0%BC");
  638. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  639. }
  640. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  641. // Issue #2082 use case: encoding path component with ampersand
  642. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  643. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  644. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  645. }
  646. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  647. string unescapedCharacters = "-_.!~*'()";
  648. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  649. }
  650. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  651. string reservedCharacters = ";,/?:@&=+$#";
  652. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  653. }
  654. TEST(EncodeUriTest, TestUTF8Characters) {
  655. string chineseCharacters = U8("中国語");
  656. string russianCharacters = U8("дом");
  657. string brazilianCharacters = U8("óculos");
  658. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  659. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  660. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  661. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  662. }
  663. TEST(EncodeUriTest, TestCompleteUri) {
  664. string uri =
  665. "https://example.com/path/to/resource?query=value&param=test#fragment";
  666. EXPECT_EQ(
  667. httplib::encode_uri(uri),
  668. "https://example.com/path/to/resource?query=value&param=test#fragment");
  669. }
  670. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  671. string uri =
  672. "https://example.com/path with spaces/file name.html?q=hello world";
  673. EXPECT_EQ(httplib::encode_uri(uri),
  674. "https://example.com/path%20with%20spaces/"
  675. "file%20name.html?q=hello%20world");
  676. }
  677. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  678. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  679. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  680. }
  681. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  682. string unescapedCharacters = "-_.!~*'()";
  683. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  684. }
  685. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  686. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  687. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  688. string encodedBrazilian = "%C3%B3culos";
  689. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  690. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  691. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  692. }
  693. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  694. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  695. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  696. "Piri Tommy Villiers - on & on");
  697. }
  698. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  699. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  700. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  701. }
  702. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  703. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  704. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  705. }
  706. TEST(DecodeUriTest, TestUTF8Characters) {
  707. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  708. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  709. string encodedBrazilian = "%C3%B3culos";
  710. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  711. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  712. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  713. }
  714. TEST(DecodeUriTest, TestCompleteUri) {
  715. string encodedUri = "https://example.com/path%20with%20spaces/"
  716. "file%20name.html?q=hello%20world";
  717. EXPECT_EQ(
  718. httplib::decode_uri(encodedUri),
  719. "https://example.com/path with spaces/file name.html?q=hello world");
  720. }
  721. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  722. string original =
  723. "https://example.com/path with spaces/file name.html?q=hello world";
  724. string encoded = httplib::encode_uri(original);
  725. string decoded = httplib::decode_uri(encoded);
  726. EXPECT_EQ(decoded, original);
  727. }
  728. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  729. // decode_uri is the inverse of encode_uri: an escaped reserved character
  730. // stays encoded so it is not promoted into a real delimiter, while
  731. // non-reserved escapes still decode (like JS decodeURI).
  732. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  733. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  734. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  735. "%3F%3A%40%26%3D%2B%24%2C%3B");
  736. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  737. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  738. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  739. "http://example.com/a%2Fb");
  740. // decode_uri_component still decodes the reserved character.
  741. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  742. }
  743. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  744. string original = "Piri Tommy Villiers - on & on";
  745. string encoded = httplib::encode_uri_component(original);
  746. string decoded = httplib::decode_uri_component(encoded);
  747. EXPECT_EQ(decoded, original);
  748. }
  749. TEST(TrimTests, TrimStringTests) {
  750. EXPECT_EQ("abc", detail::trim_copy("abc"));
  751. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  752. EXPECT_TRUE(detail::trim_copy("").empty());
  753. }
  754. TEST(AsciiTest, LocaleIndependentClassification) {
  755. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  756. // which consult the global C locale: std::isalnum(0xC5) can return true
  757. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  758. // helpers must classify every byte by the ASCII grammar alone.
  759. for (int i = 0; i < 256; i++) {
  760. auto c = static_cast<char>(i);
  761. auto is_digit = i >= '0' && i <= '9';
  762. auto is_upper = i >= 'A' && i <= 'Z';
  763. auto is_lower = i >= 'a' && i <= 'z';
  764. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  765. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  766. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  767. << "byte " << i;
  768. }
  769. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  770. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  771. // Non-ASCII bytes must be percent-encoded, never passed through as
  772. // alphanumeric.
  773. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  774. }
  775. TEST(FromCharsTest, Double) {
  776. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  777. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  778. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  779. auto parse = [](const std::string &s, double &v) {
  780. return detail::from_chars(s.data(), s.data() + s.size(), v);
  781. };
  782. double v = -1.0;
  783. // Representative quality values.
  784. EXPECT_EQ(parse("0", v).ec, std::errc{});
  785. EXPECT_DOUBLE_EQ(v, 0.0);
  786. EXPECT_EQ(parse("1", v).ec, std::errc{});
  787. EXPECT_DOUBLE_EQ(v, 1.0);
  788. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  789. EXPECT_DOUBLE_EQ(v, 0.8);
  790. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  791. EXPECT_DOUBLE_EQ(v, 0.001);
  792. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  793. EXPECT_DOUBLE_EQ(v, 1.0);
  794. // A missing integer or fractional part is tolerated.
  795. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  796. EXPECT_DOUBLE_EQ(v, 0.5);
  797. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  798. EXPECT_DOUBLE_EQ(v, 5.0);
  799. // Values outside [0, 1] still parse; the caller range-checks them.
  800. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  801. EXPECT_DOUBLE_EQ(v, 123.456);
  802. // Stops at the first byte that is not part of the number and reports where.
  803. std::string trailing = "0.9, text/html";
  804. auto r = parse(trailing, v);
  805. EXPECT_EQ(r.ec, std::errc{});
  806. EXPECT_DOUBLE_EQ(v, 0.9);
  807. EXPECT_EQ(*r.ptr, ',');
  808. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  809. // outright, and an 'e'/'E' simply ends the number.
  810. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  811. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  812. std::string exp_input = "1.5e3";
  813. r = parse(exp_input, v);
  814. EXPECT_EQ(r.ec, std::errc{});
  815. EXPECT_DOUBLE_EQ(v, 1.5);
  816. EXPECT_EQ(*r.ptr, 'e');
  817. // Invalid inputs.
  818. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  819. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  820. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  821. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  822. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  823. // Pathological but well-formed inputs must stay bounded (no overflow, no
  824. // out-of-bounds table access) and stay within [0, 1] for the caller.
  825. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  826. std::errc{});
  827. EXPECT_DOUBLE_EQ(v, 0.0);
  828. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  829. std::errc{});
  830. EXPECT_GE(v, 0.0);
  831. EXPECT_LE(v, 1.0);
  832. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  833. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  834. }
  835. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  836. // Simple case without quality values
  837. std::vector<std::string> result1;
  838. EXPECT_TRUE(detail::parse_accept_header(
  839. "text/html,application/json,text/plain", result1));
  840. EXPECT_EQ(result1.size(), 3U);
  841. EXPECT_EQ(result1[0], "text/html");
  842. EXPECT_EQ(result1[1], "application/json");
  843. EXPECT_EQ(result1[2], "text/plain");
  844. // With quality values
  845. std::vector<std::string> result2;
  846. EXPECT_TRUE(detail::parse_accept_header(
  847. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  848. EXPECT_EQ(result2.size(), 3U);
  849. EXPECT_EQ(result2[0], "application/json"); // highest q value
  850. EXPECT_EQ(result2[1], "text/html");
  851. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  852. }
  853. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  854. // Mixed with and without quality values
  855. std::vector<std::string> result;
  856. EXPECT_TRUE(detail::parse_accept_header(
  857. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  858. EXPECT_EQ(result.size(), 3U);
  859. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  860. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  861. EXPECT_EQ(result[2], "application/json"); // q=0.5
  862. }
  863. TEST(ParseAcceptHeaderTest, EdgeCases) {
  864. // Empty header
  865. std::vector<std::string> empty_result;
  866. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  867. EXPECT_TRUE(empty_result.empty());
  868. // Single type
  869. std::vector<std::string> single_result;
  870. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  871. EXPECT_EQ(single_result.size(), 1U);
  872. EXPECT_EQ(single_result[0], "application/json");
  873. // Wildcard types
  874. std::vector<std::string> wildcard_result;
  875. EXPECT_TRUE(detail::parse_accept_header(
  876. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  877. EXPECT_EQ(wildcard_result.size(), 3U);
  878. EXPECT_EQ(wildcard_result[0], "application/json");
  879. EXPECT_EQ(wildcard_result[1], "text/*");
  880. EXPECT_EQ(wildcard_result[2], "*/*");
  881. }
  882. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  883. // Common browser Accept header
  884. std::vector<std::string> browser_result;
  885. EXPECT_TRUE(
  886. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  887. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  888. browser_result));
  889. EXPECT_EQ(browser_result.size(), 6U);
  890. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  891. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  892. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  893. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  894. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  895. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  896. // API client header
  897. std::vector<std::string> api_result;
  898. EXPECT_TRUE(detail::parse_accept_header(
  899. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  900. api_result));
  901. EXPECT_EQ(api_result.size(), 3U);
  902. EXPECT_EQ(api_result[0], "application/json");
  903. EXPECT_EQ(api_result[1], "application/xml");
  904. EXPECT_EQ(api_result[2], "text/plain");
  905. }
  906. TEST(ParseAcceptHeaderTest, SpecialCases) {
  907. // Quality value with 3 decimal places
  908. std::vector<std::string> decimal_result;
  909. EXPECT_TRUE(detail::parse_accept_header(
  910. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  911. EXPECT_EQ(decimal_result.size(), 2U);
  912. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  913. EXPECT_EQ(decimal_result[1], "text/html");
  914. // Zero quality (should still be included but with lowest priority)
  915. std::vector<std::string> zero_q_result;
  916. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  917. zero_q_result));
  918. EXPECT_EQ(zero_q_result.size(), 2U);
  919. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  920. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  921. // No spaces around commas
  922. std::vector<std::string> no_space_result;
  923. EXPECT_TRUE(detail::parse_accept_header(
  924. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  925. no_space_result));
  926. EXPECT_EQ(no_space_result.size(), 3U);
  927. EXPECT_EQ(no_space_result[0], "text/html");
  928. EXPECT_EQ(no_space_result[1], "application/json");
  929. EXPECT_EQ(no_space_result[2], "text/plain");
  930. }
  931. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  932. // Quality values always use '.' as the decimal separator, so parsing must
  933. // not depend on the process locale. An embedding application may have
  934. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  935. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  936. std::string saved = cur ? cur : "C";
  937. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  938. "fr_FR.UTF-8"};
  939. bool switched = false;
  940. for (const auto loc : comma_locales) {
  941. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  942. std::localeconv()->decimal_point[0] == ',') {
  943. switched = true;
  944. break;
  945. }
  946. }
  947. if (!switched) {
  948. std::setlocale(LC_NUMERIC, saved.c_str());
  949. GTEST_SKIP() << "no comma-decimal locale available on this host";
  950. }
  951. // The higher-weighted type appears later in the list, so a correct parse
  952. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  953. // sensitive parse reads both weights as 0 and leaves the original order.
  954. std::vector<std::string> result;
  955. EXPECT_TRUE(detail::parse_accept_header(
  956. "application/json;q=0.1,text/html;q=0.9", result));
  957. ASSERT_EQ(result.size(), 2U);
  958. EXPECT_EQ(result[0], "text/html");
  959. EXPECT_EQ(result[1], "application/json");
  960. std::setlocale(LC_NUMERIC, saved.c_str());
  961. }
  962. TEST(ParseAcceptHeaderTest, InvalidCases) {
  963. std::vector<std::string> result;
  964. // Invalid quality value (> 1.0)
  965. EXPECT_FALSE(
  966. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  967. // Invalid quality value (< 0.0)
  968. EXPECT_FALSE(
  969. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  970. // Invalid quality value (not a number)
  971. EXPECT_FALSE(detail::parse_accept_header(
  972. "text/html;q=invalid,application/json", result));
  973. // A valid numeric prefix does not make the entire quality value valid.
  974. EXPECT_FALSE(detail::parse_accept_header(
  975. "text/html;q=0.5junk,application/json", result));
  976. // Empty quality value
  977. EXPECT_FALSE(
  978. detail::parse_accept_header("text/html;q=,application/json", result));
  979. // Invalid media type format (no slash and not wildcard)
  980. EXPECT_FALSE(
  981. detail::parse_accept_header("invalidtype,application/json", result));
  982. // Valid cases should still work
  983. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  984. EXPECT_EQ(result.size(), 1U);
  985. EXPECT_EQ(result[0], "*/*");
  986. EXPECT_TRUE(detail::parse_accept_header("*", result));
  987. EXPECT_EQ(result.size(), 1U);
  988. EXPECT_EQ(result[0], "*");
  989. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  990. EXPECT_EQ(result.size(), 1U);
  991. EXPECT_EQ(result[0], "text/*");
  992. }
  993. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  994. // elements, so a leading, trailing or doubled comma is a legal Accept value
  995. // and must not be answered with 400 Bad Request.
  996. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  997. struct {
  998. const char *value;
  999. std::vector<std::string> expected;
  1000. } cases[] = {
  1001. {",application/json", {"application/json"}},
  1002. {"text/html,", {"text/html"}},
  1003. {"text/html,,*/*", {"text/html", "*/*"}},
  1004. // An empty element may be spelled with whitespace in it
  1005. {"text/html, , application/json", {"text/html", "application/json"}},
  1006. // Nothing but empty elements is an empty list, which means the same
  1007. // thing as no Accept header at all
  1008. {",,,", {}},
  1009. // Quality values still apply across ignored empty elements
  1010. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1011. };
  1012. for (const auto &c : cases) {
  1013. std::vector<std::string> result;
  1014. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1015. << "value: " << c.value;
  1016. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1017. }
  1018. // An invalid entry is still rejected when empty elements surround it
  1019. std::vector<std::string> result;
  1020. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1021. }
  1022. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1023. // or ';' inside one does not end the list element or the parameter. Section
  1024. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1025. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1026. struct {
  1027. const char *value;
  1028. std::vector<std::string> expected;
  1029. } cases[] = {
  1030. {"text/html;profile=\"a,b\",application/json",
  1031. {"text/html", "application/json"}},
  1032. // A "q=" inside a quoted value is not the weight
  1033. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1034. {"text/html", "application/json"}},
  1035. // The weight after a quoted value still applies
  1036. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1037. {"application/json", "text/html"}},
  1038. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1039. {"application/json", "text/html"}},
  1040. {"text/html;profile=\"a\\\"b\",application/json",
  1041. {"text/html", "application/json"}},
  1042. // An escaped backslash does not escape the '"' after it
  1043. {"text/html;profile=\"a\\\\\",application/json",
  1044. {"text/html", "application/json"}},
  1045. };
  1046. for (const auto &c : cases) {
  1047. std::vector<std::string> result;
  1048. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1049. << "value: " << c.value;
  1050. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1051. }
  1052. }
  1053. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1054. Server svr;
  1055. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1056. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1057. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1058. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1059. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1060. res.set_content("ok", "text/plain");
  1061. });
  1062. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1063. EXPECT_TRUE(false);
  1064. res.set_content("bad request", "text/plain");
  1065. });
  1066. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1067. auto se = detail::scope_exit([&] {
  1068. svr.stop();
  1069. listen_thread.join();
  1070. ASSERT_FALSE(svr.is_running());
  1071. });
  1072. svr.wait_until_ready();
  1073. Client cli("localhost", PORT);
  1074. {
  1075. auto res = cli.Get(
  1076. "/accept_ok",
  1077. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1079. EXPECT_EQ(StatusCode::OK_200, res->status);
  1080. }
  1081. {
  1082. auto res = cli.Get("/accept_bad_request",
  1083. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1085. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1086. }
  1087. }
  1088. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1089. Server svr;
  1090. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1091. res.set_content("ok", "text/plain");
  1092. });
  1093. std::atomic<int> start_count{0};
  1094. std::atomic<bool> running_when_called{false};
  1095. svr.set_start_handler([&]() {
  1096. running_when_called = svr.is_running();
  1097. start_count++;
  1098. });
  1099. auto port = svr.bind_to_any_port(HOST);
  1100. std::thread t([&]() { svr.listen_after_bind(); });
  1101. auto se = detail::scope_exit([&] {
  1102. svr.stop();
  1103. t.join();
  1104. ASSERT_FALSE(svr.is_running());
  1105. });
  1106. svr.wait_until_ready();
  1107. // A successful request proves the accept loop is running, which the start
  1108. // handler precedes; so by now the handler must have run exactly once.
  1109. Client cli(HOST, port);
  1110. cli.set_connection_timeout(std::chrono::seconds(5));
  1111. auto res = cli.Get("/");
  1112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1113. EXPECT_EQ(StatusCode::OK_200, res->status);
  1114. EXPECT_EQ(1, start_count.load());
  1115. EXPECT_TRUE(running_when_called.load());
  1116. }
  1117. TEST(DivideTest, DivideStringTests) {
  1118. auto divide = [](const std::string &str, char d) {
  1119. std::string lhs;
  1120. std::string rhs;
  1121. detail::divide(str, d,
  1122. [&](const char *lhs_data, std::size_t lhs_size,
  1123. const char *rhs_data, std::size_t rhs_size) {
  1124. lhs.assign(lhs_data, lhs_size);
  1125. rhs.assign(rhs_data, rhs_size);
  1126. });
  1127. return std::make_pair(std::move(lhs), std::move(rhs));
  1128. };
  1129. {
  1130. const auto res = divide("", '=');
  1131. EXPECT_EQ(res.first, "");
  1132. EXPECT_EQ(res.second, "");
  1133. }
  1134. {
  1135. const auto res = divide("=", '=');
  1136. EXPECT_EQ(res.first, "");
  1137. EXPECT_EQ(res.second, "");
  1138. }
  1139. {
  1140. const auto res = divide(" ", '=');
  1141. EXPECT_EQ(res.first, " ");
  1142. EXPECT_EQ(res.second, "");
  1143. }
  1144. {
  1145. const auto res = divide("a", '=');
  1146. EXPECT_EQ(res.first, "a");
  1147. EXPECT_EQ(res.second, "");
  1148. }
  1149. {
  1150. const auto res = divide("a=", '=');
  1151. EXPECT_EQ(res.first, "a");
  1152. EXPECT_EQ(res.second, "");
  1153. }
  1154. {
  1155. const auto res = divide("=b", '=');
  1156. EXPECT_EQ(res.first, "");
  1157. EXPECT_EQ(res.second, "b");
  1158. }
  1159. {
  1160. const auto res = divide("a=b", '=');
  1161. EXPECT_EQ(res.first, "a");
  1162. EXPECT_EQ(res.second, "b");
  1163. }
  1164. {
  1165. const auto res = divide("a=b=", '=');
  1166. EXPECT_EQ(res.first, "a");
  1167. EXPECT_EQ(res.second, "b=");
  1168. }
  1169. {
  1170. const auto res = divide("a=b=c", '=');
  1171. EXPECT_EQ(res.first, "a");
  1172. EXPECT_EQ(res.second, "b=c");
  1173. }
  1174. }
  1175. TEST(SplitTest, ParseQueryString) {
  1176. string s = "key1=val1&key2=val2&key3=val3";
  1177. Params dic;
  1178. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1179. [&](const char *b, const char *e) {
  1180. string key, val;
  1181. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1182. if (key.empty()) {
  1183. key.assign(b2, e2);
  1184. } else {
  1185. val.assign(b2, e2);
  1186. }
  1187. });
  1188. dic.emplace(key, val);
  1189. });
  1190. EXPECT_EQ("val1", dic.find("key1")->second);
  1191. EXPECT_EQ("val2", dic.find("key2")->second);
  1192. EXPECT_EQ("val3", dic.find("key3")->second);
  1193. }
  1194. TEST(SplitTest, ParseInvalidQueryTests) {
  1195. {
  1196. string s = " ";
  1197. Params dict;
  1198. detail::parse_query_text(s, dict);
  1199. EXPECT_TRUE(dict.empty());
  1200. }
  1201. {
  1202. string s = " = =";
  1203. Params dict;
  1204. detail::parse_query_text(s, dict);
  1205. EXPECT_TRUE(dict.empty());
  1206. }
  1207. }
  1208. TEST(ParseQueryTest, ParseQueryString) {
  1209. {
  1210. std::string s = "key1=val1&key2=val2&key3=val3";
  1211. Params dic;
  1212. detail::parse_query_text(s, dic);
  1213. EXPECT_EQ("val1", dic.find("key1")->second);
  1214. EXPECT_EQ("val2", dic.find("key2")->second);
  1215. EXPECT_EQ("val3", dic.find("key3")->second);
  1216. }
  1217. {
  1218. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1219. Params dic;
  1220. detail::parse_query_text(s, dic);
  1221. EXPECT_EQ("", dic.find("key1")->second);
  1222. EXPECT_EQ("val1", dic.find("key2")->second);
  1223. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1224. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1225. }
  1226. }
  1227. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1228. Params dic;
  1229. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1230. dic.emplace("key1", "val1");
  1231. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1232. dic.emplace("key2", "val2");
  1233. dic.emplace("key3", "val3");
  1234. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1235. }
  1236. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1237. Params params;
  1238. params.emplace("a", "1");
  1239. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1240. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1241. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1242. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1243. // Long enough to overflow the stack when matched with std::regex.
  1244. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1245. EXPECT_EQ("/p?" + long_query + "&a=1",
  1246. append_query_params("/p?" + long_query, params));
  1247. }
  1248. // Joins every entry of a Headers or Params into "key=value " so a whole
  1249. // traversal can be compared in one assertion. Both are instantiations of the
  1250. // same insertion-ordered container, so one helper serves both.
  1251. template <typename Map> static std::string entries_to_string(const Map &m) {
  1252. std::string s;
  1253. for (const auto &entry : m) {
  1254. s += entry.first + "=" + entry.second + " ";
  1255. }
  1256. return s;
  1257. }
  1258. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1259. // Params used to be a std::multimap, which sorted by name and handed the
  1260. // caller's query back alphabetised. A client signing its query string could
  1261. // not reproduce the order it asked for.
  1262. Params dic;
  1263. dic.emplace("zulu", "1");
  1264. dic.emplace("alpha", "2");
  1265. dic.emplace("mike", "3");
  1266. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1267. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1268. }
  1269. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1270. Params dic;
  1271. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1272. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1273. }
  1274. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1275. Request req;
  1276. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1277. req.params);
  1278. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1279. EXPECT_EQ("first", req.get_param_value("tag"));
  1280. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1281. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1282. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1283. EXPECT_EQ("", req.get_param_value("tag", 3));
  1284. }
  1285. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1286. // Params shares its container with Headers, which matches field names
  1287. // case-insensitively. Parameter names must not pick that up.
  1288. Params dic;
  1289. dic.emplace("Key", "upper");
  1290. dic.emplace("key", "lower");
  1291. EXPECT_EQ(2U, dic.size());
  1292. EXPECT_EQ(1U, dic.count("Key"));
  1293. EXPECT_EQ(1U, dic.count("key"));
  1294. EXPECT_EQ("upper", dic.find("Key")->second);
  1295. EXPECT_EQ("lower", dic.find("key")->second);
  1296. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1297. }
  1298. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1299. Server svr;
  1300. std::string order;
  1301. svr.Get("/order", [&](const Request &req, Response &res) {
  1302. order = entries_to_string(req.params);
  1303. res.set_content("ok", "text/plain");
  1304. });
  1305. auto port = svr.bind_to_any_port(HOST);
  1306. thread t = thread([&] { svr.listen_after_bind(); });
  1307. auto se = detail::scope_exit([&] {
  1308. svr.stop();
  1309. t.join();
  1310. ASSERT_FALSE(svr.is_running());
  1311. });
  1312. svr.wait_until_ready();
  1313. Client cli(HOST, port);
  1314. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1315. ASSERT_TRUE(res);
  1316. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1317. }
  1318. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1319. Server svr;
  1320. std::string field_order, file_order;
  1321. svr.Post("/order", [&](const Request &req, Response &res) {
  1322. for (const auto &field : req.form.fields) {
  1323. field_order += field.first + "=" + field.second.content + " ";
  1324. }
  1325. for (const auto &file : req.form.files) {
  1326. file_order += file.first + "=" + file.second.filename + " ";
  1327. }
  1328. res.set_content("ok", "text/plain");
  1329. });
  1330. auto port = svr.bind_to_any_port(HOST);
  1331. thread t = thread([&] { svr.listen_after_bind(); });
  1332. auto se = detail::scope_exit([&] {
  1333. svr.stop();
  1334. t.join();
  1335. ASSERT_FALSE(svr.is_running());
  1336. });
  1337. svr.wait_until_ready();
  1338. UploadFormDataItems items = {
  1339. {"zulu", "1", "", ""},
  1340. {"alpha", "2", "", ""},
  1341. {"mike", "3", "", ""},
  1342. {"zebra", "z", "z.txt", "text/plain"},
  1343. {"apple", "a", "a.txt", "text/plain"},
  1344. };
  1345. Client cli(HOST, port);
  1346. auto res = cli.Post("/order", items);
  1347. ASSERT_TRUE(res);
  1348. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1349. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1350. }
  1351. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1352. Server svr;
  1353. std::vector<std::string> values;
  1354. std::string first, second, out_of_range, order;
  1355. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1356. values = req.form.get_fields("tag");
  1357. first = req.form.get_field("tag", 0);
  1358. second = req.form.get_field("tag", 1);
  1359. out_of_range = req.form.get_field("tag", 2);
  1360. for (const auto &field : req.form.fields) {
  1361. order += field.first + "=" + field.second.content + " ";
  1362. }
  1363. res.set_content("ok", "text/plain");
  1364. });
  1365. auto port = svr.bind_to_any_port(HOST);
  1366. thread t = thread([&] { svr.listen_after_bind(); });
  1367. auto se = detail::scope_exit([&] {
  1368. svr.stop();
  1369. t.join();
  1370. ASSERT_FALSE(svr.is_running());
  1371. });
  1372. svr.wait_until_ready();
  1373. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1374. // not adjacent in the container.
  1375. UploadFormDataItems items = {
  1376. {"tag", "first", "", ""},
  1377. {"other", "x", "", ""},
  1378. {"tag", "second", "", ""},
  1379. };
  1380. Client cli(HOST, port);
  1381. auto res = cli.Post("/repeated", items);
  1382. ASSERT_TRUE(res);
  1383. ASSERT_EQ(2U, values.size());
  1384. EXPECT_EQ("first", values[0]);
  1385. EXPECT_EQ("second", values[1]);
  1386. EXPECT_EQ("first", first);
  1387. EXPECT_EQ("second", second);
  1388. // std::multimap already kept entries sharing a name in insertion order, so
  1389. // everything above passes without this change too. The whole traversal is
  1390. // what tells the two apart: sorting by name would hoist "other" to the front
  1391. // and the two "tag" parts would end up adjacent.
  1392. EXPECT_EQ("tag=first other=x tag=second ", order);
  1393. // Advancing past the last entry of a name used to run off the container;
  1394. // the container's saturating increment makes it return the default instead.
  1395. EXPECT_EQ("", out_of_range);
  1396. }
  1397. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1398. // Server::read_content() keeps a FormFields::iterator alive across the
  1399. // content callbacks that fill the part it points at. The container is
  1400. // vector-backed, so a later emplace can reallocate and invalidate an older
  1401. // iterator; 64 parts grow the vector through seven reallocations, which
  1402. // checks that every part's content still lands in its own entry.
  1403. const size_t part_count = 64;
  1404. // One formula for both the parts sent and the values expected back, so the
  1405. // two cannot drift apart.
  1406. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1407. auto content_of = [](size_t i) {
  1408. return std::string(64, static_cast<char>('a' + (i % 26)));
  1409. };
  1410. Server svr;
  1411. std::vector<std::pair<std::string, std::string>> received;
  1412. svr.Post("/many", [&](const Request &req, Response &res) {
  1413. for (const auto &field : req.form.fields) {
  1414. received.emplace_back(field.first, field.second.content);
  1415. }
  1416. res.set_content("ok", "text/plain");
  1417. });
  1418. auto port = svr.bind_to_any_port(HOST);
  1419. thread t = thread([&] { svr.listen_after_bind(); });
  1420. auto se = detail::scope_exit([&] {
  1421. svr.stop();
  1422. t.join();
  1423. ASSERT_FALSE(svr.is_running());
  1424. });
  1425. svr.wait_until_ready();
  1426. UploadFormDataItems items;
  1427. for (size_t i = 0; i < part_count; i++) {
  1428. items.push_back({name_of(i), content_of(i), "", ""});
  1429. }
  1430. Client cli(HOST, port);
  1431. auto res = cli.Post("/many", items);
  1432. ASSERT_TRUE(res);
  1433. ASSERT_EQ(part_count, received.size());
  1434. for (size_t i = 0; i < part_count; i++) {
  1435. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1436. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1437. }
  1438. }
  1439. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1440. string content_type = "multipart/form-data; boundary=something";
  1441. string boundary;
  1442. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1443. EXPECT_TRUE(ret);
  1444. EXPECT_EQ(boundary, "something");
  1445. }
  1446. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1447. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1448. string boundary;
  1449. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1450. EXPECT_TRUE(ret);
  1451. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1452. }
  1453. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1454. string content_type =
  1455. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1456. string boundary;
  1457. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1458. EXPECT_TRUE(ret);
  1459. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1460. }
  1461. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1462. string content_type =
  1463. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1464. string boundary;
  1465. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1466. EXPECT_TRUE(ret);
  1467. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1468. }
  1469. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1470. const string boundary(70, 'a');
  1471. string content_type = "multipart/form-data; boundary=" + boundary;
  1472. string parsed;
  1473. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1474. EXPECT_TRUE(ret);
  1475. EXPECT_EQ(parsed, boundary);
  1476. }
  1477. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1478. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1479. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1480. string parsed;
  1481. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1482. EXPECT_FALSE(ret);
  1483. }
  1484. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1485. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1486. // is 72 characters on the wire and still valid.
  1487. const string boundary(70, 'a');
  1488. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1489. string parsed;
  1490. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1491. EXPECT_EQ(parsed, boundary);
  1492. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1493. parsed.clear();
  1494. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1495. }
  1496. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1497. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1498. // The parameter parser must not treat that '=' as the key/value separator.
  1499. string content_type =
  1500. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1501. "charset=UTF-8";
  1502. string parsed;
  1503. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1504. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1505. }
  1506. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1507. // A ';' inside the quoted-string is part of the value, not a parameter
  1508. // separator, so it must not truncate the boundary.
  1509. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1510. string parsed;
  1511. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1512. EXPECT_EQ(parsed, "a;b");
  1513. }
  1514. TEST(ParseDispositionParamsTest, QuotedValues) {
  1515. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1516. // ';' and '=' are ordinary characters inside one.
  1517. struct {
  1518. const char *value;
  1519. std::vector<std::pair<const char *, const char *>> expected;
  1520. } cases[] = {
  1521. {"name=\"file1\"; filename=\"a.txt\"",
  1522. {{"name", "file1"}, {"filename", "a.txt"}}},
  1523. // Whitespace around '=' and ';' is still trimmed
  1524. {"name=\"file2\" ;filename = \"a.html\"",
  1525. {{"name", "file2"}, {"filename", "a.html"}}},
  1526. // '=' inside the value used to leave only the text after the last one
  1527. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1528. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1529. {"name=\"x=y\"", {{"name", "x=y"}}},
  1530. // ';' inside the value used to truncate the pair and leave a bogus one
  1531. {"name=\"file3\"; filename=\"a;b.txt\"",
  1532. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1533. // An unquoted value keeps working, and so does filename*
  1534. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1535. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1536. // A parameter with no key is dropped rather than turned into one whose
  1537. // key is the value
  1538. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1539. };
  1540. for (const auto &c : cases) {
  1541. Params params;
  1542. detail::parse_disposition_params(c.value, params);
  1543. for (const auto &kv : c.expected) {
  1544. auto it = params.find(kv.first);
  1545. ASSERT_NE(it, params.end())
  1546. << "value: " << c.value << ", key: " << kv.first;
  1547. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1548. }
  1549. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1550. }
  1551. }
  1552. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1553. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1554. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1555. Server svr;
  1556. std::string field_value, file_name, file_filename;
  1557. bool has_field = false, has_file = false;
  1558. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1559. has_field = req.form.has_field("x=y");
  1560. field_value = req.form.get_field("x=y");
  1561. has_file = req.form.has_file("file1");
  1562. const auto &file = req.form.get_file("file1");
  1563. file_name = file.name;
  1564. file_filename = file.filename;
  1565. res.set_content("ok", "text/plain");
  1566. });
  1567. auto port = svr.bind_to_any_port(HOST);
  1568. thread t = thread([&] { svr.listen_after_bind(); });
  1569. auto se = detail::scope_exit([&] {
  1570. svr.stop();
  1571. t.join();
  1572. ASSERT_FALSE(svr.is_running());
  1573. });
  1574. svr.wait_until_ready();
  1575. UploadFormDataItems items = {
  1576. {"x=y", "field-value", "", ""},
  1577. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1578. };
  1579. Client cli(HOST, port);
  1580. auto res = cli.Post("/quoted", items);
  1581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1582. ASSERT_EQ(StatusCode::OK_200, res->status);
  1583. EXPECT_TRUE(has_field);
  1584. EXPECT_EQ("field-value", field_value);
  1585. EXPECT_TRUE(has_file);
  1586. EXPECT_EQ("file1", file_name);
  1587. EXPECT_EQ("a;b=report.pdf", file_filename);
  1588. }
  1589. TEST(GetHeaderValueTest, DefaultValue) {
  1590. Headers headers = {{"Dummy", "Dummy"}};
  1591. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1592. EXPECT_STREQ("text/plain", val);
  1593. }
  1594. TEST(GetHeaderValueTest, DefaultValueInt) {
  1595. Headers headers = {{"Dummy", "Dummy"}};
  1596. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1597. EXPECT_EQ(100ull, val);
  1598. }
  1599. TEST(GetHeaderValueTest, RegularValue) {
  1600. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1601. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1602. EXPECT_STREQ("text/html", val);
  1603. }
  1604. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1605. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1606. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1607. EXPECT_STREQ("text/html", val);
  1608. }
  1609. TEST(GetHeaderValueTest, SetContent) {
  1610. Response res;
  1611. res.set_content("html", "text/html");
  1612. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1613. res.set_content("text", "text/plain");
  1614. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1615. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1616. }
  1617. TEST(GetHeaderValueTest, RegularValueInt) {
  1618. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1619. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1620. EXPECT_EQ(100ull, val);
  1621. }
  1622. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1623. Headers headers = {{"Content-Length", "x"}};
  1624. auto is_invalid_value = false;
  1625. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1626. is_invalid_value);
  1627. EXPECT_EQ(0ull, val);
  1628. EXPECT_TRUE(is_invalid_value);
  1629. }
  1630. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1631. // An all-digit value that overflows size_t must be reported as invalid, not
  1632. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1633. // a large length to a small one on 32-bit builds, leaving the framing length
  1634. // wrong while is_invalid_value stayed false.
  1635. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1636. auto is_invalid_value = false;
  1637. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1638. is_invalid_value);
  1639. EXPECT_TRUE(is_invalid_value);
  1640. // A well-formed length is unaffected.
  1641. Headers ok = {{"Content-Length", "1234"}};
  1642. is_invalid_value = false;
  1643. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1644. is_invalid_value);
  1645. EXPECT_EQ(1234ull, val);
  1646. EXPECT_FALSE(is_invalid_value);
  1647. }
  1648. TEST(GetHeaderValueTest, Range) {
  1649. {
  1650. Headers headers = {make_range_header({{1, -1}})};
  1651. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1652. EXPECT_STREQ("bytes=1-", val);
  1653. }
  1654. {
  1655. Headers headers = {make_range_header({{-1, 1}})};
  1656. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1657. EXPECT_STREQ("bytes=-1", val);
  1658. }
  1659. {
  1660. Headers headers = {make_range_header({{1, 10}})};
  1661. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1662. EXPECT_STREQ("bytes=1-10", val);
  1663. }
  1664. {
  1665. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1666. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1667. EXPECT_STREQ("bytes=1-10, 100-", val);
  1668. }
  1669. {
  1670. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1671. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1672. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1673. }
  1674. {
  1675. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1676. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1677. EXPECT_STREQ("bytes=0-0, -1", val);
  1678. }
  1679. }
  1680. TEST(BearerTokenAuthTest, SchemeValidation) {
  1681. // A value shorter than "Bearer " must not throw from the fixed-length
  1682. // substr, and a non-Bearer scheme must not be reported as a token.
  1683. struct {
  1684. const char *value;
  1685. const char *expected;
  1686. } cases[] = {
  1687. {"x", ""},
  1688. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1689. {"Bearer abc123", "abc123"},
  1690. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1691. };
  1692. for (const auto &c : cases) {
  1693. Request req;
  1694. req.set_header("Authorization", c.value);
  1695. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1696. }
  1697. }
  1698. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1699. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1700. // to depend on the standard library (libstdc++ handed back duplicates in
  1701. // reverse insertion order, libc++ in insertion order).
  1702. Request req;
  1703. req.set_header("Accept-Encoding", "gzip");
  1704. req.set_header("Accept-Encoding", "deflate");
  1705. req.set_header("Accept-Encoding", "br");
  1706. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1707. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1708. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1709. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1710. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1711. }
  1712. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1713. Request req;
  1714. req.set_header("X-Test", "only");
  1715. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1716. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1717. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1718. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1719. }
  1720. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1721. Request req;
  1722. req.set_header("X-First", "1");
  1723. req.set_header("X-Test", "2");
  1724. req.params.emplace("first", "1");
  1725. req.params.emplace("test", "2");
  1726. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1727. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1728. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1729. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1730. // The second one is negative when read as a signed value
  1731. const auto max_id = (std::numeric_limits<size_t>::max)();
  1732. for (auto id : {max_id / 2, max_id}) {
  1733. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1734. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1735. EXPECT_EQ("", req.get_param_value("test", id));
  1736. EXPECT_EQ("", req.form.get_field("test", id));
  1737. EXPECT_EQ("", req.form.get_file("test", id).content);
  1738. }
  1739. }
  1740. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1741. Headers headers;
  1742. headers.emplace("Host", "example.com");
  1743. headers.emplace("Accept-Encoding", "gzip");
  1744. headers.emplace("User-Agent", "test");
  1745. headers.emplace("Accept-Encoding", "deflate");
  1746. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1747. "Accept-Encoding=deflate ",
  1748. entries_to_string(headers));
  1749. }
  1750. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1751. Headers headers = {{"Content-Type", "text/html"},
  1752. {"CONTENT-TYPE", "text/xml"}};
  1753. EXPECT_EQ(2U, headers.count("content-type"));
  1754. auto it = headers.find("content-type");
  1755. ASSERT_TRUE(it != headers.end());
  1756. EXPECT_EQ("text/html", it->second);
  1757. }
  1758. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1759. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1760. // drop only those fields and leave everything positioned between them.
  1761. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1762. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1763. auto rng = headers.equal_range("a");
  1764. headers.erase(rng.first, rng.second);
  1765. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1766. }
  1767. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1768. Headers headers = {
  1769. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1770. EXPECT_EQ(3U, headers.erase("A"));
  1771. EXPECT_EQ(0U, headers.count("A"));
  1772. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1773. }
  1774. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1775. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1776. headers.emplace_front("Host", "example.com");
  1777. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1778. entries_to_string(headers));
  1779. }
  1780. TEST(ParseHeaderValueTest, Range) {
  1781. {
  1782. Ranges ranges;
  1783. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1784. EXPECT_TRUE(ret);
  1785. EXPECT_EQ(1u, ranges.size());
  1786. EXPECT_EQ(1u, ranges[0].first);
  1787. EXPECT_EQ(-1, ranges[0].second);
  1788. }
  1789. {
  1790. Ranges ranges;
  1791. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1792. EXPECT_TRUE(ret);
  1793. EXPECT_EQ(1u, ranges.size());
  1794. EXPECT_EQ(-1, ranges[0].first);
  1795. EXPECT_EQ(1u, ranges[0].second);
  1796. }
  1797. {
  1798. Ranges ranges;
  1799. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1800. EXPECT_TRUE(ret);
  1801. EXPECT_EQ(1u, ranges.size());
  1802. EXPECT_EQ(1u, ranges[0].first);
  1803. EXPECT_EQ(10u, ranges[0].second);
  1804. }
  1805. {
  1806. Ranges ranges;
  1807. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1808. EXPECT_FALSE(ret);
  1809. }
  1810. {
  1811. Ranges ranges;
  1812. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1813. EXPECT_TRUE(ret);
  1814. EXPECT_EQ(2u, ranges.size());
  1815. EXPECT_EQ(1u, ranges[0].first);
  1816. EXPECT_EQ(10u, ranges[0].second);
  1817. EXPECT_EQ(100u, ranges[1].first);
  1818. EXPECT_EQ(-1, ranges[1].second);
  1819. }
  1820. {
  1821. Ranges ranges;
  1822. auto ret =
  1823. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1824. EXPECT_TRUE(ret);
  1825. EXPECT_EQ(3u, ranges.size());
  1826. EXPECT_EQ(1u, ranges[0].first);
  1827. EXPECT_EQ(10u, ranges[0].second);
  1828. EXPECT_EQ(100u, ranges[1].first);
  1829. EXPECT_EQ(200u, ranges[1].second);
  1830. EXPECT_EQ(300u, ranges[2].first);
  1831. EXPECT_EQ(400u, ranges[2].second);
  1832. }
  1833. {
  1834. Ranges ranges;
  1835. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1836. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1837. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1838. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1839. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1840. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1841. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1842. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1843. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1844. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1845. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1846. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1847. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1848. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1849. EXPECT_FALSE(
  1850. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1851. EXPECT_TRUE(ranges.empty());
  1852. }
  1853. {
  1854. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1855. // remainder of the representation, so it stays accepted.
  1856. Ranges ranges;
  1857. auto ret =
  1858. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1859. EXPECT_TRUE(ret);
  1860. ASSERT_EQ(1u, ranges.size());
  1861. EXPECT_EQ(0, ranges[0].first);
  1862. EXPECT_EQ(-1, ranges[0].second);
  1863. }
  1864. // RFC 9110 14.1: range unit names are case-insensitive.
  1865. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1866. Ranges ranges;
  1867. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1868. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1869. }
  1870. }
  1871. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1872. Request req;
  1873. req.set_header("Accept-Encoding", "gzip");
  1874. Response res;
  1875. res.set_header("Content-Type", "text/plain");
  1876. auto ret = detail::encoding_type(req, res);
  1877. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1878. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1879. #else
  1880. EXPECT_TRUE(ret == detail::EncodingType::None);
  1881. #endif
  1882. }
  1883. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1884. Request req;
  1885. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1886. Response res;
  1887. res.set_header("Content-Type", "text/plain");
  1888. auto ret = detail::encoding_type(req, res);
  1889. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1890. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1891. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1892. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1893. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1894. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1895. #else
  1896. EXPECT_TRUE(ret == detail::EncodingType::None);
  1897. #endif
  1898. }
  1899. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1900. Request req;
  1901. req.set_header("Accept-Encoding",
  1902. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1903. Response res;
  1904. res.set_header("Content-Type", "text/plain");
  1905. auto ret = detail::encoding_type(req, res);
  1906. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1907. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1908. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1909. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1910. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1911. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1912. #else
  1913. EXPECT_TRUE(ret == detail::EncodingType::None);
  1914. #endif
  1915. }
  1916. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1917. // All supported encodings rejected with q=0 should return None
  1918. Request req;
  1919. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1920. Response res;
  1921. res.set_header("Content-Type", "text/plain");
  1922. auto ret = detail::encoding_type(req, res);
  1923. EXPECT_TRUE(ret == detail::EncodingType::None);
  1924. }
  1925. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1926. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1927. Request req;
  1928. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1929. Response res;
  1930. res.set_header("Content-Type", "text/plain");
  1931. auto ret = detail::encoding_type(req, res);
  1932. EXPECT_TRUE(ret == detail::EncodingType::None);
  1933. }
  1934. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  1935. Request req;
  1936. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  1937. Response res;
  1938. res.set_header("Content-Type", "text/plain");
  1939. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  1940. }
  1941. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1942. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1943. Request req;
  1944. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1945. Response res;
  1946. res.set_header("Content-Type", "text/plain");
  1947. auto ret = detail::encoding_type(req, res);
  1948. EXPECT_TRUE(ret == detail::EncodingType::None);
  1949. }
  1950. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1951. // RFC 7231: Accept-Encoding values are case-insensitive
  1952. Request req;
  1953. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1954. Response res;
  1955. res.set_header("Content-Type", "text/plain");
  1956. auto ret = detail::encoding_type(req, res);
  1957. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1958. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1959. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1960. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1961. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1962. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1963. #else
  1964. EXPECT_TRUE(ret == detail::EncodingType::None);
  1965. #endif
  1966. }
  1967. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1968. // q value should determine priority, not hardcoded order
  1969. Request req;
  1970. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1971. Response res;
  1972. res.set_header("Content-Type", "text/plain");
  1973. auto ret = detail::encoding_type(req, res);
  1974. // gzip has highest q=1.0, so it should be selected even though
  1975. // br and zstd are also supported
  1976. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1977. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1978. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1979. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1980. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1981. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1982. #else
  1983. EXPECT_TRUE(ret == detail::EncodingType::None);
  1984. #endif
  1985. }
  1986. TEST(BufferStreamTest, read) {
  1987. detail::BufferStream strm1;
  1988. Stream &strm = strm1;
  1989. EXPECT_EQ(5, strm.write("hello"));
  1990. char buf[512];
  1991. EXPECT_EQ(2, strm.read(buf, 2));
  1992. EXPECT_EQ('h', buf[0]);
  1993. EXPECT_EQ('e', buf[1]);
  1994. EXPECT_EQ(2, strm.read(buf, 2));
  1995. EXPECT_EQ('l', buf[0]);
  1996. EXPECT_EQ('l', buf[1]);
  1997. EXPECT_EQ(1, strm.read(buf, 1));
  1998. EXPECT_EQ('o', buf[0]);
  1999. EXPECT_EQ(0, strm.read(buf, 1));
  2000. }
  2001. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2002. auto host = "www.httpwatch.com";
  2003. auto ip = hosted_at(host);
  2004. EXPECT_EQ("23.96.13.243", ip);
  2005. std::vector<std::string> addrs;
  2006. hosted_at(host, addrs);
  2007. EXPECT_EQ(1u, addrs.size());
  2008. }
  2009. #if 0 // It depends on each test environment...
  2010. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2011. auto host = "www.youtube.com";
  2012. std::vector<std::string> addrs;
  2013. hosted_at(host, addrs);
  2014. EXPECT_EQ(20u, addrs.size());
  2015. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2016. EXPECT_TRUE(it != addrs.end());
  2017. }
  2018. #endif
  2019. class ChunkedEncodingTest : public ::testing::Test {
  2020. protected:
  2021. ChunkedEncodingTest()
  2022. : cli_(HOST, PORT)
  2023. #ifdef CPPHTTPLIB_SSL_ENABLED
  2024. ,
  2025. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2026. #endif
  2027. {
  2028. cli_.set_connection_timeout(2);
  2029. #ifdef CPPHTTPLIB_SSL_ENABLED
  2030. cli_.enable_server_certificate_verification(false);
  2031. #endif
  2032. }
  2033. virtual void SetUp() {
  2034. read_file("./image.jpg", image_data_);
  2035. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2036. res.set_content("Hello World!", "text/plain");
  2037. });
  2038. svr_.Get(
  2039. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2040. res.set_chunked_content_provider(
  2041. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2042. size_t remaining = image_data_.size() - offset;
  2043. if (remaining == 0) {
  2044. sink.done();
  2045. } else {
  2046. constexpr size_t CHUNK_SIZE = 1024;
  2047. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2048. sink.write(&image_data_[offset], send_size);
  2049. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2050. }
  2051. return true;
  2052. });
  2053. });
  2054. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2055. svr_.wait_until_ready();
  2056. }
  2057. virtual void TearDown() {
  2058. svr_.stop();
  2059. if (!request_threads_.empty()) {
  2060. std::this_thread::sleep_for(std::chrono::seconds(1));
  2061. for (auto &t : request_threads_) {
  2062. t.join();
  2063. }
  2064. }
  2065. t_.join();
  2066. }
  2067. #ifdef CPPHTTPLIB_SSL_ENABLED
  2068. SSLClient cli_;
  2069. SSLServer svr_;
  2070. #else
  2071. Client cli_;
  2072. Server svr_;
  2073. #endif
  2074. thread t_;
  2075. std::vector<thread> request_threads_;
  2076. std::string image_data_;
  2077. };
  2078. TEST_F(ChunkedEncodingTest, NormalGet) {
  2079. auto res = cli_.Get("/chunked");
  2080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2081. std::string out;
  2082. read_file("./image.jpg", out);
  2083. EXPECT_EQ(StatusCode::OK_200, res->status);
  2084. EXPECT_EQ(out, res->body);
  2085. }
  2086. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2087. std::string body;
  2088. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2089. body.append(data, data_length);
  2090. return true;
  2091. });
  2092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2093. std::string out;
  2094. read_file("./image.jpg", out);
  2095. EXPECT_EQ(StatusCode::OK_200, res->status);
  2096. EXPECT_EQ(out, body);
  2097. }
  2098. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2099. std::string body;
  2100. auto res = cli_.Get(
  2101. "/chunked",
  2102. [&](const Response &response) {
  2103. EXPECT_EQ(StatusCode::OK_200, response.status);
  2104. return true;
  2105. },
  2106. [&](const char *data, size_t data_length) {
  2107. body.append(data, data_length);
  2108. return true;
  2109. });
  2110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2111. std::string out;
  2112. read_file("./image.jpg", out);
  2113. EXPECT_EQ(StatusCode::OK_200, res->status);
  2114. EXPECT_EQ(out, body);
  2115. }
  2116. TEST(RangeTest, FromHTTPBin_Online) {
  2117. auto host = "httpbingo.org";
  2118. auto path = std::string{"/range/32"};
  2119. #ifdef CPPHTTPLIB_SSL_ENABLED
  2120. auto port = 443;
  2121. SSLClient cli(host, port);
  2122. #else
  2123. auto port = 80;
  2124. Client cli(host, port);
  2125. #endif
  2126. cli.set_connection_timeout(5);
  2127. {
  2128. auto res = cli.Get(path);
  2129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2130. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2131. EXPECT_EQ(StatusCode::OK_200, res->status);
  2132. }
  2133. {
  2134. Headers headers = {make_range_header({{1, -1}})};
  2135. auto res = cli.Get(path, headers);
  2136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2137. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2138. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2139. }
  2140. {
  2141. Headers headers = {make_range_header({{1, 10}})};
  2142. auto res = cli.Get(path, headers);
  2143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2144. EXPECT_EQ("bcdefghijk", res->body);
  2145. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2146. }
  2147. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2148. // entire resource, while the original httpbin returned 200. Both are
  2149. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2150. {
  2151. Headers headers = {make_range_header({{0, 31}})};
  2152. auto res = cli.Get(path, headers);
  2153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2154. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2155. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2156. res->status == StatusCode::PartialContent_206);
  2157. }
  2158. {
  2159. Headers headers = {make_range_header({{0, -1}})};
  2160. auto res = cli.Get(path, headers);
  2161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2162. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2163. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2164. res->status == StatusCode::PartialContent_206);
  2165. }
  2166. // go-httpbin returns 206 with clamped range for over-range requests,
  2167. // while the original httpbin returned 416. Both behaviors are observed
  2168. // in real servers, so we only verify the request succeeds.
  2169. {
  2170. Headers headers = {make_range_header({{0, 32}})};
  2171. auto res = cli.Get(path, headers);
  2172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2173. }
  2174. }
  2175. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2176. auto host = "unresolvableaddress.local";
  2177. auto path = std::string{"/"};
  2178. #ifdef CPPHTTPLIB_SSL_ENABLED
  2179. auto port = 443;
  2180. SSLClient cli(host, port);
  2181. #else
  2182. auto port = 80;
  2183. Client cli(host, port);
  2184. #endif
  2185. cli.set_connection_timeout(1);
  2186. {
  2187. auto res = cli.Get(path);
  2188. ASSERT_FALSE(res);
  2189. }
  2190. std::this_thread::sleep_for(std::chrono::seconds(8));
  2191. }
  2192. #if defined(__linux__) && defined(__GLIBC__) && \
  2193. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2194. // Forward declaration: in split builds split.py strips `inline` and moves the
  2195. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2196. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2197. // against the symbol in both header-only and split builds.
  2198. namespace httplib {
  2199. namespace detail {
  2200. int getaddrinfo_with_timeout(const char *node, const char *service,
  2201. const struct addrinfo *hints,
  2202. struct addrinfo **res, time_t timeout_sec);
  2203. } // namespace detail
  2204. } // namespace httplib
  2205. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2206. //
  2207. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2208. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2209. // gai_suspend() call hits the connection timeout the function calls
  2210. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2211. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2212. // still alive and still references the now-destroyed stack frame.
  2213. //
  2214. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2215. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2216. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2217. // and runs them in a container.
  2218. namespace {
  2219. bool should_run_issue_2431_tests() {
  2220. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2221. return v && *v && std::string(v) != "0";
  2222. }
  2223. std::string unique_unresolvable_host(int n) {
  2224. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2225. // glibc still asks the configured nameserver — which is exactly the path
  2226. // we want to exercise. A unique label per call avoids the resolver cache.
  2227. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2228. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2229. std::to_string(n) + ".invalid";
  2230. }
  2231. } // namespace
  2232. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2233. if (!should_run_issue_2431_tests()) {
  2234. GTEST_SKIP()
  2235. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2236. }
  2237. for (int i = 0; i < 8; ++i) {
  2238. struct addrinfo hints;
  2239. memset(&hints, 0, sizeof(hints));
  2240. hints.ai_family = AF_UNSPEC;
  2241. hints.ai_socktype = SOCK_STREAM;
  2242. auto host = unique_unresolvable_host(i);
  2243. struct addrinfo *result = nullptr;
  2244. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2245. &result, /*timeout_sec=*/1);
  2246. if (rc == 0 && result) { freeaddrinfo(result); }
  2247. }
  2248. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2249. // stack region they still believe holds their gaicb.
  2250. std::this_thread::sleep_for(std::chrono::seconds(3));
  2251. }
  2252. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2253. if (!should_run_issue_2431_tests()) {
  2254. GTEST_SKIP()
  2255. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2256. }
  2257. std::atomic<bool> stop{false};
  2258. std::vector<std::thread> threads;
  2259. for (int t = 0; t < 8; ++t) {
  2260. threads.emplace_back([t, &stop] {
  2261. int i = 0;
  2262. while (!stop.load(std::memory_order_relaxed)) {
  2263. struct addrinfo hints;
  2264. memset(&hints, 0, sizeof(hints));
  2265. hints.ai_family = AF_UNSPEC;
  2266. hints.ai_socktype = SOCK_STREAM;
  2267. auto host = unique_unresolvable_host(t * 100000 + i++);
  2268. struct addrinfo *result = nullptr;
  2269. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2270. &result, /*timeout_sec=*/1);
  2271. if (rc == 0 && result) { freeaddrinfo(result); }
  2272. }
  2273. });
  2274. }
  2275. std::this_thread::sleep_for(std::chrono::seconds(8));
  2276. stop.store(true, std::memory_order_relaxed);
  2277. for (auto &th : threads) {
  2278. th.join();
  2279. }
  2280. std::this_thread::sleep_for(std::chrono::seconds(3));
  2281. }
  2282. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2283. if (!should_run_issue_2431_tests()) {
  2284. GTEST_SKIP()
  2285. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2286. }
  2287. std::atomic<bool> stop{false};
  2288. std::vector<std::thread> threads;
  2289. for (int t = 0; t < 8; ++t) {
  2290. threads.emplace_back([t, &stop] {
  2291. int i = 0;
  2292. while (!stop.load(std::memory_order_relaxed)) {
  2293. auto host = unique_unresolvable_host(t * 100000 + i++);
  2294. Client cli(host, 80);
  2295. cli.set_connection_timeout(1, 0);
  2296. cli.set_read_timeout(1, 0);
  2297. cli.set_write_timeout(1, 0);
  2298. (void)cli.Get("/");
  2299. }
  2300. });
  2301. }
  2302. std::this_thread::sleep_for(std::chrono::seconds(8));
  2303. stop.store(true, std::memory_order_relaxed);
  2304. for (auto &th : threads) {
  2305. th.join();
  2306. }
  2307. std::this_thread::sleep_for(std::chrono::seconds(3));
  2308. }
  2309. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2310. TEST(ConnectionErrorTest, InvalidHost) {
  2311. auto host = "-abcde.com";
  2312. #ifdef CPPHTTPLIB_SSL_ENABLED
  2313. auto port = 443;
  2314. SSLClient cli(host, port);
  2315. #else
  2316. auto port = 80;
  2317. Client cli(host, port);
  2318. #endif
  2319. cli.set_connection_timeout(std::chrono::seconds(2));
  2320. auto res = cli.Get("/");
  2321. ASSERT_TRUE(!res);
  2322. EXPECT_EQ(Error::Connection, res.error());
  2323. }
  2324. TEST(ConnectionErrorTest, InvalidHost2) {
  2325. auto host = "httpcan.org/";
  2326. #ifdef CPPHTTPLIB_SSL_ENABLED
  2327. SSLClient cli(host);
  2328. #else
  2329. Client cli(host);
  2330. #endif
  2331. cli.set_connection_timeout(std::chrono::seconds(2));
  2332. auto res = cli.Get("/");
  2333. ASSERT_TRUE(!res);
  2334. EXPECT_EQ(Error::Connection, res.error());
  2335. }
  2336. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2337. auto host = "httpcan.org/";
  2338. #ifdef CPPHTTPLIB_SSL_ENABLED
  2339. SSLClient cli(host);
  2340. #else
  2341. Client cli(host);
  2342. #endif
  2343. cli.set_connection_timeout(std::chrono::seconds(2));
  2344. auto res = cli.Get("/");
  2345. ASSERT_TRUE(!res);
  2346. stringstream s;
  2347. s << "error code: " << res.error();
  2348. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2349. }
  2350. TEST(ConnectionErrorTest, InvalidPort) {
  2351. auto host = "localhost";
  2352. auto port = 44380;
  2353. #ifdef CPPHTTPLIB_SSL_ENABLED
  2354. SSLClient cli(host, port);
  2355. #else
  2356. Client cli(host, port);
  2357. #endif
  2358. cli.set_connection_timeout(std::chrono::seconds(2));
  2359. auto res = cli.Get("/");
  2360. ASSERT_TRUE(!res);
  2361. EXPECT_TRUE(Error::Connection == res.error() ||
  2362. Error::ConnectionTimeout == res.error());
  2363. }
  2364. TEST(ConnectionErrorTest, Timeout_Online) {
  2365. auto host = "google.com";
  2366. #ifdef CPPHTTPLIB_SSL_ENABLED
  2367. auto port = 44380;
  2368. SSLClient cli(host, port);
  2369. #else
  2370. auto port = 8080;
  2371. Client cli(host, port);
  2372. #endif
  2373. cli.set_connection_timeout(std::chrono::seconds(2));
  2374. // only probe one address type so that the error reason
  2375. // correlates to the timed-out IPv4, not the unsupported
  2376. // IPv6 connection attempt
  2377. cli.set_address_family(AF_INET);
  2378. auto res = cli.Get("/");
  2379. ASSERT_TRUE(!res);
  2380. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2381. }
  2382. TEST(CancelTest, NoCancel_Online) {
  2383. auto host = "httpbingo.org";
  2384. auto path = std::string{"/range/32"};
  2385. #ifdef CPPHTTPLIB_SSL_ENABLED
  2386. auto port = 443;
  2387. SSLClient cli(host, port);
  2388. #else
  2389. auto port = 80;
  2390. Client cli(host, port);
  2391. #endif
  2392. cli.set_connection_timeout(std::chrono::seconds(5));
  2393. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2395. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2396. EXPECT_EQ(StatusCode::OK_200, res->status);
  2397. }
  2398. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2399. // Use /bytes with a large payload so that the DownloadProgress callback
  2400. // (which only fires for Content-Length responses) is invoked before the
  2401. // entire body is received, giving cancellation a chance to fire.
  2402. auto host = "httpbingo.org";
  2403. auto path = std::string{"/bytes/524288"};
  2404. #ifdef CPPHTTPLIB_SSL_ENABLED
  2405. auto port = 443;
  2406. SSLClient cli(host, port);
  2407. #else
  2408. auto port = 80;
  2409. Client cli(host, port);
  2410. #endif
  2411. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2412. cli.set_connection_timeout(std::chrono::seconds(5));
  2413. ASSERT_TRUE(!res);
  2414. EXPECT_EQ(Error::Canceled, res.error());
  2415. }
  2416. TEST(CancelTest, WithCancelLargePayload_Online) {
  2417. auto host = "httpbingo.org";
  2418. auto path = std::string{"/bytes/524288"};
  2419. #ifdef CPPHTTPLIB_SSL_ENABLED
  2420. auto port = 443;
  2421. SSLClient cli(host, port);
  2422. #else
  2423. auto port = 80;
  2424. Client cli(host, port);
  2425. #endif
  2426. cli.set_connection_timeout(std::chrono::seconds(5));
  2427. uint32_t count = 0;
  2428. auto res =
  2429. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2430. ASSERT_TRUE(!res);
  2431. EXPECT_EQ(Error::Canceled, res.error());
  2432. }
  2433. TEST(CancelTest, NoCancelPost) {
  2434. Server svr;
  2435. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2436. res.set_content("Hello World!", "text/plain");
  2437. });
  2438. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2439. auto se = detail::scope_exit([&] {
  2440. svr.stop();
  2441. thread.join();
  2442. ASSERT_FALSE(svr.is_running());
  2443. });
  2444. svr.wait_until_ready();
  2445. Client cli(HOST, PORT);
  2446. cli.set_connection_timeout(std::chrono::seconds(5));
  2447. auto res =
  2448. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2449. "application/json", [](uint64_t, uint64_t) { return true; });
  2450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2451. EXPECT_EQ("Hello World!", res->body);
  2452. EXPECT_EQ(StatusCode::OK_200, res->status);
  2453. }
  2454. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2455. Server svr;
  2456. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2457. res.set_content("Hello World!", "text/plain");
  2458. });
  2459. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2460. auto se = detail::scope_exit([&] {
  2461. svr.stop();
  2462. thread.join();
  2463. ASSERT_FALSE(svr.is_running());
  2464. });
  2465. svr.wait_until_ready();
  2466. Client cli(HOST, PORT);
  2467. cli.set_connection_timeout(std::chrono::seconds(5));
  2468. auto res =
  2469. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2470. "application/json", [](uint64_t, uint64_t) { return false; });
  2471. ASSERT_TRUE(!res);
  2472. EXPECT_EQ(Error::Canceled, res.error());
  2473. }
  2474. TEST(CancelTest, WithCancelLargePayloadPost) {
  2475. Server svr;
  2476. svr.set_payload_max_length(200 * 1024 * 1024);
  2477. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2478. res.set_content(LARGE_DATA, "text/plain");
  2479. });
  2480. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2481. auto se = detail::scope_exit([&] {
  2482. svr.stop();
  2483. thread.join();
  2484. ASSERT_FALSE(svr.is_running());
  2485. });
  2486. svr.wait_until_ready();
  2487. Client cli(HOST, PORT);
  2488. cli.set_payload_max_length(200 * 1024 * 1024);
  2489. cli.set_connection_timeout(std::chrono::seconds(5));
  2490. auto res =
  2491. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2492. "application/json", [](uint64_t, uint64_t) { return false; });
  2493. ASSERT_TRUE(!res);
  2494. EXPECT_EQ(Error::Canceled, res.error());
  2495. }
  2496. TEST(CancelTest, NoCancelPut) {
  2497. Server svr;
  2498. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2499. res.set_content("Hello World!", "text/plain");
  2500. });
  2501. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2502. auto se = detail::scope_exit([&] {
  2503. svr.stop();
  2504. thread.join();
  2505. ASSERT_FALSE(svr.is_running());
  2506. });
  2507. svr.wait_until_ready();
  2508. Client cli(HOST, PORT);
  2509. cli.set_connection_timeout(std::chrono::seconds(5));
  2510. auto res =
  2511. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2512. "application/json", [](uint64_t, uint64_t) { return true; });
  2513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2514. EXPECT_EQ("Hello World!", res->body);
  2515. EXPECT_EQ(StatusCode::OK_200, res->status);
  2516. }
  2517. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2518. Server svr;
  2519. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2520. res.set_content("Hello World!", "text/plain");
  2521. });
  2522. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2523. auto se = detail::scope_exit([&] {
  2524. svr.stop();
  2525. thread.join();
  2526. ASSERT_FALSE(svr.is_running());
  2527. });
  2528. svr.wait_until_ready();
  2529. Client cli(HOST, PORT);
  2530. cli.set_connection_timeout(std::chrono::seconds(5));
  2531. auto res =
  2532. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2533. "application/json", [](uint64_t, uint64_t) { return false; });
  2534. ASSERT_TRUE(!res);
  2535. EXPECT_EQ(Error::Canceled, res.error());
  2536. }
  2537. TEST(CancelTest, WithCancelLargePayloadPut) {
  2538. Server svr;
  2539. svr.set_payload_max_length(200 * 1024 * 1024);
  2540. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2541. res.set_content(LARGE_DATA, "text/plain");
  2542. });
  2543. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2544. auto se = detail::scope_exit([&] {
  2545. svr.stop();
  2546. thread.join();
  2547. ASSERT_FALSE(svr.is_running());
  2548. });
  2549. svr.wait_until_ready();
  2550. Client cli(HOST, PORT);
  2551. cli.set_payload_max_length(200 * 1024 * 1024);
  2552. cli.set_connection_timeout(std::chrono::seconds(5));
  2553. auto res =
  2554. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2555. "application/json", [](uint64_t, uint64_t) { return false; });
  2556. ASSERT_TRUE(!res);
  2557. EXPECT_EQ(Error::Canceled, res.error());
  2558. }
  2559. TEST(CancelTest, NoCancelPatch) {
  2560. Server svr;
  2561. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2562. res.set_content("Hello World!", "text/plain");
  2563. });
  2564. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2565. auto se = detail::scope_exit([&] {
  2566. svr.stop();
  2567. thread.join();
  2568. ASSERT_FALSE(svr.is_running());
  2569. });
  2570. svr.wait_until_ready();
  2571. Client cli(HOST, PORT);
  2572. cli.set_connection_timeout(std::chrono::seconds(5));
  2573. auto res =
  2574. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2575. "application/json", [](uint64_t, uint64_t) { return true; });
  2576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2577. EXPECT_EQ("Hello World!", res->body);
  2578. EXPECT_EQ(StatusCode::OK_200, res->status);
  2579. }
  2580. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2581. Server svr;
  2582. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2583. res.set_content("Hello World!", "text/plain");
  2584. });
  2585. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2586. auto se = detail::scope_exit([&] {
  2587. svr.stop();
  2588. thread.join();
  2589. ASSERT_FALSE(svr.is_running());
  2590. });
  2591. svr.wait_until_ready();
  2592. Client cli(HOST, PORT);
  2593. cli.set_connection_timeout(std::chrono::seconds(5));
  2594. auto res =
  2595. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2596. "application/json", [](uint64_t, uint64_t) { return false; });
  2597. ASSERT_TRUE(!res);
  2598. EXPECT_EQ(Error::Canceled, res.error());
  2599. }
  2600. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2601. Server svr;
  2602. svr.set_payload_max_length(200 * 1024 * 1024);
  2603. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2604. res.set_content(LARGE_DATA, "text/plain");
  2605. });
  2606. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2607. auto se = detail::scope_exit([&] {
  2608. svr.stop();
  2609. thread.join();
  2610. ASSERT_FALSE(svr.is_running());
  2611. });
  2612. svr.wait_until_ready();
  2613. Client cli(HOST, PORT);
  2614. cli.set_payload_max_length(200 * 1024 * 1024);
  2615. cli.set_connection_timeout(std::chrono::seconds(5));
  2616. auto res =
  2617. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2618. "application/json", [](uint64_t, uint64_t) { return false; });
  2619. ASSERT_TRUE(!res);
  2620. EXPECT_EQ(Error::Canceled, res.error());
  2621. }
  2622. TEST(CancelTest, NoCancelDelete) {
  2623. Server svr;
  2624. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2625. res.set_content("Hello World!", "text/plain");
  2626. });
  2627. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2628. auto se = detail::scope_exit([&] {
  2629. svr.stop();
  2630. thread.join();
  2631. ASSERT_FALSE(svr.is_running());
  2632. });
  2633. svr.wait_until_ready();
  2634. Client cli(HOST, PORT);
  2635. cli.set_connection_timeout(std::chrono::seconds(5));
  2636. auto res =
  2637. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2638. "application/json", [](uint64_t, uint64_t) { return true; });
  2639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2640. EXPECT_EQ("Hello World!", res->body);
  2641. EXPECT_EQ(StatusCode::OK_200, res->status);
  2642. }
  2643. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2644. Server svr;
  2645. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2646. res.set_content("Hello World!", "text/plain");
  2647. });
  2648. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2649. auto se = detail::scope_exit([&] {
  2650. svr.stop();
  2651. thread.join();
  2652. ASSERT_FALSE(svr.is_running());
  2653. });
  2654. svr.wait_until_ready();
  2655. Client cli(HOST, PORT);
  2656. cli.set_connection_timeout(std::chrono::seconds(5));
  2657. auto res =
  2658. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2659. "application/json", [](uint64_t, uint64_t) { return false; });
  2660. ASSERT_TRUE(!res);
  2661. EXPECT_EQ(Error::Canceled, res.error());
  2662. }
  2663. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2664. Server svr;
  2665. svr.set_payload_max_length(200 * 1024 * 1024);
  2666. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2667. res.set_content(LARGE_DATA, "text/plain");
  2668. });
  2669. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2670. auto se = detail::scope_exit([&] {
  2671. svr.stop();
  2672. thread.join();
  2673. ASSERT_FALSE(svr.is_running());
  2674. });
  2675. svr.wait_until_ready();
  2676. Client cli(HOST, PORT);
  2677. cli.set_payload_max_length(200 * 1024 * 1024);
  2678. cli.set_connection_timeout(std::chrono::seconds(5));
  2679. auto res =
  2680. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2681. "application/json", [](uint64_t, uint64_t) { return false; });
  2682. ASSERT_TRUE(!res);
  2683. EXPECT_EQ(Error::Canceled, res.error());
  2684. }
  2685. static std::string remove_whitespace(const std::string &input) {
  2686. std::string output;
  2687. output.reserve(input.size());
  2688. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2689. [](unsigned char c) { return !std::isspace(c); });
  2690. return output;
  2691. }
  2692. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2693. auto host = "httpbingo.org";
  2694. auto path = std::string{"/basic-auth/hello/world"};
  2695. #ifdef CPPHTTPLIB_SSL_ENABLED
  2696. auto port = 443;
  2697. SSLClient cli(host, port);
  2698. #else
  2699. auto port = 80;
  2700. Client cli(host, port);
  2701. #endif
  2702. {
  2703. auto res = cli.Get(path);
  2704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2705. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2706. }
  2707. {
  2708. auto res = cli.Get(
  2709. path, Headers{make_basic_authentication_header("hello", "world")});
  2710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2711. auto body = remove_whitespace(res->body);
  2712. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2713. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2714. EXPECT_EQ(StatusCode::OK_200, res->status);
  2715. }
  2716. {
  2717. cli.set_basic_auth("hello", "world");
  2718. auto res = cli.Get(path);
  2719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2720. auto body = remove_whitespace(res->body);
  2721. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2722. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2723. EXPECT_EQ(StatusCode::OK_200, res->status);
  2724. }
  2725. {
  2726. cli.set_basic_auth("hello", "bad");
  2727. auto res = cli.Get(path);
  2728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2729. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2730. }
  2731. {
  2732. cli.set_basic_auth("bad", "world");
  2733. auto res = cli.Get(path);
  2734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2735. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2736. }
  2737. }
  2738. #ifdef CPPHTTPLIB_SSL_ENABLED
  2739. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2740. auto host = "httpbingo.org";
  2741. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2742. auto paths = std::vector<std::string>{
  2743. "/digest-auth/auth/hello/world/MD5",
  2744. "/digest-auth/auth/hello/world/SHA-256",
  2745. };
  2746. auto port = 443;
  2747. SSLClient cli(host, port);
  2748. {
  2749. auto res = cli.Get(unauth_path);
  2750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2751. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2752. }
  2753. {
  2754. cli.set_digest_auth("hello", "world");
  2755. for (const auto &path : paths) {
  2756. auto res = cli.Get(path.c_str());
  2757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2758. auto body = remove_whitespace(res->body);
  2759. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2760. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2761. EXPECT_EQ(StatusCode::OK_200, res->status);
  2762. }
  2763. cli.set_digest_auth("hello", "bad");
  2764. for (const auto &path : paths) {
  2765. auto res = cli.Get(path.c_str());
  2766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2767. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2768. }
  2769. }
  2770. }
  2771. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2772. // comma-separated list of challenges, and each challenge may itself carry a
  2773. // comma-separated auth-param list, so a server can legally offer Basic
  2774. // before Digest, either as two field lines or packed into one. Runs one 401
  2775. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2776. // value() joins them in receipt order) and checks that the retry carries a
  2777. // well-formed Digest Authorization header naming expected_realm.
  2778. static void
  2779. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2780. const std::string &expected_realm) {
  2781. std::atomic<int> hits{0};
  2782. Server svr;
  2783. svr.Get("/x", [&](const Request &req, Response &res) {
  2784. if (++hits == 1) {
  2785. res.status = StatusCode::Unauthorized_401;
  2786. for (const auto &challenge : challenges) {
  2787. res.set_header("WWW-Authenticate", challenge);
  2788. }
  2789. } else {
  2790. auto authorization = req.get_header_value("Authorization");
  2791. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2792. EXPECT_NE(std::string::npos,
  2793. authorization.find("realm=\"" + expected_realm + "\""));
  2794. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2795. res.set_content("ok", "text/plain");
  2796. }
  2797. });
  2798. auto port = svr.bind_to_any_port(HOST);
  2799. std::thread t([&]() { svr.listen_after_bind(); });
  2800. auto se = detail::scope_exit([&] {
  2801. svr.stop();
  2802. t.join();
  2803. });
  2804. svr.wait_until_ready();
  2805. Client cli(HOST, port);
  2806. cli.set_digest_auth("hello", "world");
  2807. auto res = cli.Get("/x");
  2808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2809. EXPECT_EQ(2, hits.load());
  2810. }
  2811. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2812. static const char *kDigestChallenge =
  2813. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2814. "algorithm=MD5";
  2815. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2816. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2817. "testrealm");
  2818. }
  2819. // Same challenge list with the schemes in the opposite order, to make sure
  2820. // the fix above didn't just special-case "Basic first".
  2821. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2822. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2823. "testrealm");
  2824. }
  2825. // A comma inside a quoted auth-param value must not be mistaken for the
  2826. // separator between two challenges (or two auth-params).
  2827. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2828. run_digest_challenge_list_test(
  2829. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2830. "algorithm=MD5"},
  2831. "test,realm");
  2832. }
  2833. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2834. // make_digest_authentication_header() dereferences both unconditionally, so
  2835. // a server sending a challenge missing either one must not be treated as
  2836. // usable -- doing so used to crash the client with std::out_of_range.
  2837. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2838. Server svr;
  2839. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2840. res.status = StatusCode::Unauthorized_401;
  2841. res.set_header("WWW-Authenticate", challenge);
  2842. });
  2843. auto port = svr.bind_to_any_port(HOST);
  2844. std::thread t([&]() { svr.listen_after_bind(); });
  2845. auto se = detail::scope_exit([&] {
  2846. svr.stop();
  2847. t.join();
  2848. });
  2849. svr.wait_until_ready();
  2850. Client cli(HOST, port);
  2851. cli.set_digest_auth("hello", "world");
  2852. auto res = cli.Get("/x");
  2853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2854. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2855. }
  2856. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2857. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2858. }
  2859. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2860. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2861. }
  2862. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2863. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2864. }
  2865. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2866. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2867. // when storing the values, so the header builder has to re-escape them (and
  2868. // keep algorithm a bare token); otherwise the value breaks out of its
  2869. // quoted-string and injects extra auth-params into the client's Authorization.
  2870. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2871. std::atomic<int> hits{0};
  2872. std::string authorization;
  2873. Server svr;
  2874. svr.Get("/x", [&](const Request &req, Response &res) {
  2875. if (++hits == 1) {
  2876. res.status = StatusCode::Unauthorized_401;
  2877. // On the wire the quotes embedded in the values are backslash-escaped.
  2878. res.set_header("WWW-Authenticate",
  2879. "Digest realm=\"testrealm\", "
  2880. "nonce=\"n\\\"; injected=\\\"x\", "
  2881. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2882. } else {
  2883. authorization = req.get_header_value("Authorization");
  2884. res.set_content("ok", "text/plain");
  2885. }
  2886. });
  2887. auto port = svr.bind_to_any_port(HOST);
  2888. std::thread t([&]() { svr.listen_after_bind(); });
  2889. auto se = detail::scope_exit([&] {
  2890. svr.stop();
  2891. t.join();
  2892. });
  2893. svr.wait_until_ready();
  2894. Client cli(HOST, port);
  2895. cli.set_digest_auth("hello", "world");
  2896. auto res = cli.Get("/x");
  2897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2898. EXPECT_EQ(2, hits.load());
  2899. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2900. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  2901. // inside its quoted-string rather than starting an "injected" auth-param.
  2902. EXPECT_NE(std::string::npos,
  2903. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  2904. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  2905. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  2906. }
  2907. #endif
  2908. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2909. auto host = "google.com";
  2910. auto another_host = "example.com";
  2911. auto wrong_ip = "0.0.0.0";
  2912. #ifdef CPPHTTPLIB_SSL_ENABLED
  2913. SSLClient cli(host);
  2914. #else
  2915. Client cli(host);
  2916. #endif
  2917. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2918. auto res = cli.Get("/");
  2919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2920. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2921. }
  2922. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2923. auto host = "google.com";
  2924. auto wrong_ip = "0.0.0.0";
  2925. #ifdef CPPHTTPLIB_SSL_ENABLED
  2926. SSLClient cli(host);
  2927. #else
  2928. Client cli(host);
  2929. #endif
  2930. cli.set_hostname_addr_map({{host, wrong_ip}});
  2931. auto res = cli.Get("/");
  2932. ASSERT_TRUE(!res);
  2933. EXPECT_EQ(Error::Connection, res.error());
  2934. }
  2935. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2936. // A mapped value that is not an IP literal must be resolved. "localhost"
  2937. // resolves from the hosts file, so this test needs no external DNS.
  2938. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2939. auto host = "target.invalid";
  2940. Server svr;
  2941. std::string received_host;
  2942. svr.Get("/hi", [&](const Request &req, Response &res) {
  2943. received_host = req.get_header_value("Host");
  2944. res.set_content("Hello World!", "text/plain");
  2945. });
  2946. auto port = svr.bind_to_any_port(HOST);
  2947. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2948. auto se = detail::scope_exit([&] {
  2949. svr.stop();
  2950. thread.join();
  2951. ASSERT_FALSE(svr.is_running());
  2952. });
  2953. svr.wait_until_ready();
  2954. Client cli(host, port);
  2955. cli.set_hostname_addr_map({{host, HOST}});
  2956. auto res = cli.Get("/hi");
  2957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2958. EXPECT_EQ(StatusCode::OK_200, res->status);
  2959. // The mapping only redirects the connection; the identity stays host_.
  2960. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2961. }
  2962. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2963. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2964. auto host = "target.invalid";
  2965. Server svr;
  2966. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2967. res.set_content("Hello World!", "text/plain");
  2968. });
  2969. auto port = svr.bind_to_any_port("127.0.0.1");
  2970. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2971. auto se = detail::scope_exit([&] {
  2972. svr.stop();
  2973. thread.join();
  2974. ASSERT_FALSE(svr.is_running());
  2975. });
  2976. svr.wait_until_ready();
  2977. Client cli(host, port);
  2978. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2979. auto res = cli.Get("/hi");
  2980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2981. EXPECT_EQ(StatusCode::OK_200, res->status);
  2982. }
  2983. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2984. // An empty mapped value must leave host_ as the connection target. Without
  2985. // that guard the empty value would become the host argument, getaddrinfo
  2986. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2987. // loopback - silently connecting somewhere the caller never asked for.
  2988. // The server listens on loopback, so such a fallback would succeed and is
  2989. // therefore observable as a failure of this test.
  2990. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2991. Server svr;
  2992. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2993. res.set_content("Hello World!", "text/plain");
  2994. });
  2995. auto port = svr.bind_to_any_port(HOST);
  2996. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2997. auto se = detail::scope_exit([&] {
  2998. svr.stop();
  2999. thread.join();
  3000. ASSERT_FALSE(svr.is_running());
  3001. });
  3002. svr.wait_until_ready();
  3003. Client cli(blackhole, port);
  3004. cli.set_hostname_addr_map({{blackhole, ""}});
  3005. cli.set_connection_timeout(1);
  3006. auto res = cli.Get("/hi");
  3007. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3008. }
  3009. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3010. auto host = "httpbingo.org";
  3011. auto path = std::string{"/absolute-redirect/3"};
  3012. #ifdef CPPHTTPLIB_SSL_ENABLED
  3013. SSLClient cli(host);
  3014. #else
  3015. Client cli(host);
  3016. #endif
  3017. cli.set_follow_location(true);
  3018. auto res = cli.Get(path);
  3019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3020. EXPECT_EQ(StatusCode::OK_200, res->status);
  3021. }
  3022. TEST(RedirectTest, Redirect_Online) {
  3023. auto host = "httpbingo.org";
  3024. auto path = std::string{"/redirect/3"};
  3025. #ifdef CPPHTTPLIB_SSL_ENABLED
  3026. SSLClient cli(host);
  3027. #else
  3028. Client cli(host);
  3029. #endif
  3030. cli.set_follow_location(true);
  3031. auto res = cli.Get(path);
  3032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3033. EXPECT_EQ(StatusCode::OK_200, res->status);
  3034. }
  3035. TEST(RelativeRedirectTest, Redirect_Online) {
  3036. auto host = "httpbingo.org";
  3037. auto path = std::string{"/relative-redirect/3"};
  3038. #ifdef CPPHTTPLIB_SSL_ENABLED
  3039. SSLClient cli(host);
  3040. #else
  3041. Client cli(host);
  3042. #endif
  3043. cli.set_follow_location(true);
  3044. auto res = cli.Get(path);
  3045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3046. EXPECT_EQ(StatusCode::OK_200, res->status);
  3047. }
  3048. TEST(TooManyRedirectTest, Redirect_Online) {
  3049. auto host = "httpbingo.org";
  3050. auto path = std::string{"/redirect/21"};
  3051. #ifdef CPPHTTPLIB_SSL_ENABLED
  3052. SSLClient cli(host);
  3053. #else
  3054. Client cli(host);
  3055. #endif
  3056. cli.set_follow_location(true);
  3057. auto res = cli.Get(path);
  3058. ASSERT_TRUE(!res);
  3059. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3060. }
  3061. #ifdef CPPHTTPLIB_SSL_ENABLED
  3062. TEST(YahooRedirectTest, Redirect_Online) {
  3063. Client cli("yahoo.com");
  3064. auto res = cli.Get("/");
  3065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3066. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3067. cli.set_follow_location(true);
  3068. res = cli.Get("/");
  3069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3070. EXPECT_EQ(StatusCode::OK_200, res->status);
  3071. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3072. }
  3073. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3074. #define REDIR_HOST "httpbingo.org"
  3075. #define REDIR_PATH "/redirect-to"
  3076. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3077. SSLClient cli(REDIR_HOST);
  3078. cli.set_follow_location(true);
  3079. auto res =
  3080. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3082. EXPECT_EQ(StatusCode::OK_200, res->status);
  3083. }
  3084. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3085. SSLClient cli(REDIR_HOST);
  3086. cli.set_follow_location(true);
  3087. Params params;
  3088. params.emplace("url", "http://example.com");
  3089. params.emplace("status_code", "302");
  3090. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3092. EXPECT_EQ(StatusCode::OK_200, res->status);
  3093. }
  3094. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3095. SSLClient cli(REDIR_HOST);
  3096. cli.set_follow_location(true);
  3097. Params params;
  3098. params.emplace("url", "http://example.com");
  3099. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3101. EXPECT_EQ(StatusCode::OK_200, res->status);
  3102. }
  3103. TEST(UrlWithSpace, Redirect_Online) {
  3104. SSLClient cli("edge.forgecdn.net");
  3105. cli.set_follow_location(true);
  3106. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3108. EXPECT_EQ(StatusCode::OK_200, res->status);
  3109. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3110. }
  3111. #endif
  3112. #if !defined(_WIN32) && !defined(_WIN64)
  3113. TEST(ReceiveSignals, Signal) {
  3114. auto setupSignalHandlers = []() {
  3115. struct sigaction act;
  3116. sigemptyset(&act.sa_mask);
  3117. act.sa_flags = SA_SIGINFO;
  3118. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3119. switch (sig) {
  3120. case SIGINT:
  3121. default: break;
  3122. }
  3123. };
  3124. ::sigaction(SIGINT, &act, nullptr);
  3125. };
  3126. Server svr;
  3127. int port = 0;
  3128. auto thread = std::thread([&]() {
  3129. setupSignalHandlers();
  3130. port = svr.bind_to_any_port(HOST);
  3131. svr.listen_after_bind();
  3132. });
  3133. auto se = detail::scope_exit([&] {
  3134. svr.stop();
  3135. thread.join();
  3136. ASSERT_FALSE(svr.is_running());
  3137. });
  3138. svr.wait_until_ready();
  3139. ASSERT_TRUE(svr.is_running());
  3140. pthread_kill(thread.native_handle(), SIGINT);
  3141. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3142. ASSERT_TRUE(svr.is_running());
  3143. }
  3144. #endif
  3145. TEST(RedirectToDifferentPort, Redirect) {
  3146. Server svr1;
  3147. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3148. res.set_content("Hello World!", "text/plain");
  3149. });
  3150. int svr1_port = 0;
  3151. auto thread1 = std::thread([&]() {
  3152. svr1_port = svr1.bind_to_any_port(HOST);
  3153. svr1.listen_after_bind();
  3154. });
  3155. Server svr2;
  3156. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3157. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3158. });
  3159. int svr2_port = 0;
  3160. auto thread2 = std::thread([&]() {
  3161. svr2_port = svr2.bind_to_any_port(HOST);
  3162. svr2.listen_after_bind();
  3163. });
  3164. auto se = detail::scope_exit([&] {
  3165. svr2.stop();
  3166. thread2.join();
  3167. svr1.stop();
  3168. thread1.join();
  3169. ASSERT_FALSE(svr2.is_running());
  3170. ASSERT_FALSE(svr1.is_running());
  3171. });
  3172. svr1.wait_until_ready();
  3173. svr2.wait_until_ready();
  3174. Client cli("localhost", svr2_port);
  3175. cli.set_follow_location(true);
  3176. auto res = cli.Get("/2");
  3177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3178. EXPECT_EQ(StatusCode::OK_200, res->status);
  3179. EXPECT_EQ("Hello World!", res->body);
  3180. }
  3181. // GET /redir on one server redirects to /target on another port, so the
  3182. // client follows it with a new client.
  3183. static Result
  3184. GetThroughRedirectToDifferentPort(Server::Handler target,
  3185. const std::function<void(Client &)> &setup,
  3186. const Headers &headers = Headers()) {
  3187. Server target_svr;
  3188. target_svr.Get("/target", target);
  3189. int target_port = 0;
  3190. auto target_thread = std::thread([&]() {
  3191. target_port = target_svr.bind_to_any_port(HOST);
  3192. target_svr.listen_after_bind();
  3193. });
  3194. Server origin_svr;
  3195. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3196. res.set_redirect(
  3197. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3198. });
  3199. int origin_port = 0;
  3200. auto origin_thread = std::thread([&]() {
  3201. origin_port = origin_svr.bind_to_any_port(HOST);
  3202. origin_svr.listen_after_bind();
  3203. });
  3204. auto se = detail::scope_exit([&] {
  3205. origin_svr.stop();
  3206. origin_thread.join();
  3207. target_svr.stop();
  3208. target_thread.join();
  3209. });
  3210. target_svr.wait_until_ready();
  3211. origin_svr.wait_until_ready();
  3212. Client cli("localhost", origin_port);
  3213. cli.set_follow_location(true);
  3214. setup(cli);
  3215. return cli.Get("/redir", headers);
  3216. }
  3217. static void
  3218. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3219. std::string captured_authorization;
  3220. auto result = GetThroughRedirectToDifferentPort(
  3221. [&](const Request &req, Response &res) {
  3222. captured_authorization = req.get_header_value("Authorization");
  3223. res.set_content("OK", "text/plain");
  3224. },
  3225. set_auth);
  3226. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3227. EXPECT_EQ(StatusCode::OK_200, result->status);
  3228. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3229. EXPECT_TRUE(captured_authorization.empty());
  3230. }
  3231. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3232. TestDoNotForwardCredentialsOnRedirect(
  3233. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3234. }
  3235. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3236. TestDoNotForwardCredentialsOnRedirect(
  3237. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3238. }
  3239. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3240. std::string captured_cookie;
  3241. auto result = GetThroughRedirectToDifferentPort(
  3242. [&](const Request &req, Response &res) {
  3243. captured_cookie = req.get_header_value("Cookie");
  3244. res.set_content("OK", "text/plain");
  3245. },
  3246. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3247. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3248. EXPECT_EQ(StatusCode::OK_200, result->status);
  3249. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3250. EXPECT_TRUE(captured_cookie.empty());
  3251. }
  3252. TEST(RedirectToSamePort, ForwardCookie) {
  3253. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3254. // header so that ordinary session flows keep working.
  3255. Server svr;
  3256. std::string captured_cookie;
  3257. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3258. res.set_redirect("/target", 302);
  3259. });
  3260. svr.Get("/target", [&](const Request &req, Response &res) {
  3261. captured_cookie = req.get_header_value("Cookie");
  3262. res.set_content("OK", "text/plain");
  3263. });
  3264. auto port = svr.bind_to_any_port(HOST);
  3265. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3266. auto se = detail::scope_exit([&] {
  3267. svr.stop();
  3268. thread.join();
  3269. ASSERT_FALSE(svr.is_running());
  3270. });
  3271. svr.wait_until_ready();
  3272. Client cli(HOST, port);
  3273. cli.set_follow_location(true);
  3274. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3275. auto res = cli.Get("/redir", headers);
  3276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3277. EXPECT_EQ(StatusCode::OK_200, res->status);
  3278. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3279. }
  3280. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3281. std::string authorization;
  3282. std::string trace_id;
  3283. auto result = GetThroughRedirectToDifferentPort(
  3284. [&](const Request &req, Response &res) {
  3285. authorization = req.get_header_value("Authorization");
  3286. trace_id = req.get_header_value("X-Trace-Id");
  3287. res.set_content("OK", "text/plain");
  3288. },
  3289. [](Client &cli) {
  3290. cli.set_default_headers(
  3291. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3292. });
  3293. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3294. EXPECT_EQ(StatusCode::OK_200, result->status);
  3295. // Like a header given with the request, a default one goes along unless it
  3296. // carries credentials (RFC 9110 15.4).
  3297. EXPECT_TRUE(authorization.empty());
  3298. EXPECT_EQ("42", trace_id);
  3299. }
  3300. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3301. auto result = GetThroughRedirectToDifferentPort(
  3302. [](const Request &, Response &res) {
  3303. res.set_content(std::string(2048, 'x'), "text/plain");
  3304. },
  3305. [](Client &cli) { cli.set_payload_max_length(1024); });
  3306. EXPECT_FALSE(result);
  3307. }
  3308. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3309. auto result = GetThroughRedirectToDifferentPort(
  3310. [](const Request &req, Response &res) {
  3311. // Answer after a second, or once the client gives up.
  3312. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3313. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3314. }
  3315. res.set_content("late", "text/plain");
  3316. },
  3317. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3318. ASSERT_FALSE(result);
  3319. EXPECT_EQ(Error::Read, result.error());
  3320. }
  3321. #ifdef CPPHTTPLIB_SSL_ENABLED
  3322. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3323. auto result = GetThroughRedirectToDifferentPort(
  3324. [](const Request &, Response &res) {
  3325. res.status = StatusCode::Unauthorized_401;
  3326. res.set_header("WWW-Authenticate",
  3327. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3328. },
  3329. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3330. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3331. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3332. }
  3333. #endif
  3334. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3335. Server svr;
  3336. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3337. // Port number that overflows int — should not crash
  3338. res.set_redirect("http://localhost:99999999999999999999/target");
  3339. });
  3340. auto port = svr.bind_to_any_port(HOST);
  3341. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3342. auto se = detail::scope_exit([&] {
  3343. svr.stop();
  3344. thread.join();
  3345. ASSERT_FALSE(svr.is_running());
  3346. });
  3347. svr.wait_until_ready();
  3348. Client cli(HOST, port);
  3349. cli.set_follow_location(true);
  3350. auto res = cli.Get("/redir");
  3351. // Should fail gracefully, not crash (no valid response due to bad port)
  3352. EXPECT_FALSE(res);
  3353. }
  3354. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3355. Server svr;
  3356. auto port = svr.bind_to_any_port(HOST);
  3357. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3358. // The server's own port followed by junk must not be followed
  3359. res.set_redirect("http://" + std::string(HOST) + ":" +
  3360. std::to_string(port) + "junk/target");
  3361. });
  3362. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3363. res.set_content("target", "text/plain");
  3364. });
  3365. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3366. auto se = detail::scope_exit([&] {
  3367. svr.stop();
  3368. thread.join();
  3369. ASSERT_FALSE(svr.is_running());
  3370. });
  3371. svr.wait_until_ready();
  3372. Client cli(HOST, port);
  3373. cli.set_follow_location(true);
  3374. auto res = cli.Get("/redir");
  3375. EXPECT_FALSE(res);
  3376. }
  3377. TEST(RedirectFromPageWithContent, Redirect) {
  3378. Server svr;
  3379. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3380. res.set_content("___", "text/plain");
  3381. res.set_redirect("/2");
  3382. });
  3383. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3384. res.set_content("Hello World!", "text/plain");
  3385. });
  3386. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3387. auto se = detail::scope_exit([&] {
  3388. svr.stop();
  3389. th.join();
  3390. ASSERT_FALSE(svr.is_running());
  3391. });
  3392. svr.wait_until_ready();
  3393. {
  3394. Client cli("localhost", PORT);
  3395. cli.set_follow_location(true);
  3396. std::string body;
  3397. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3398. body.append(data, data_length);
  3399. return true;
  3400. });
  3401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3402. EXPECT_EQ(StatusCode::OK_200, res->status);
  3403. EXPECT_EQ("Hello World!", body);
  3404. }
  3405. {
  3406. Client cli("localhost", PORT);
  3407. std::string body;
  3408. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3409. body.append(data, data_length);
  3410. return true;
  3411. });
  3412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3413. EXPECT_EQ(StatusCode::Found_302, res->status);
  3414. EXPECT_EQ("___", body);
  3415. }
  3416. }
  3417. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3418. Server svr;
  3419. auto port_str = std::to_string(PORT);
  3420. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3421. auto expected_host = "[::1]:" + port_str;
  3422. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3423. res.set_content("___", "text/plain");
  3424. // res.set_redirect("/2");
  3425. res.set_redirect(redirect_url);
  3426. });
  3427. svr.Get("/2", [&](const Request &req, Response &res) {
  3428. auto host_header = req.headers.find("Host");
  3429. ASSERT_TRUE(host_header != req.headers.end());
  3430. EXPECT_EQ(expected_host, host_header->second);
  3431. res.set_content("Hello World!", "text/plain");
  3432. });
  3433. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3434. auto se = detail::scope_exit([&] {
  3435. svr.stop();
  3436. th.join();
  3437. ASSERT_FALSE(svr.is_running());
  3438. });
  3439. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3440. // actually starts anything, so the condition !svr.is_running() will
  3441. // always remain true, and the loop never stops.
  3442. // This basically counts how many milliseconds have passed since the
  3443. // call to svr.listen(), and if after 5 seconds nothing started yet
  3444. // aborts the test.
  3445. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3446. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3447. ASSERT_LT(milliseconds, 5000U);
  3448. }
  3449. {
  3450. Client cli("::1", PORT);
  3451. cli.set_follow_location(true);
  3452. std::string body;
  3453. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3454. body.append(data, data_length);
  3455. return true;
  3456. });
  3457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3458. EXPECT_EQ(StatusCode::OK_200, res->status);
  3459. EXPECT_EQ("Hello World!", body);
  3460. }
  3461. {
  3462. Client cli("::1", PORT);
  3463. std::string body;
  3464. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3465. body.append(data, data_length);
  3466. return true;
  3467. });
  3468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3469. EXPECT_EQ(StatusCode::Found_302, res->status);
  3470. EXPECT_EQ("___", body);
  3471. }
  3472. }
  3473. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3474. Server svr;
  3475. svr.Get("/foo", [](const Request &req, Response &res) {
  3476. auto a = req.params.find("a");
  3477. if (a != req.params.end()) {
  3478. res.set_content((*a).second, "text/plain");
  3479. res.status = StatusCode::OK_200;
  3480. } else {
  3481. res.status = StatusCode::BadRequest_400;
  3482. }
  3483. });
  3484. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3485. auto se = detail::scope_exit([&] {
  3486. svr.stop();
  3487. thread.join();
  3488. ASSERT_FALSE(svr.is_running());
  3489. });
  3490. svr.wait_until_ready();
  3491. {
  3492. Client cli(HOST, PORT);
  3493. cli.set_path_encode(false);
  3494. auto res = cli.Get("/foo?a=explicitly+encoded");
  3495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3496. EXPECT_EQ(StatusCode::OK_200, res->status);
  3497. // This expects it back with a space, as the `+` won't have been
  3498. // url-encoded, and server-side the params get decoded turning `+`
  3499. // into spaces.
  3500. EXPECT_EQ("explicitly encoded", res->body);
  3501. }
  3502. }
  3503. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3504. // When path encoding is disabled the client must transmit the supplied
  3505. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3506. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3507. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3508. // than a space (0x20). Assert on the raw wire target to catch this.
  3509. Server svr;
  3510. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3511. svr.Get("/foo", [&](const Request &req, Response &res) {
  3512. EXPECT_EQ(expected_target, req.target);
  3513. res.status = StatusCode::OK_200;
  3514. });
  3515. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3516. auto se = detail::scope_exit([&] {
  3517. svr.stop();
  3518. thread.join();
  3519. ASSERT_FALSE(svr.is_running());
  3520. });
  3521. svr.wait_until_ready();
  3522. {
  3523. Client cli(HOST, PORT);
  3524. cli.set_path_encode(false);
  3525. auto res = cli.Get(expected_target.c_str());
  3526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3527. EXPECT_EQ(StatusCode::OK_200, res->status);
  3528. }
  3529. }
  3530. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3531. // `open_stream()` used to skip the path encoding that the buffered send
  3532. // path applies, so the same `path` produced different bytes in the request
  3533. // line depending on which API was used. Assert the two agree.
  3534. Server svr;
  3535. std::string target;
  3536. svr.Get(".*", [&](const Request &req, Response &res) {
  3537. target = req.target;
  3538. res.status = StatusCode::OK_200;
  3539. });
  3540. auto port = svr.bind_to_any_port(HOST);
  3541. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3542. auto se = detail::scope_exit([&] {
  3543. svr.stop();
  3544. thread.join();
  3545. ASSERT_FALSE(svr.is_running());
  3546. });
  3547. svr.wait_until_ready();
  3548. struct {
  3549. const char *path;
  3550. const char *expected;
  3551. } cases[] = {
  3552. {"/a b?x=1", "/a%20b?x=1"},
  3553. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3554. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3555. };
  3556. for (const auto &c : cases) {
  3557. Client cli(HOST, port);
  3558. target.clear();
  3559. auto res = cli.Get(c.path);
  3560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3561. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3562. auto buffered_target = target;
  3563. target.clear();
  3564. auto handle = cli.open_stream("GET", c.path);
  3565. EXPECT_TRUE(handle.is_valid())
  3566. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3567. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3568. }
  3569. }
  3570. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3571. // The `set_path_encode(false)` contract — transmit the supplied target
  3572. // verbatim — must hold for the streaming API too.
  3573. Server svr;
  3574. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3575. std::string target;
  3576. svr.Get("/foo", [&](const Request &req, Response &res) {
  3577. target = req.target;
  3578. res.status = StatusCode::OK_200;
  3579. });
  3580. auto port = svr.bind_to_any_port(HOST);
  3581. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3582. auto se = detail::scope_exit([&] {
  3583. svr.stop();
  3584. thread.join();
  3585. ASSERT_FALSE(svr.is_running());
  3586. });
  3587. svr.wait_until_ready();
  3588. {
  3589. Client cli(HOST, port);
  3590. cli.set_path_encode(false);
  3591. auto handle = cli.open_stream("GET", expected_target);
  3592. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3593. EXPECT_EQ(expected_target, target);
  3594. }
  3595. }
  3596. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3597. // With path encoding enabled a CR/LF in the target is percent-encoded
  3598. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3599. // write_request_line still backstops `set_path_encode(false)`, which is
  3600. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3601. Server svr;
  3602. // Captured before routing: the decoded path contains a newline, which a
  3603. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3604. std::string target;
  3605. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3606. target = req.target;
  3607. res.status = StatusCode::OK_200;
  3608. return Server::HandlerResponse::Handled;
  3609. });
  3610. auto port = svr.bind_to_any_port(HOST);
  3611. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3612. auto se = detail::scope_exit([&] {
  3613. svr.stop();
  3614. thread.join();
  3615. ASSERT_FALSE(svr.is_running());
  3616. });
  3617. svr.wait_until_ready();
  3618. {
  3619. Client cli(HOST, port);
  3620. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3621. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3622. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3623. }
  3624. }
  3625. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3626. // Every control character is percent-encoded, not just CR/LF, so the target
  3627. // passes the request-target check in write_request_line.
  3628. Server svr;
  3629. std::string target;
  3630. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3631. target = req.target;
  3632. res.status = StatusCode::OK_200;
  3633. return Server::HandlerResponse::Handled;
  3634. });
  3635. auto port = svr.bind_to_any_port(HOST);
  3636. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3637. auto se = detail::scope_exit([&] {
  3638. svr.stop();
  3639. thread.join();
  3640. ASSERT_FALSE(svr.is_running());
  3641. });
  3642. svr.wait_until_ready();
  3643. {
  3644. Client cli(HOST, port);
  3645. auto res = cli.Get("/a\tb\x1b\x7f");
  3646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3647. EXPECT_EQ("/a%09b%1B%7F", target);
  3648. }
  3649. }
  3650. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3651. // Nothing may reach the wire: a raw CR/LF target would split the request
  3652. // line and inject headers.
  3653. Server svr;
  3654. // Pre-routing so that "not called" means nothing reached the server at all,
  3655. // rather than merely failing to match a handler pattern.
  3656. auto handler_called = false;
  3657. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3658. handler_called = true;
  3659. res.status = StatusCode::OK_200;
  3660. return Server::HandlerResponse::Handled;
  3661. });
  3662. auto port = svr.bind_to_any_port(HOST);
  3663. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3664. auto se = detail::scope_exit([&] {
  3665. svr.stop();
  3666. thread.join();
  3667. ASSERT_FALSE(svr.is_running());
  3668. });
  3669. svr.wait_until_ready();
  3670. {
  3671. Client cli(HOST, port);
  3672. cli.set_path_encode(false);
  3673. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3674. EXPECT_FALSE(handle.is_valid());
  3675. EXPECT_EQ(Error::Write, handle.error);
  3676. EXPECT_FALSE(handler_called);
  3677. }
  3678. }
  3679. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3680. // Which of the two branches runs is decided by whether the query component
  3681. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3682. // an empty query and must still fall back to building one from
  3683. // `req.params`, while a non-empty query must win over `req.params`.
  3684. Server svr;
  3685. std::string target;
  3686. svr.Get("/foo", [&](const Request &req, Response &res) {
  3687. target = req.target;
  3688. res.status = StatusCode::OK_200;
  3689. });
  3690. auto port = svr.bind_to_any_port(HOST);
  3691. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3692. auto se = detail::scope_exit([&] {
  3693. svr.stop();
  3694. thread.join();
  3695. ASSERT_FALSE(svr.is_running());
  3696. });
  3697. svr.wait_until_ready();
  3698. {
  3699. // Trailing `?` -> empty query component -> `req.params` is used.
  3700. Client cli(HOST, port);
  3701. Request req;
  3702. req.method = "GET";
  3703. req.path = "/foo?";
  3704. req.params.emplace("a", "1");
  3705. target.clear();
  3706. auto res = cli.send(req);
  3707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3708. EXPECT_EQ("/foo?a=1", target);
  3709. }
  3710. {
  3711. // Non-empty query in `req.path` -> `req.params` is not appended.
  3712. Client cli(HOST, port);
  3713. Request req;
  3714. req.method = "GET";
  3715. req.path = "/foo?b=2";
  3716. req.params.emplace("a", "1");
  3717. target.clear();
  3718. auto res = cli.send(req);
  3719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3720. EXPECT_EQ("/foo?b=2", target);
  3721. }
  3722. }
  3723. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3724. Server svr;
  3725. svr.Get("/", [](const Request &req, Response &) {
  3726. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3727. });
  3728. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  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. Client cli(HOST, PORT);
  3737. cli.set_path_encode(false);
  3738. auto res = cli.Get("/?something=%0A");
  3739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3740. EXPECT_EQ(StatusCode::OK_200, res->status);
  3741. }
  3742. }
  3743. TEST(BindServerTest, BindDualStack) {
  3744. Server svr;
  3745. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3746. res.set_content("Hello World!", "text/plain");
  3747. });
  3748. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3749. auto se = detail::scope_exit([&] {
  3750. svr.stop();
  3751. thread.join();
  3752. ASSERT_FALSE(svr.is_running());
  3753. });
  3754. svr.wait_until_ready();
  3755. {
  3756. Client cli("127.0.0.1", PORT);
  3757. auto res = cli.Get("/1");
  3758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3759. EXPECT_EQ(StatusCode::OK_200, res->status);
  3760. EXPECT_EQ("Hello World!", res->body);
  3761. }
  3762. {
  3763. Client cli("::1", PORT);
  3764. auto res = cli.Get("/1");
  3765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3766. EXPECT_EQ(StatusCode::OK_200, res->status);
  3767. EXPECT_EQ("Hello World!", res->body);
  3768. }
  3769. }
  3770. TEST(BindServerTest, BindAndListenSeparately) {
  3771. Server svr;
  3772. int port = svr.bind_to_any_port("0.0.0.0");
  3773. ASSERT_TRUE(svr.is_valid());
  3774. ASSERT_TRUE(port > 0);
  3775. svr.stop();
  3776. }
  3777. // Reports whether anything is still listening on a loopback port. A plain
  3778. // connect() is used instead of a Client request because a socket left bound by
  3779. // mistake accepts the connection into its backlog and never answers, which
  3780. // would hang the test instead of failing it.
  3781. static bool is_loopback_port_accepting(int port) {
  3782. sockaddr_in addr{};
  3783. addr.sin_family = AF_INET;
  3784. addr.sin_port = htons(static_cast<uint16_t>(port));
  3785. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3786. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3787. EXPECT_NE(sock, INVALID_SOCKET);
  3788. if (sock == INVALID_SOCKET) { return false; }
  3789. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3790. static_cast<socklen_t>(sizeof(addr)));
  3791. detail::close_socket(sock);
  3792. return ret == 0;
  3793. }
  3794. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3795. Server svr;
  3796. auto port = svr.bind_to_any_port("127.0.0.1");
  3797. ASSERT_TRUE(port > 0);
  3798. svr.stop();
  3799. // bind_to_any_port() already called listen(2), so until stop() closed the
  3800. // descriptor the port kept accepting connections into the backlog. ASSERT
  3801. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3802. // below blocks forever in the accept loop.
  3803. ASSERT_FALSE(is_loopback_port_accepting(port));
  3804. // Nothing is left to accept on, so listen_after_bind() must report failure
  3805. // instead of returning success without ever serving.
  3806. EXPECT_FALSE(svr.listen_after_bind());
  3807. // The failed listen marks the server decommissioned, so a waiter returns
  3808. // instead of spinning forever.
  3809. svr.wait_until_ready();
  3810. }
  3811. #ifdef CPPHTTPLIB_SSL_ENABLED
  3812. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3813. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3814. CLIENT_CA_CERT_DIR);
  3815. int port = svr.bind_to_any_port("0.0.0.0");
  3816. ASSERT_TRUE(svr.is_valid());
  3817. ASSERT_TRUE(port > 0);
  3818. svr.stop();
  3819. }
  3820. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3821. // or a rejected CustomRoute() registration would not stop the server binding.
  3822. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3823. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3824. CLIENT_CA_CERT_DIR);
  3825. ASSERT_TRUE(svr.is_valid());
  3826. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3827. EXPECT_FALSE(svr.is_valid());
  3828. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3829. }
  3830. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3831. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3832. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3833. int port = svr.bind_to_any_port("0.0.0.0");
  3834. ASSERT_TRUE(svr.is_valid());
  3835. ASSERT_TRUE(port > 0);
  3836. svr.stop();
  3837. }
  3838. TEST(BindServerTest, UpdateCertsPem) {
  3839. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3840. int port = svr.bind_to_any_port("0.0.0.0");
  3841. ASSERT_TRUE(svr.is_valid());
  3842. ASSERT_TRUE(port > 0);
  3843. // Read PEM files
  3844. std::string cert_pem, key_pem, ca_pem;
  3845. read_file(SERVER_CERT_FILE, cert_pem);
  3846. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3847. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3848. // Update server certificates using PEM API
  3849. ASSERT_TRUE(
  3850. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3851. ASSERT_TRUE(svr.is_valid());
  3852. svr.stop();
  3853. }
  3854. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3855. // Start server with client CA (enables client auth)
  3856. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3857. ASSERT_TRUE(svr.is_valid());
  3858. bool handler_called = false;
  3859. svr.Get("/test", [&](const Request &req, Response &res) {
  3860. handler_called = true;
  3861. // Verify client certificate is present
  3862. auto cert = req.peer_cert();
  3863. EXPECT_TRUE(static_cast<bool>(cert));
  3864. res.set_content("ok", "text/plain");
  3865. });
  3866. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3867. auto se = detail::scope_exit([&] {
  3868. svr.stop();
  3869. t.join();
  3870. ASSERT_FALSE(svr.is_running());
  3871. });
  3872. svr.wait_until_ready();
  3873. // Read PEM files
  3874. std::string cert_pem, key_pem, ca_pem;
  3875. read_file(SERVER_CERT_FILE, cert_pem);
  3876. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3877. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3878. // Update server certificates and client CA using PEM API while server running
  3879. ASSERT_TRUE(
  3880. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3881. // Connect with client certificate
  3882. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3883. cli.enable_server_certificate_verification(false);
  3884. cli.set_connection_timeout(30);
  3885. auto res = cli.Get("/test");
  3886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3887. ASSERT_EQ(StatusCode::OK_200, res->status);
  3888. ASSERT_TRUE(handler_called);
  3889. EXPECT_EQ("ok", res->body);
  3890. }
  3891. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  3892. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3893. ASSERT_TRUE(svr.is_valid());
  3894. svr.Get("/test", [](const Request &, Response &res) {
  3895. res.set_content("ok", "text/plain");
  3896. });
  3897. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3898. auto se = detail::scope_exit([&] {
  3899. svr.stop();
  3900. t.join();
  3901. ASSERT_FALSE(svr.is_running());
  3902. });
  3903. svr.wait_until_ready();
  3904. // A connection that sends no ClientHello keeps its handshake in progress,
  3905. // once the server has had a moment to start it.
  3906. auto error = Error::Success;
  3907. auto sock = detail::create_client_socket(
  3908. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  3909. /*connection_timeout_sec=*/5, 0,
  3910. /*read_timeout_sec=*/5, 0,
  3911. /*write_timeout_sec=*/5, 0, std::string(), error);
  3912. ASSERT_NE(INVALID_SOCKET, sock);
  3913. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3914. std::string cert_pem, key_pem;
  3915. read_file(SERVER_CERT_FILE, cert_pem);
  3916. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3917. auto update = std::async(std::launch::async, [&]() {
  3918. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  3919. });
  3920. EXPECT_EQ(std::future_status::timeout,
  3921. update.wait_for(std::chrono::milliseconds(200)));
  3922. detail::close_socket(sock);
  3923. EXPECT_TRUE(update.get());
  3924. SSLClient cli(HOST, PORT);
  3925. cli.enable_server_certificate_verification(false);
  3926. auto res = cli.Get("/test");
  3927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3928. EXPECT_EQ(StatusCode::OK_200, res->status);
  3929. }
  3930. #endif
  3931. TEST(ErrorHandlerTest, ContentLength) {
  3932. Server svr;
  3933. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3934. res.status = StatusCode::OK_200;
  3935. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3936. "text/html"); // <= Content-Length still 13
  3937. });
  3938. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3939. res.set_content("Hello World!\n", "text/plain");
  3940. res.status = 524;
  3941. });
  3942. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3943. auto se = detail::scope_exit([&] {
  3944. svr.stop();
  3945. thread.join();
  3946. ASSERT_FALSE(svr.is_running());
  3947. });
  3948. svr.wait_until_ready();
  3949. {
  3950. Client cli(HOST, PORT);
  3951. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3953. EXPECT_EQ(StatusCode::OK_200, res->status);
  3954. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3955. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3956. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3957. }
  3958. }
  3959. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3960. TEST(ExceptionTest, WithoutExceptionHandler) {
  3961. Server svr;
  3962. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3963. throw std::runtime_error("exception...");
  3964. });
  3965. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3966. throw std::runtime_error("exception\r\n...");
  3967. });
  3968. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3969. auto se = detail::scope_exit([&] {
  3970. svr.stop();
  3971. listen_thread.join();
  3972. ASSERT_FALSE(svr.is_running());
  3973. });
  3974. svr.wait_until_ready();
  3975. Client cli("localhost", PORT);
  3976. {
  3977. auto res = cli.Get("/exception");
  3978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3979. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3980. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3981. }
  3982. {
  3983. auto res = cli.Get("/unknown");
  3984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3985. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3986. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3987. }
  3988. }
  3989. TEST(ExceptionTest, WithExceptionHandler) {
  3990. Server svr;
  3991. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3992. std::exception_ptr ep) {
  3993. EXPECT_FALSE(ep == nullptr);
  3994. try {
  3995. std::rethrow_exception(ep);
  3996. } catch (std::exception &e) {
  3997. EXPECT_EQ("abc", std::string(e.what()));
  3998. } catch (...) {}
  3999. res.status = StatusCode::InternalServerError_500;
  4000. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4001. "text/html"); // <= Content-Length still 13 at this point
  4002. });
  4003. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4004. res.set_content("Hello World!\n", "text/plain");
  4005. throw std::runtime_error("abc");
  4006. });
  4007. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4008. auto se = detail::scope_exit([&] {
  4009. svr.stop();
  4010. thread.join();
  4011. ASSERT_FALSE(svr.is_running());
  4012. });
  4013. svr.wait_until_ready();
  4014. for (size_t i = 0; i < 10; i++) {
  4015. Client cli(HOST, PORT);
  4016. for (size_t j = 0; j < 100; j++) {
  4017. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4019. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4020. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4021. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4022. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4023. }
  4024. cli.set_keep_alive(true);
  4025. for (size_t j = 0; j < 100; j++) {
  4026. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4028. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4029. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4030. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4031. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4032. }
  4033. }
  4034. }
  4035. TEST(ExceptionTest, AndErrorHandler) {
  4036. Server svr;
  4037. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4038. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4039. });
  4040. svr.set_exception_handler(
  4041. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4042. EXPECT_FALSE(ep == nullptr);
  4043. try {
  4044. std::rethrow_exception(ep);
  4045. } catch (std::exception &e) {
  4046. res.set_content(e.what(), "text/html");
  4047. } catch (...) {}
  4048. res.status = StatusCode::InternalServerError_500;
  4049. });
  4050. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4051. throw std::runtime_error("EXCEPTION");
  4052. });
  4053. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4054. res.set_content("ERROR", "text/html");
  4055. res.status = StatusCode::InternalServerError_500;
  4056. });
  4057. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4058. auto se = detail::scope_exit([&] {
  4059. svr.stop();
  4060. thread.join();
  4061. ASSERT_FALSE(svr.is_running());
  4062. });
  4063. svr.wait_until_ready();
  4064. Client cli(HOST, PORT);
  4065. {
  4066. auto res = cli.Get("/exception");
  4067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4068. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4069. EXPECT_EQ("EXCEPTION", res->body);
  4070. }
  4071. {
  4072. auto res = cli.Get("/error");
  4073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4074. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4075. EXPECT_EQ("ERROR", res->body);
  4076. }
  4077. {
  4078. auto res = cli.Get("/invalid");
  4079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4080. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4081. EXPECT_EQ("NOT_FOUND", res->body);
  4082. }
  4083. }
  4084. #endif
  4085. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4086. // process_request() wraps only routing() in a try/catch, so an exception from
  4087. // any other user callback used to unwind into the task queue - which does not
  4088. // catch - and terminate the process. Each test below runs the server on a
  4089. // single worker thread: a guard that catches the exception but still loses the
  4090. // thread would otherwise be hidden by a spare worker serving the follow-up
  4091. // request. Note that a regression here aborts the whole test binary rather
  4092. // than failing one test.
  4093. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4094. Server svr;
  4095. svr.new_task_queue = [] { return new ThreadPool(1); };
  4096. std::atomic<int> reported{0};
  4097. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4098. if (err == Error::UserCallbackException) { reported++; }
  4099. });
  4100. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4101. res.set_content_provider(
  4102. 1024, "text/plain",
  4103. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4104. sink.write("hello", 5);
  4105. throw std::runtime_error("from the content provider");
  4106. });
  4107. });
  4108. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4109. res.set_content("ok", "text/plain");
  4110. });
  4111. auto port = svr.bind_to_any_port(HOST);
  4112. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4113. auto se = detail::scope_exit([&] {
  4114. svr.stop();
  4115. listen_thread.join();
  4116. ASSERT_FALSE(svr.is_running());
  4117. });
  4118. svr.wait_until_ready();
  4119. {
  4120. Client cli(HOST, port);
  4121. cli.set_read_timeout(5, 0);
  4122. EXPECT_FALSE(cli.Get("/throw"));
  4123. }
  4124. EXPECT_TRUE(svr.is_running());
  4125. EXPECT_EQ(1, reported.load());
  4126. // A request on a fresh connection is still served.
  4127. {
  4128. Client cli(HOST, port);
  4129. auto res = cli.Get("/ok");
  4130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4131. EXPECT_EQ(StatusCode::OK_200, res->status);
  4132. EXPECT_EQ("ok", res->body);
  4133. }
  4134. }
  4135. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4136. Server svr;
  4137. svr.new_task_queue = [] { return new ThreadPool(1); };
  4138. std::atomic<bool> should_throw{true};
  4139. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4140. res.set_content("hi", "text/plain");
  4141. });
  4142. svr.set_post_routing_handler(
  4143. [&](const Request & /*req*/, Response & /*res*/) {
  4144. if (should_throw) {
  4145. throw std::runtime_error("from the post-routing handler");
  4146. }
  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("/hi"));
  4160. }
  4161. EXPECT_TRUE(svr.is_running());
  4162. should_throw = false;
  4163. {
  4164. Client cli(HOST, port);
  4165. auto res = cli.Get("/hi");
  4166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4167. EXPECT_EQ(StatusCode::OK_200, res->status);
  4168. EXPECT_EQ("hi", res->body);
  4169. }
  4170. }
  4171. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4172. // The guard reports the caught exception through the error logger, which is
  4173. // a user callback too. A logger that throws has to be contained as well, or
  4174. // the process would terminate from inside the catch.
  4175. Server svr;
  4176. svr.new_task_queue = [] { return new ThreadPool(1); };
  4177. std::atomic<int> reported{0};
  4178. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4179. if (err == Error::UserCallbackException) {
  4180. reported++;
  4181. throw std::runtime_error("from the error logger");
  4182. }
  4183. });
  4184. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4185. res.set_content_provider(
  4186. 1024, "text/plain",
  4187. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4188. sink.write("hello", 5);
  4189. throw std::runtime_error("from the content provider");
  4190. });
  4191. });
  4192. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4193. res.set_content("ok", "text/plain");
  4194. });
  4195. auto port = svr.bind_to_any_port(HOST);
  4196. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4197. auto se = detail::scope_exit([&] {
  4198. svr.stop();
  4199. listen_thread.join();
  4200. ASSERT_FALSE(svr.is_running());
  4201. });
  4202. svr.wait_until_ready();
  4203. {
  4204. Client cli(HOST, port);
  4205. cli.set_read_timeout(5, 0);
  4206. EXPECT_FALSE(cli.Get("/throw"));
  4207. }
  4208. EXPECT_TRUE(svr.is_running());
  4209. EXPECT_EQ(1, reported.load());
  4210. {
  4211. Client cli(HOST, port);
  4212. auto res = cli.Get("/ok");
  4213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4214. EXPECT_EQ(StatusCode::OK_200, res->status);
  4215. EXPECT_EQ("ok", res->body);
  4216. }
  4217. }
  4218. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4219. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4220. // so the exception unwinds through the ws::WebSocket object on its way to
  4221. // the guard. None of the HTTP cases above cross that.
  4222. Server svr;
  4223. svr.new_task_queue = [] { return new ThreadPool(1); };
  4224. std::atomic<int> reported{0};
  4225. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4226. if (err == Error::UserCallbackException) { reported++; }
  4227. });
  4228. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4229. throw std::runtime_error("from the WebSocket handler");
  4230. });
  4231. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4232. res.set_content("ok", "text/plain");
  4233. });
  4234. auto port = svr.bind_to_any_port(HOST);
  4235. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4236. auto se = detail::scope_exit([&] {
  4237. svr.stop();
  4238. listen_thread.join();
  4239. ASSERT_FALSE(svr.is_running());
  4240. });
  4241. svr.wait_until_ready();
  4242. {
  4243. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4244. "/ws");
  4245. auto res = client.connect();
  4246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4247. // The server dropped the connection instead of dying.
  4248. std::string msg;
  4249. EXPECT_FALSE(client.read(msg));
  4250. client.close();
  4251. }
  4252. EXPECT_TRUE(svr.is_running());
  4253. EXPECT_EQ(1, reported.load());
  4254. {
  4255. Client cli(HOST, port);
  4256. auto res = cli.Get("/ok");
  4257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4258. EXPECT_EQ(StatusCode::OK_200, res->status);
  4259. EXPECT_EQ("ok", res->body);
  4260. }
  4261. }
  4262. #ifdef CPPHTTPLIB_SSL_ENABLED
  4263. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4264. // SSLServer::process_and_close_socket() is a separate overload with its own
  4265. // guard, so it is exercised on its own.
  4266. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4267. ASSERT_TRUE(svr.is_valid());
  4268. svr.new_task_queue = [] { return new ThreadPool(1); };
  4269. std::atomic<int> reported{0};
  4270. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4271. if (err == Error::UserCallbackException) { reported++; }
  4272. });
  4273. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4274. res.set_content_provider(
  4275. 1024, "text/plain",
  4276. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4277. sink.write("hello", 5);
  4278. throw std::runtime_error("from the content provider");
  4279. });
  4280. });
  4281. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4282. res.set_content("ok", "text/plain");
  4283. });
  4284. auto port = svr.bind_to_any_port(HOST);
  4285. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4286. auto se = detail::scope_exit([&] {
  4287. svr.stop();
  4288. listen_thread.join();
  4289. ASSERT_FALSE(svr.is_running());
  4290. });
  4291. svr.wait_until_ready();
  4292. {
  4293. SSLClient cli(HOST, port);
  4294. cli.enable_server_certificate_verification(false);
  4295. cli.set_read_timeout(5, 0);
  4296. EXPECT_FALSE(cli.Get("/throw"));
  4297. }
  4298. EXPECT_TRUE(svr.is_running());
  4299. EXPECT_EQ(1, reported.load());
  4300. {
  4301. SSLClient cli(HOST, port);
  4302. cli.enable_server_certificate_verification(false);
  4303. auto res = cli.Get("/ok");
  4304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4305. EXPECT_EQ(StatusCode::OK_200, res->status);
  4306. EXPECT_EQ("ok", res->body);
  4307. }
  4308. }
  4309. #endif
  4310. #endif
  4311. TEST(NoContentTest, ContentLength) {
  4312. Server svr;
  4313. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4314. res.status = StatusCode::NoContent_204;
  4315. });
  4316. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4317. auto se = detail::scope_exit([&] {
  4318. svr.stop();
  4319. thread.join();
  4320. ASSERT_FALSE(svr.is_running());
  4321. });
  4322. svr.wait_until_ready();
  4323. {
  4324. Client cli(HOST, PORT);
  4325. auto res = cli.Get("/hi");
  4326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4327. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4328. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4329. }
  4330. }
  4331. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4332. #ifdef CPPHTTPLIB_SSL_ENABLED
  4333. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4334. ASSERT_TRUE(svr.is_valid());
  4335. #else
  4336. Server svr;
  4337. #endif
  4338. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4339. if (req.path == "/routing_handler") {
  4340. res.set_header("PRE_ROUTING", "on");
  4341. res.set_content("Routing Handler", "text/plain");
  4342. return httplib::Server::HandlerResponse::Handled;
  4343. }
  4344. return httplib::Server::HandlerResponse::Unhandled;
  4345. });
  4346. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4347. res.set_content("Error", "text/html");
  4348. });
  4349. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4350. if (req.path == "/routing_handler") {
  4351. res.set_header("POST_ROUTING", "on");
  4352. }
  4353. });
  4354. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4355. res.set_content("Hello World!\n", "text/plain");
  4356. });
  4357. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4358. auto se = detail::scope_exit([&] {
  4359. svr.stop();
  4360. thread.join();
  4361. ASSERT_FALSE(svr.is_running());
  4362. });
  4363. svr.wait_until_ready();
  4364. {
  4365. #ifdef CPPHTTPLIB_SSL_ENABLED
  4366. SSLClient cli(HOST, PORT);
  4367. cli.enable_server_certificate_verification(false);
  4368. #else
  4369. Client cli(HOST, PORT);
  4370. #endif
  4371. auto res = cli.Get("/routing_handler");
  4372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4373. EXPECT_EQ(StatusCode::OK_200, res->status);
  4374. EXPECT_EQ("Routing Handler", res->body);
  4375. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4376. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4377. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4378. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4379. }
  4380. {
  4381. #ifdef CPPHTTPLIB_SSL_ENABLED
  4382. SSLClient cli(HOST, PORT);
  4383. cli.enable_server_certificate_verification(false);
  4384. #else
  4385. Client cli(HOST, PORT);
  4386. #endif
  4387. auto res = cli.Get("/hi");
  4388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4389. EXPECT_EQ(StatusCode::OK_200, res->status);
  4390. EXPECT_EQ("Hello World!\n", res->body);
  4391. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4392. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4393. }
  4394. {
  4395. #ifdef CPPHTTPLIB_SSL_ENABLED
  4396. SSLClient cli(HOST, PORT);
  4397. cli.enable_server_certificate_verification(false);
  4398. #else
  4399. Client cli(HOST, PORT);
  4400. #endif
  4401. auto res = cli.Get("/aaa");
  4402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4403. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4404. EXPECT_EQ("Error", res->body);
  4405. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4406. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4407. }
  4408. }
  4409. TEST(RequestHandlerTest, PreRequestHandler) {
  4410. auto route_path = "/user/:user";
  4411. Server svr;
  4412. svr.Get("/hi", [](const Request &, Response &res) {
  4413. res.set_content("hi", "text/plain");
  4414. });
  4415. svr.Get(route_path, [](const Request &req, Response &res) {
  4416. res.set_content(req.path_params.at("user"), "text/plain");
  4417. });
  4418. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4419. if (req.matched_route == route_path) {
  4420. auto user = req.path_params.at("user");
  4421. if (user != "john") {
  4422. res.status = StatusCode::Forbidden_403;
  4423. res.set_content("error", "text/html");
  4424. return Server::HandlerResponse::Handled;
  4425. }
  4426. }
  4427. return Server::HandlerResponse::Unhandled;
  4428. });
  4429. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4430. auto se = detail::scope_exit([&] {
  4431. svr.stop();
  4432. thread.join();
  4433. ASSERT_FALSE(svr.is_running());
  4434. });
  4435. svr.wait_until_ready();
  4436. Client cli(HOST, PORT);
  4437. {
  4438. auto res = cli.Get("/hi");
  4439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4440. EXPECT_EQ(StatusCode::OK_200, res->status);
  4441. EXPECT_EQ("hi", res->body);
  4442. }
  4443. {
  4444. auto res = cli.Get("/user/john");
  4445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4446. EXPECT_EQ(StatusCode::OK_200, res->status);
  4447. EXPECT_EQ("john", res->body);
  4448. }
  4449. {
  4450. auto res = cli.Get("/user/invalid-user");
  4451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4452. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4453. EXPECT_EQ("error", res->body);
  4454. }
  4455. }
  4456. // The pre-request handler must run before the request body is read, so a
  4457. // rejected request never forces the server to buffer a (potentially large)
  4458. // body. Here the posted body is larger than the payload limit: if the body
  4459. // were read first the server would answer 413, but because the pre-request
  4460. // handler runs first it answers 403 and the body is never read.
  4461. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4462. Server svr;
  4463. svr.set_payload_max_length(8);
  4464. auto handler_ran = false;
  4465. svr.Post("/reject", [&](const Request &req, Response &res) {
  4466. handler_ran = true;
  4467. res.set_content(req.body, "text/plain");
  4468. });
  4469. svr.Post("/accept", [](const Request &req, Response &res) {
  4470. res.set_content(req.body, "text/plain");
  4471. });
  4472. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4473. if (req.matched_route == "/reject") {
  4474. res.status = StatusCode::Forbidden_403;
  4475. res.set_content("denied", "text/plain");
  4476. return Server::HandlerResponse::Handled;
  4477. }
  4478. return Server::HandlerResponse::Unhandled;
  4479. });
  4480. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4481. auto se = detail::scope_exit([&] {
  4482. svr.stop();
  4483. thread.join();
  4484. ASSERT_FALSE(svr.is_running());
  4485. });
  4486. svr.wait_until_ready();
  4487. Client cli(HOST, PORT);
  4488. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4489. // rejects with 403 before the body is read, so 413 is never reached.
  4490. {
  4491. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4493. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4494. EXPECT_EQ("denied", res->body);
  4495. EXPECT_FALSE(handler_ran);
  4496. }
  4497. // An approved route still reads the body and enforces the payload limit.
  4498. {
  4499. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4501. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4502. }
  4503. }
  4504. TEST(UserDataTest, BasicOperations) {
  4505. httplib::UserData ud;
  4506. // Initially empty
  4507. EXPECT_FALSE(ud.has("key"));
  4508. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4509. // set and get
  4510. ud.set("key", 42);
  4511. EXPECT_TRUE(ud.has("key"));
  4512. auto *p = ud.get<int>("key");
  4513. ASSERT_NE(nullptr, p);
  4514. EXPECT_EQ(42, *p);
  4515. // Type mismatch → nullptr
  4516. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4517. // Overwrite with different type
  4518. ud.set("key", std::string("hello"));
  4519. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4520. auto *s = ud.get<std::string>("key");
  4521. ASSERT_NE(nullptr, s);
  4522. EXPECT_EQ("hello", *s);
  4523. // erase
  4524. ud.erase("key");
  4525. EXPECT_FALSE(ud.has("key"));
  4526. // clear
  4527. ud.set("a", 1);
  4528. ud.set("b", 2);
  4529. ud.clear();
  4530. EXPECT_FALSE(ud.has("a"));
  4531. EXPECT_FALSE(ud.has("b"));
  4532. }
  4533. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4534. struct AuthCtx {
  4535. std::string user_id;
  4536. };
  4537. Server svr;
  4538. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4539. res.user_data.set("auth", AuthCtx{"alice"});
  4540. return Server::HandlerResponse::Unhandled;
  4541. });
  4542. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4543. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4544. ASSERT_NE(nullptr, ctx);
  4545. res.set_content("Hello " + ctx->user_id, "text/plain");
  4546. });
  4547. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4548. auto se = detail::scope_exit([&] {
  4549. svr.stop();
  4550. thread.join();
  4551. ASSERT_FALSE(svr.is_running());
  4552. });
  4553. svr.wait_until_ready();
  4554. Client cli(HOST, PORT);
  4555. auto res = cli.Get("/me");
  4556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4557. EXPECT_EQ(StatusCode::OK_200, res->status);
  4558. EXPECT_EQ("Hello alice", res->body);
  4559. }
  4560. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4561. struct RoleCtx {
  4562. std::string role;
  4563. };
  4564. Server svr;
  4565. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4566. res.user_data.set("role", RoleCtx{"admin"});
  4567. return Server::HandlerResponse::Unhandled;
  4568. });
  4569. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4570. auto *ctx = res.user_data.get<RoleCtx>("role");
  4571. ASSERT_NE(nullptr, ctx);
  4572. res.set_content(ctx->role, "text/plain");
  4573. });
  4574. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4575. auto se = detail::scope_exit([&] {
  4576. svr.stop();
  4577. thread.join();
  4578. ASSERT_FALSE(svr.is_running());
  4579. });
  4580. svr.wait_until_ready();
  4581. Client cli(HOST, PORT);
  4582. auto res = cli.Get("/role");
  4583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4584. EXPECT_EQ(StatusCode::OK_200, res->status);
  4585. EXPECT_EQ("admin", res->body);
  4586. }
  4587. TEST(InvalidFormatTest, StatusCode) {
  4588. Server svr;
  4589. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4590. res.set_content("Hello World!\n", "text/plain");
  4591. res.status = 9999; // Status should be a three-digit code...
  4592. });
  4593. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4594. auto se = detail::scope_exit([&] {
  4595. svr.stop();
  4596. thread.join();
  4597. ASSERT_FALSE(svr.is_running());
  4598. });
  4599. svr.wait_until_ready();
  4600. {
  4601. Client cli(HOST, PORT);
  4602. auto res = cli.Get("/hi");
  4603. ASSERT_FALSE(res);
  4604. }
  4605. }
  4606. TEST(URLFragmentTest, WithFragment) {
  4607. Server svr;
  4608. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4609. EXPECT_TRUE(req.target == "/hi");
  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. {
  4619. Client cli(HOST, PORT);
  4620. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4621. EXPECT_TRUE(res);
  4622. EXPECT_EQ(StatusCode::OK_200, res->status);
  4623. res = cli.Get("/hi%23key1=val1=key2=val2");
  4624. EXPECT_TRUE(res);
  4625. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4626. }
  4627. }
  4628. TEST(HeaderWriter, SetHeaderWriter) {
  4629. Server svr;
  4630. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4631. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4632. return detail::write_headers(strm, hdrs);
  4633. });
  4634. svr.Get("/hi", [](const Request &req, Response &res) {
  4635. auto it = req.headers.find("CustomClientHeader");
  4636. EXPECT_TRUE(it != req.headers.end());
  4637. EXPECT_EQ(it->second, "CustomClientValue");
  4638. res.set_content("Hello World!\n", "text/plain");
  4639. });
  4640. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4641. auto se = detail::scope_exit([&] {
  4642. svr.stop();
  4643. thread.join();
  4644. ASSERT_FALSE(svr.is_running());
  4645. });
  4646. svr.wait_until_ready();
  4647. {
  4648. Client cli(HOST, PORT);
  4649. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4650. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4651. return detail::write_headers(strm, hdrs);
  4652. });
  4653. auto res = cli.Get("/hi");
  4654. EXPECT_TRUE(res);
  4655. EXPECT_EQ(StatusCode::OK_200, res->status);
  4656. auto it = res->headers.find("CustomServerHeader");
  4657. EXPECT_TRUE(it != res->headers.end());
  4658. EXPECT_EQ(it->second, "CustomServerValue");
  4659. }
  4660. }
  4661. class ServerTest : public ::testing::Test {
  4662. protected:
  4663. ServerTest()
  4664. : cli_(HOST, PORT)
  4665. #ifdef CPPHTTPLIB_SSL_ENABLED
  4666. ,
  4667. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4668. #endif
  4669. {
  4670. #ifdef CPPHTTPLIB_SSL_ENABLED
  4671. cli_.enable_server_certificate_verification(false);
  4672. #endif
  4673. // Allow LARGE_DATA (100MB) responses
  4674. cli_.set_payload_max_length(200 * 1024 * 1024);
  4675. }
  4676. virtual void SetUp() {
  4677. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4678. svr_.set_payload_max_length(200 * 1024 * 1024);
  4679. svr_.set_mount_point("/", "./www");
  4680. svr_.set_mount_point("/mount", "./www2");
  4681. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4682. svr_.Get("/hi",
  4683. [&](const Request & /*req*/, Response &res) {
  4684. res.set_content("Hello World!", "text/plain");
  4685. })
  4686. .Get("/file_content",
  4687. [&](const Request & /*req*/, Response &res) {
  4688. res.set_file_content("./www/dir/test.html");
  4689. })
  4690. .Get("/file_content_with_content_type",
  4691. [&](const Request & /*req*/, Response &res) {
  4692. res.set_file_content("./www/file", "text/plain");
  4693. })
  4694. .Get("/invalid_file_content",
  4695. [&](const Request & /*req*/, Response &res) {
  4696. res.set_file_content("./www/dir/invalid_file_path");
  4697. })
  4698. .Get("/http_response_splitting",
  4699. [&](const Request & /*req*/, Response &res) {
  4700. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4701. EXPECT_EQ(0U, res.headers.size());
  4702. EXPECT_FALSE(res.has_header("a"));
  4703. res.set_header("a", "1\nSet-Cookie: a=1");
  4704. EXPECT_EQ(0U, res.headers.size());
  4705. EXPECT_FALSE(res.has_header("a"));
  4706. res.set_header("a", "1\rSet-Cookie: a=1");
  4707. EXPECT_EQ(0U, res.headers.size());
  4708. EXPECT_FALSE(res.has_header("a"));
  4709. res.set_header("a\r\nb", "0");
  4710. EXPECT_EQ(0U, res.headers.size());
  4711. EXPECT_FALSE(res.has_header("a"));
  4712. res.set_header("a\rb", "0");
  4713. EXPECT_EQ(0U, res.headers.size());
  4714. EXPECT_FALSE(res.has_header("a"));
  4715. res.set_header("a\nb", "0");
  4716. EXPECT_EQ(0U, res.headers.size());
  4717. EXPECT_FALSE(res.has_header("a"));
  4718. res.set_redirect("1\r\nSet-Cookie: a=1");
  4719. EXPECT_EQ(0U, res.headers.size());
  4720. EXPECT_FALSE(res.has_header("Location"));
  4721. })
  4722. .Get("/slow",
  4723. [&](const Request & /*req*/, Response &res) {
  4724. std::this_thread::sleep_for(std::chrono::seconds(4));
  4725. res.set_content("slow", "text/plain");
  4726. })
  4727. #if 0
  4728. .Post("/slowpost",
  4729. [&](const Request & /*req*/, Response &res) {
  4730. std::this_thread::sleep_for(std::chrono::seconds(2));
  4731. res.set_content("slow", "text/plain");
  4732. })
  4733. #endif
  4734. .Get("/remote_addr",
  4735. [&](const Request &req, Response &res) {
  4736. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4737. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4738. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4739. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4740. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4741. #endif
  4742. res.set_content(req.remote_addr, "text/plain");
  4743. })
  4744. .Get("/local_addr",
  4745. [&](const Request &req, Response &res) {
  4746. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4747. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4748. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4749. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4750. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4751. #endif
  4752. auto local_addr = req.local_addr;
  4753. auto local_port = std::to_string(req.local_port);
  4754. res.set_content(local_addr.append(":").append(local_port),
  4755. "text/plain");
  4756. })
  4757. .Get("/endwith%",
  4758. [&](const Request & /*req*/, Response &res) {
  4759. res.set_content("Hello World!", "text/plain");
  4760. })
  4761. .Get("/a\\+\\+b",
  4762. [&](const Request &req, Response &res) {
  4763. ASSERT_TRUE(req.has_param("a +b"));
  4764. auto val = req.get_param_value("a +b");
  4765. res.set_content(val, "text/plain");
  4766. })
  4767. .Get("/", [&](const Request & /*req*/,
  4768. Response &res) { res.set_redirect("/hi"); })
  4769. .Post("/1",
  4770. [](const Request & /*req*/, Response &res) {
  4771. res.set_redirect("/2", StatusCode::SeeOther_303);
  4772. })
  4773. .Get("/2",
  4774. [](const Request & /*req*/, Response &res) {
  4775. res.set_content("redirected.", "text/plain");
  4776. res.status = StatusCode::OK_200;
  4777. })
  4778. .Post("/person",
  4779. [&](const Request &req, Response &res) {
  4780. if (req.has_param("name") && req.has_param("note")) {
  4781. persons_[req.get_param_value("name")] =
  4782. req.get_param_value("note");
  4783. } else {
  4784. res.status = StatusCode::BadRequest_400;
  4785. }
  4786. })
  4787. .Put("/person",
  4788. [&](const Request &req, Response &res) {
  4789. if (req.has_param("name") && req.has_param("note")) {
  4790. persons_[req.get_param_value("name")] =
  4791. req.get_param_value("note");
  4792. } else {
  4793. res.status = StatusCode::BadRequest_400;
  4794. }
  4795. })
  4796. .Get("/person/(.*)",
  4797. [&](const Request &req, Response &res) {
  4798. string name = req.matches[1];
  4799. if (persons_.find(name) != persons_.end()) {
  4800. auto note = persons_[name];
  4801. res.set_content(note, "text/plain");
  4802. } else {
  4803. res.status = StatusCode::NotFound_404;
  4804. }
  4805. })
  4806. .Delete("/person",
  4807. [&](const Request &req, Response &res) {
  4808. if (req.has_param("name")) {
  4809. string name = req.get_param_value("name");
  4810. if (persons_.find(name) != persons_.end()) {
  4811. persons_.erase(name);
  4812. res.set_content("DELETED", "text/plain");
  4813. } else {
  4814. res.status = StatusCode::NotFound_404;
  4815. }
  4816. } else {
  4817. res.status = StatusCode::BadRequest_400;
  4818. }
  4819. })
  4820. .Post("/x-www-form-urlencoded-json",
  4821. [&](const Request &req, Response &res) {
  4822. auto json = req.get_param_value("json");
  4823. ASSERT_EQ(JSON_DATA, json);
  4824. res.set_content(json, "appliation/json");
  4825. res.status = StatusCode::OK_200;
  4826. })
  4827. .Get("/streamed-chunked",
  4828. [&](const Request & /*req*/, Response &res) {
  4829. res.set_chunked_content_provider(
  4830. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4831. sink.os << "123";
  4832. sink.os << "456";
  4833. sink.os << "789";
  4834. sink.done();
  4835. return true;
  4836. });
  4837. })
  4838. .Get("/streamed-chunked-with-prohibited-trailer",
  4839. [&](const Request & /*req*/, Response &res) {
  4840. auto i = new int(0);
  4841. // Declare both a prohibited trailer (Content-Length) and an
  4842. // allowed one
  4843. res.set_header("Trailer", "Content-Length, X-Allowed");
  4844. res.set_chunked_content_provider(
  4845. "text/plain",
  4846. [i](size_t /*offset*/, DataSink &sink) {
  4847. switch (*i) {
  4848. case 0: sink.os << "123"; break;
  4849. case 1: sink.os << "456"; break;
  4850. case 2: sink.os << "789"; break;
  4851. case 3: {
  4852. sink.done_with_trailer(
  4853. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4854. } break;
  4855. }
  4856. (*i)++;
  4857. return true;
  4858. },
  4859. [i](bool success) {
  4860. EXPECT_TRUE(success);
  4861. delete i;
  4862. });
  4863. })
  4864. .Get("/streamed-chunked2",
  4865. [&](const Request & /*req*/, Response &res) {
  4866. auto i = new int(0);
  4867. res.set_chunked_content_provider(
  4868. "text/plain",
  4869. [i](size_t /*offset*/, DataSink &sink) {
  4870. switch (*i) {
  4871. case 0: sink.os << "123"; break;
  4872. case 1: sink.os << "456"; break;
  4873. case 2: sink.os << "789"; break;
  4874. case 3: sink.done(); break;
  4875. }
  4876. (*i)++;
  4877. return true;
  4878. },
  4879. [i](bool success) {
  4880. EXPECT_TRUE(success);
  4881. delete i;
  4882. });
  4883. })
  4884. .Get("/streamed-chunked-with-trailer",
  4885. [&](const Request & /*req*/, Response &res) {
  4886. auto i = new int(0);
  4887. res.set_header("Trailer", "Dummy1, Dummy2");
  4888. res.set_chunked_content_provider(
  4889. "text/plain",
  4890. [i](size_t /*offset*/, DataSink &sink) {
  4891. switch (*i) {
  4892. case 0: sink.os << "123"; break;
  4893. case 1: sink.os << "456"; break;
  4894. case 2: sink.os << "789"; break;
  4895. case 3: {
  4896. sink.done_with_trailer(
  4897. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4898. } break;
  4899. }
  4900. (*i)++;
  4901. return true;
  4902. },
  4903. [i](bool success) {
  4904. EXPECT_TRUE(success);
  4905. delete i;
  4906. });
  4907. })
  4908. .Get("/streamed",
  4909. [&](const Request & /*req*/, Response &res) {
  4910. res.set_content_provider(
  4911. 6, "text/plain",
  4912. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4913. sink.os << (offset < 3 ? "a" : "b");
  4914. return true;
  4915. });
  4916. })
  4917. .Get("/streamed-without-length",
  4918. [&](const Request & /*req*/, Response &res) {
  4919. auto data = new std::string("abcdefg");
  4920. res.set_content_provider(
  4921. "text/plain",
  4922. [data](size_t offset, DataSink &sink) {
  4923. if (offset < data->size()) {
  4924. sink.os << data->substr(offset);
  4925. }
  4926. sink.done();
  4927. return true;
  4928. },
  4929. [data](bool success) {
  4930. EXPECT_TRUE(success);
  4931. delete data;
  4932. });
  4933. })
  4934. .Get("/streamed-with-range",
  4935. [&](const Request &req, Response &res) {
  4936. auto data = new std::string("abcdefg");
  4937. // An explicit status keeps the server from picking the 206 it
  4938. // would otherwise choose for a ranged request, so the response
  4939. // is not a partial representation.
  4940. auto status = req.get_param_value("status");
  4941. if (status == "200") {
  4942. res.status = StatusCode::OK_200;
  4943. } else if (status == "403") {
  4944. res.status = StatusCode::Forbidden_403;
  4945. }
  4946. res.set_content_provider(
  4947. data->size(), "text/plain",
  4948. [data](size_t offset, size_t length, DataSink &sink) {
  4949. size_t DATA_CHUNK_SIZE = 4;
  4950. const auto &d = *data;
  4951. auto out_len =
  4952. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4953. auto ret =
  4954. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4955. EXPECT_TRUE(ret);
  4956. return true;
  4957. },
  4958. [data, &req](bool success) {
  4959. EXPECT_EQ(success, !req.has_param("error"));
  4960. delete data;
  4961. });
  4962. })
  4963. .Get("/streamed-cancel",
  4964. [&](const Request & /*req*/, Response &res) {
  4965. res.set_content_provider(
  4966. size_t(-1), "text/plain",
  4967. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4968. sink.os << "data_chunk";
  4969. return true;
  4970. });
  4971. })
  4972. .Get("/regex-with-delimiter",
  4973. [&](const Request &req, Response & /*res*/) {
  4974. ASSERT_TRUE(req.has_param("key"));
  4975. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4976. })
  4977. .Get("/with-range",
  4978. [&](const Request & /*req*/, Response &res) {
  4979. res.set_content("abcdefg", "text/plain");
  4980. })
  4981. .Get("/test-start-time",
  4982. [&](const Request &req, Response & /*res*/) {
  4983. EXPECT_NE(req.start_time_,
  4984. std::chrono::steady_clock::time_point::min());
  4985. })
  4986. .Get("/with-range-customized-response",
  4987. [&](const Request & /*req*/, Response &res) {
  4988. res.status = StatusCode::BadRequest_400;
  4989. res.set_content(JSON_DATA, "application/json");
  4990. })
  4991. .Post("/chunked",
  4992. [&](const Request &req, Response & /*res*/) {
  4993. EXPECT_EQ(req.body, "dechunked post body");
  4994. })
  4995. .Post("/large-chunked",
  4996. [&](const Request &req, Response & /*res*/) {
  4997. std::string expected(6 * 30 * 1024u, 'a');
  4998. EXPECT_EQ(req.body, expected);
  4999. })
  5000. .Post("/multipart",
  5001. [&](const Request &req, Response & /*res*/) {
  5002. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5003. req.form.get_field_count("text2") +
  5004. req.form.get_field_count("file3") +
  5005. req.form.get_field_count("file4"));
  5006. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5007. req.form.get_file_count("file2"));
  5008. ASSERT_TRUE(!req.form.has_file("???"));
  5009. ASSERT_TRUE(!req.form.has_field("???"));
  5010. ASSERT_TRUE(req.body.empty());
  5011. {
  5012. const auto &text = req.form.get_field("text1");
  5013. EXPECT_EQ("text default", text);
  5014. }
  5015. {
  5016. const auto &text = req.form.get_field("text2");
  5017. EXPECT_EQ("aωb", text);
  5018. }
  5019. {
  5020. const auto &file = req.form.get_file("file1");
  5021. EXPECT_EQ("hello.txt", file.filename);
  5022. EXPECT_EQ("text/plain", file.content_type);
  5023. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5024. }
  5025. {
  5026. const auto &file = req.form.get_file("file2");
  5027. EXPECT_EQ("world.json", file.filename);
  5028. EXPECT_EQ("application/json", file.content_type);
  5029. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5030. }
  5031. {
  5032. const auto &text = req.form.get_field("file3");
  5033. EXPECT_EQ(0u, text.size());
  5034. }
  5035. {
  5036. const auto &text = req.form.get_field("file4");
  5037. EXPECT_EQ(0u, text.size());
  5038. }
  5039. })
  5040. .Post("/multipart/multi_file_values",
  5041. [&](const Request &req, Response & /*res*/) {
  5042. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5043. req.form.get_field_count("multi_text1"));
  5044. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  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("text");
  5050. EXPECT_EQ("default text", text);
  5051. }
  5052. {
  5053. const auto &text1_values = req.form.get_fields("multi_text1");
  5054. EXPECT_EQ(2u, text1_values.size());
  5055. EXPECT_EQ("aaaaa", text1_values[0]);
  5056. EXPECT_EQ("bbbbb", text1_values[1]);
  5057. }
  5058. {
  5059. const auto &file1_values = req.form.get_files("multi_file1");
  5060. EXPECT_EQ(2u, file1_values.size());
  5061. auto file1 = file1_values[0];
  5062. EXPECT_EQ(file1.filename, "hello.txt");
  5063. EXPECT_EQ(file1.content_type, "text/plain");
  5064. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5065. auto file2 = file1_values[1];
  5066. EXPECT_EQ(file2.filename, "world.json");
  5067. EXPECT_EQ(file2.content_type, "application/json");
  5068. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5069. }
  5070. })
  5071. .Post("/empty",
  5072. [&](const Request &req, Response &res) {
  5073. EXPECT_EQ(req.body, "");
  5074. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5075. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5076. res.set_content("empty", "text/plain");
  5077. })
  5078. .Post("/empty-no-content-type",
  5079. [&](const Request &req, Response &res) {
  5080. EXPECT_EQ(req.body, "");
  5081. EXPECT_FALSE(req.has_header("Content-Type"));
  5082. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5083. res.set_content("empty-no-content-type", "text/plain");
  5084. })
  5085. .Post("/path-only",
  5086. [&](const Request &req, Response &res) {
  5087. EXPECT_EQ(req.body, "");
  5088. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5089. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5090. res.set_content("path-only", "text/plain");
  5091. })
  5092. .Post("/path-headers-only",
  5093. [&](const Request &req, Response &res) {
  5094. EXPECT_EQ(req.body, "");
  5095. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5096. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5097. EXPECT_EQ("world", req.get_header_value("hello"));
  5098. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5099. res.set_content("path-headers-only", "text/plain");
  5100. })
  5101. .Post("/post-large",
  5102. [&](const Request &req, Response &res) {
  5103. EXPECT_EQ(req.body, LARGE_DATA);
  5104. res.set_content(req.body, "text/plain");
  5105. })
  5106. .Post("/post-loopback",
  5107. [&](const Request &, Response &res,
  5108. ContentReader const &content_reader) {
  5109. std::string body;
  5110. content_reader([&](const char *data, size_t data_length) {
  5111. body.append(data, data_length);
  5112. return true;
  5113. });
  5114. res.set_content(body, "text/plain");
  5115. })
  5116. .Put("/put-loopback",
  5117. [&](const Request &, Response &res,
  5118. ContentReader const &content_reader) {
  5119. std::string body;
  5120. content_reader([&](const char *data, size_t data_length) {
  5121. body.append(data, data_length);
  5122. return true;
  5123. });
  5124. res.set_content(body, "text/plain");
  5125. })
  5126. .Patch("/patch-loopback",
  5127. [&](const Request &, Response &res,
  5128. ContentReader const &content_reader) {
  5129. std::string body;
  5130. content_reader([&](const char *data, size_t data_length) {
  5131. body.append(data, data_length);
  5132. return true;
  5133. });
  5134. res.set_content(body, "text/plain");
  5135. })
  5136. .Put("/empty-no-content-type",
  5137. [&](const Request &req, Response &res) {
  5138. EXPECT_EQ(req.body, "");
  5139. EXPECT_FALSE(req.has_header("Content-Type"));
  5140. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5141. res.set_content("empty-no-content-type", "text/plain");
  5142. })
  5143. .Put("/put",
  5144. [&](const Request &req, Response &res) {
  5145. EXPECT_EQ(req.body, "PUT");
  5146. res.set_content(req.body, "text/plain");
  5147. })
  5148. .Put("/put-large",
  5149. [&](const Request &req, Response &res) {
  5150. EXPECT_EQ(req.body, LARGE_DATA);
  5151. res.set_content(req.body, "text/plain");
  5152. })
  5153. .Patch("/patch",
  5154. [&](const Request &req, Response &res) {
  5155. EXPECT_EQ(req.body, "PATCH");
  5156. res.set_content(req.body, "text/plain");
  5157. })
  5158. .Delete("/delete",
  5159. [&](const Request & /*req*/, Response &res) {
  5160. res.set_content("DELETE", "text/plain");
  5161. })
  5162. .Delete("/delete-body",
  5163. [&](const Request &req, Response &res) {
  5164. EXPECT_EQ(req.body, "content");
  5165. res.set_content(req.body, "text/plain");
  5166. })
  5167. .Options(R"(\*)",
  5168. [&](const Request & /*req*/, Response &res) {
  5169. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5170. })
  5171. .CustomRoute("PROPFIND", "/dav/:id",
  5172. [&](const Request &req, Response &res) {
  5173. res.set_header("x-body-size",
  5174. std::to_string(req.body.size()));
  5175. res.set_header("x-matched-route", req.matched_route);
  5176. res.set_header("x-dav-id", req.path_params.at("id"));
  5177. res.status = StatusCode::MultiStatus_207;
  5178. res.set_content(req.body, "application/xml");
  5179. })
  5180. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5181. [&](const Request &req, Response &res) {
  5182. res.set_header("x-dav-match", req.matches[1]);
  5183. res.status = StatusCode::MultiStatus_207;
  5184. })
  5185. .CustomRoute("MKCOL", "/dav-mkcol",
  5186. [&](const Request &req, Response &res) {
  5187. EXPECT_TRUE(req.body.empty());
  5188. res.status = StatusCode::Created_201;
  5189. })
  5190. .CustomRoute(
  5191. "REPORT", "/dav-report",
  5192. [&](const Request & /*req*/, Response &res,
  5193. const ContentReader &content_reader) {
  5194. std::string body;
  5195. content_reader([&](const char *data, size_t data_length) {
  5196. body.append(data, data_length);
  5197. return true;
  5198. });
  5199. res.set_header("x-body-size", std::to_string(body.size()));
  5200. res.status = StatusCode::MultiStatus_207;
  5201. res.set_content(body, "application/xml");
  5202. })
  5203. .Get("/request-target",
  5204. [&](const Request &req, Response & /*res*/) {
  5205. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5206. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5207. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5208. })
  5209. .Get("/long-query-value",
  5210. [&](const Request &req, Response & /*res*/) {
  5211. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5212. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5213. })
  5214. .Get("/too-long-query-value",
  5215. [&](const Request &req, Response & /*res*/) {
  5216. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5217. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5218. })
  5219. .Get("/array-param",
  5220. [&](const Request &req, Response & /*res*/) {
  5221. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5222. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5223. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5224. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5225. })
  5226. .Get("/array-param-values",
  5227. [&](const Request &req, Response & /*res*/) {
  5228. auto values = req.get_param_values("array");
  5229. EXPECT_EQ(3u, values.size());
  5230. EXPECT_EQ("value1", values[0]);
  5231. EXPECT_EQ("value2", values[1]);
  5232. EXPECT_EQ("value3", values[2]);
  5233. auto empty = req.get_param_values("nonexistent");
  5234. EXPECT_TRUE(empty.empty());
  5235. })
  5236. .Post("/validate-no-multiple-headers",
  5237. [&](const Request &req, Response & /*res*/) {
  5238. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5239. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5240. })
  5241. .Post("/content_receiver",
  5242. [&](const Request &req, Response &res,
  5243. const ContentReader &content_reader) {
  5244. if (req.is_multipart_form_data()) {
  5245. std::vector<FormData> items;
  5246. content_reader(
  5247. [&](const FormData &file) {
  5248. items.push_back(file);
  5249. return true;
  5250. },
  5251. [&](const char *data, size_t data_length) {
  5252. items.back().content.append(data, data_length);
  5253. return true;
  5254. });
  5255. EXPECT_EQ(5u, items.size());
  5256. {
  5257. const auto &file = get_file_value(items, "text1");
  5258. EXPECT_TRUE(file.filename.empty());
  5259. EXPECT_EQ("text default", file.content);
  5260. }
  5261. {
  5262. const auto &file = get_file_value(items, "text2");
  5263. EXPECT_TRUE(file.filename.empty());
  5264. EXPECT_EQ("aωb", file.content);
  5265. }
  5266. {
  5267. const auto &file = get_file_value(items, "file1");
  5268. EXPECT_EQ("hello.txt", file.filename);
  5269. EXPECT_EQ("text/plain", file.content_type);
  5270. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5271. }
  5272. {
  5273. const auto &file = get_file_value(items, "file2");
  5274. EXPECT_EQ("world.json", file.filename);
  5275. EXPECT_EQ("application/json", file.content_type);
  5276. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5277. }
  5278. {
  5279. const auto &file = get_file_value(items, "file3");
  5280. EXPECT_TRUE(file.filename.empty());
  5281. EXPECT_EQ("application/octet-stream", file.content_type);
  5282. EXPECT_EQ(0u, file.content.size());
  5283. }
  5284. } else {
  5285. std::string body;
  5286. content_reader([&](const char *data, size_t data_length) {
  5287. EXPECT_EQ(7U, data_length);
  5288. body.append(data, data_length);
  5289. return true;
  5290. });
  5291. EXPECT_EQ(body, "content");
  5292. res.set_content(body, "text/plain");
  5293. }
  5294. })
  5295. .Put("/content_receiver",
  5296. [&](const Request & /*req*/, Response &res,
  5297. const ContentReader &content_reader) {
  5298. std::string body;
  5299. content_reader([&](const char *data, size_t data_length) {
  5300. body.append(data, data_length);
  5301. return true;
  5302. });
  5303. EXPECT_EQ(body, "content");
  5304. res.set_content(body, "text/plain");
  5305. })
  5306. .Patch("/content_receiver",
  5307. [&](const Request & /*req*/, Response &res,
  5308. const ContentReader &content_reader) {
  5309. std::string body;
  5310. content_reader([&](const char *data, size_t data_length) {
  5311. body.append(data, data_length);
  5312. return true;
  5313. });
  5314. EXPECT_EQ(body, "content");
  5315. res.set_content(body, "text/plain");
  5316. })
  5317. .Post("/query-string-and-body",
  5318. [&](const Request &req, Response & /*res*/) {
  5319. ASSERT_TRUE(req.has_param("key"));
  5320. EXPECT_EQ(req.get_param_value("key"), "value");
  5321. EXPECT_EQ(req.body, "content");
  5322. })
  5323. .Get("/last-request",
  5324. [&](const Request &req, Response & /*res*/) {
  5325. EXPECT_EQ("close", req.get_header_value("Connection"));
  5326. })
  5327. .Get(R"(/redirect/(\d+))",
  5328. [&](const Request &req, Response &res) {
  5329. auto num = std::stoi(req.matches[1]) + 1;
  5330. std::string url = "/redirect/" + std::to_string(num);
  5331. res.set_redirect(url);
  5332. })
  5333. .Post("/binary",
  5334. [&](const Request &req, Response &res) {
  5335. EXPECT_EQ(4U, req.body.size());
  5336. EXPECT_EQ("application/octet-stream",
  5337. req.get_header_value("Content-Type"));
  5338. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5339. res.set_content(req.body, "application/octet-stream");
  5340. })
  5341. .Put("/binary",
  5342. [&](const Request &req, Response &res) {
  5343. EXPECT_EQ(4U, req.body.size());
  5344. EXPECT_EQ("application/octet-stream",
  5345. req.get_header_value("Content-Type"));
  5346. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5347. res.set_content(req.body, "application/octet-stream");
  5348. })
  5349. .Patch("/binary",
  5350. [&](const Request &req, Response &res) {
  5351. EXPECT_EQ(4U, req.body.size());
  5352. EXPECT_EQ("application/octet-stream",
  5353. req.get_header_value("Content-Type"));
  5354. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5355. res.set_content(req.body, "application/octet-stream");
  5356. })
  5357. .Delete("/binary",
  5358. [&](const Request &req, Response &res) {
  5359. EXPECT_EQ(4U, req.body.size());
  5360. EXPECT_EQ("application/octet-stream",
  5361. req.get_header_value("Content-Type"));
  5362. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5363. res.set_content(req.body, "application/octet-stream");
  5364. })
  5365. .Get("/issue1772",
  5366. [&](const Request & /*req*/, Response &res) {
  5367. res.status = 401;
  5368. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5369. })
  5370. .Delete("/issue609",
  5371. [](const httplib::Request &, httplib::Response &res,
  5372. const httplib::ContentReader &) {
  5373. res.set_content("ok", "text/plain");
  5374. })
  5375. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5376. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5377. .Get("/compress",
  5378. [&](const Request & /*req*/, Response &res) {
  5379. res.set_content(
  5380. "12345678901234567890123456789012345678901234567890123456789"
  5381. "01234567890123456789012345678901234567890",
  5382. "text/plain");
  5383. })
  5384. .Get("/compress-with-charset",
  5385. [&](const Request & /*req*/, Response &res) {
  5386. res.set_content(
  5387. "12345678901234567890123456789012345678901234567890123456789"
  5388. "01234567890123456789012345678901234567890",
  5389. "application/json; charset=utf-8");
  5390. })
  5391. .Get("/nocompress",
  5392. [&](const Request & /*req*/, Response &res) {
  5393. res.set_content(
  5394. "12345678901234567890123456789012345678901234567890123456789"
  5395. "01234567890123456789012345678901234567890",
  5396. "application/octet-stream");
  5397. })
  5398. .Post("/compress-multipart",
  5399. [&](const Request &req, Response & /*res*/) {
  5400. EXPECT_EQ(2u, req.form.fields.size());
  5401. ASSERT_TRUE(!req.form.has_field("???"));
  5402. {
  5403. const auto &text = req.form.get_field("key1");
  5404. EXPECT_EQ("test", text);
  5405. }
  5406. {
  5407. const auto &text = req.form.get_field("key2");
  5408. EXPECT_EQ("--abcdefg123", text);
  5409. }
  5410. })
  5411. #endif
  5412. ;
  5413. persons_["john"] = "programmer";
  5414. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5415. svr_.wait_until_ready();
  5416. }
  5417. virtual void TearDown() {
  5418. svr_.stop();
  5419. if (!request_threads_.empty()) {
  5420. std::this_thread::sleep_for(std::chrono::seconds(1));
  5421. for (auto &t : request_threads_) {
  5422. t.join();
  5423. }
  5424. }
  5425. t_.join();
  5426. }
  5427. map<string, string> persons_;
  5428. #ifdef CPPHTTPLIB_SSL_ENABLED
  5429. SSLClient cli_;
  5430. SSLServer svr_;
  5431. #else
  5432. Client cli_;
  5433. Server svr_;
  5434. #endif
  5435. thread t_;
  5436. std::vector<thread> request_threads_;
  5437. };
  5438. TEST_F(ServerTest, GetMethod200) {
  5439. auto res = cli_.Get("/hi");
  5440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5441. EXPECT_EQ("HTTP/1.1", res->version);
  5442. EXPECT_EQ(StatusCode::OK_200, res->status);
  5443. EXPECT_EQ("OK", res->reason);
  5444. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5445. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5446. EXPECT_EQ("Hello World!", res->body);
  5447. }
  5448. TEST_F(ServerTest, GetEmptyFile) {
  5449. auto res = cli_.Get("/empty_file");
  5450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5451. EXPECT_EQ(StatusCode::OK_200, res->status);
  5452. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5453. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5454. EXPECT_EQ("", res->body);
  5455. }
  5456. TEST_F(ServerTest, GetFileContent) {
  5457. auto res = cli_.Get("/file_content");
  5458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5459. EXPECT_EQ(StatusCode::OK_200, res->status);
  5460. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5461. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5462. EXPECT_EQ("test.html", res->body);
  5463. }
  5464. TEST_F(ServerTest, GetFileContentWithRange) {
  5465. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5467. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5468. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5469. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5470. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5471. EXPECT_EQ("est", res->body);
  5472. }
  5473. TEST_F(ServerTest, GetFileContentWithContentType) {
  5474. auto res = cli_.Get("/file_content_with_content_type");
  5475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5476. EXPECT_EQ(StatusCode::OK_200, res->status);
  5477. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5478. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5479. EXPECT_EQ("file\n", res->body);
  5480. }
  5481. TEST_F(ServerTest, GetInvalidFileContent) {
  5482. auto res = cli_.Get("/invalid_file_content");
  5483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5484. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5485. }
  5486. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5487. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5489. EXPECT_EQ("HTTP/1.1", res->version);
  5490. EXPECT_EQ(StatusCode::OK_200, res->status);
  5491. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5492. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5493. EXPECT_EQ("Hello World!", res->body);
  5494. }
  5495. TEST_F(ServerTest, GetMethod302) {
  5496. auto res = cli_.Get("/");
  5497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5498. EXPECT_EQ(StatusCode::Found_302, res->status);
  5499. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5500. }
  5501. TEST_F(ServerTest, GetMethod302Redirect) {
  5502. cli_.set_follow_location(true);
  5503. auto res = cli_.Get("/");
  5504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5505. EXPECT_EQ(StatusCode::OK_200, res->status);
  5506. EXPECT_EQ("Hello World!", res->body);
  5507. EXPECT_EQ("/hi", res->location);
  5508. }
  5509. TEST_F(ServerTest, GetMethod404) {
  5510. auto res = cli_.Get("/invalid");
  5511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5512. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5513. }
  5514. TEST_F(ServerTest, HeadMethod200) {
  5515. auto res = cli_.Head("/hi");
  5516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5517. EXPECT_EQ(StatusCode::OK_200, res->status);
  5518. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5519. EXPECT_TRUE(res->body.empty());
  5520. }
  5521. TEST_F(ServerTest, HeadMethod200Static) {
  5522. auto res = cli_.Head("/mount/dir/index.html");
  5523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5524. EXPECT_EQ(StatusCode::OK_200, res->status);
  5525. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5526. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5527. EXPECT_TRUE(res->body.empty());
  5528. }
  5529. TEST_F(ServerTest, HeadMethod404) {
  5530. auto res = cli_.Head("/invalid");
  5531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5532. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5533. EXPECT_TRUE(res->body.empty());
  5534. }
  5535. TEST_F(ServerTest, GetMethodPersonJohn) {
  5536. auto res = cli_.Get("/person/john");
  5537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5538. EXPECT_EQ(StatusCode::OK_200, res->status);
  5539. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5540. EXPECT_EQ("programmer", res->body);
  5541. }
  5542. TEST_F(ServerTest, PostMethod1) {
  5543. auto res = cli_.Get("/person/john1");
  5544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5545. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5546. res = cli_.Post("/person", "name=john1&note=coder",
  5547. "application/x-www-form-urlencoded");
  5548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5549. ASSERT_EQ(StatusCode::OK_200, res->status);
  5550. res = cli_.Get("/person/john1");
  5551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5552. ASSERT_EQ(StatusCode::OK_200, res->status);
  5553. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5554. ASSERT_EQ("coder", res->body);
  5555. }
  5556. TEST_F(ServerTest, PostMethod2) {
  5557. auto res = cli_.Get("/person/john2");
  5558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5559. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5560. Params params;
  5561. params.emplace("name", "john2");
  5562. params.emplace("note", "coder");
  5563. res = cli_.Post("/person", params);
  5564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5565. ASSERT_EQ(StatusCode::OK_200, res->status);
  5566. res = cli_.Get("/person/john2");
  5567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5568. ASSERT_EQ(StatusCode::OK_200, res->status);
  5569. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5570. ASSERT_EQ("coder", res->body);
  5571. }
  5572. TEST_F(ServerTest, PutMethod3) {
  5573. auto res = cli_.Get("/person/john3");
  5574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5575. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5576. Params params;
  5577. params.emplace("name", "john3");
  5578. params.emplace("note", "coder");
  5579. res = cli_.Put("/person", params);
  5580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5581. ASSERT_EQ(StatusCode::OK_200, res->status);
  5582. res = cli_.Get("/person/john3");
  5583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5584. ASSERT_EQ(StatusCode::OK_200, res->status);
  5585. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5586. ASSERT_EQ("coder", res->body);
  5587. }
  5588. TEST_F(ServerTest, DeleteMethod1) {
  5589. auto res = cli_.Get("/person/john4");
  5590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5591. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5592. Params params;
  5593. params.emplace("name", "john4");
  5594. params.emplace("note", "coder");
  5595. res = cli_.Post("/person", params);
  5596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5597. ASSERT_EQ(StatusCode::OK_200, res->status);
  5598. res = cli_.Get("/person/john4");
  5599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5600. ASSERT_EQ(StatusCode::OK_200, res->status);
  5601. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5602. ASSERT_EQ("coder", res->body);
  5603. Params delete_params;
  5604. delete_params.emplace("name", "john4");
  5605. res = cli_.Delete("/person", delete_params);
  5606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5607. ASSERT_EQ(StatusCode::OK_200, res->status);
  5608. ASSERT_EQ("DELETED", res->body);
  5609. res = cli_.Get("/person/john4");
  5610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5611. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5612. }
  5613. TEST_F(ServerTest, DeleteMethod2) {
  5614. auto res = cli_.Get("/person/john5");
  5615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5616. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5617. Params params;
  5618. params.emplace("name", "john5");
  5619. params.emplace("note", "developer");
  5620. res = cli_.Post("/person", params);
  5621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5622. ASSERT_EQ(StatusCode::OK_200, res->status);
  5623. res = cli_.Get("/person/john5");
  5624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5625. ASSERT_EQ(StatusCode::OK_200, res->status);
  5626. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5627. ASSERT_EQ("developer", res->body);
  5628. Params delete_params;
  5629. delete_params.emplace("name", "john5");
  5630. Headers headers;
  5631. headers.emplace("Custom-Header", "test-value");
  5632. res = cli_.Delete("/person", headers, delete_params);
  5633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5634. ASSERT_EQ(StatusCode::OK_200, res->status);
  5635. ASSERT_EQ("DELETED", res->body);
  5636. res = cli_.Get("/person/john5");
  5637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5638. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5639. }
  5640. TEST_F(ServerTest, DeleteMethod3) {
  5641. auto res = cli_.Get("/person/john6");
  5642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5643. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5644. Params params;
  5645. params.emplace("name", "john6");
  5646. params.emplace("note", "tester");
  5647. res = cli_.Post("/person", params);
  5648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5649. ASSERT_EQ(StatusCode::OK_200, res->status);
  5650. res = cli_.Get("/person/john6");
  5651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5652. ASSERT_EQ(StatusCode::OK_200, res->status);
  5653. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5654. ASSERT_EQ("tester", res->body);
  5655. Params delete_params;
  5656. delete_params.emplace("name", "john6");
  5657. Headers headers;
  5658. headers.emplace("Custom-Header", "test-value");
  5659. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5661. ASSERT_EQ(StatusCode::OK_200, res->status);
  5662. ASSERT_EQ("DELETED", res->body);
  5663. res = cli_.Get("/person/john6");
  5664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5665. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5666. }
  5667. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5668. Params params;
  5669. params.emplace("json", JSON_DATA);
  5670. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5672. ASSERT_EQ(StatusCode::OK_200, res->status);
  5673. ASSERT_EQ(JSON_DATA, res->body);
  5674. }
  5675. TEST_F(ServerTest, PostEmptyContent) {
  5676. auto res = cli_.Post("/empty", "", "text/plain");
  5677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5678. ASSERT_EQ(StatusCode::OK_200, res->status);
  5679. ASSERT_EQ("empty", res->body);
  5680. }
  5681. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5682. auto res = cli_.Post("/empty-no-content-type");
  5683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5684. ASSERT_EQ(StatusCode::OK_200, res->status);
  5685. ASSERT_EQ("empty-no-content-type", res->body);
  5686. }
  5687. TEST_F(ServerTest, PostPathOnly) {
  5688. auto res = cli_.Post("/path-only");
  5689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5690. ASSERT_EQ(StatusCode::OK_200, res->status);
  5691. ASSERT_EQ("path-only", res->body);
  5692. }
  5693. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5694. auto res = cli_.Post("/path-headers-only",
  5695. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5697. ASSERT_EQ(StatusCode::OK_200, res->status);
  5698. ASSERT_EQ("path-headers-only", res->body);
  5699. }
  5700. TEST_F(ServerTest, PostLarge) {
  5701. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5703. ASSERT_EQ(StatusCode::OK_200, res->status);
  5704. EXPECT_EQ(LARGE_DATA, res->body);
  5705. }
  5706. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5707. auto res = cli_.Put("/empty-no-content-type");
  5708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5709. ASSERT_EQ(StatusCode::OK_200, res->status);
  5710. ASSERT_EQ("empty-no-content-type", res->body);
  5711. }
  5712. TEST_F(ServerTest, GetMethodDir) {
  5713. auto res = cli_.Get("/dir/");
  5714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5715. EXPECT_EQ(StatusCode::OK_200, res->status);
  5716. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5717. auto body = R"(<html>
  5718. <head>
  5719. </head>
  5720. <body>
  5721. <a href="/dir/test.html">Test</a>
  5722. <a href="/hi">hi</a>
  5723. </body>
  5724. </html>
  5725. )";
  5726. EXPECT_EQ(body, res->body);
  5727. }
  5728. TEST_F(ServerTest, GetMethodDirTest) {
  5729. auto res = cli_.Get("/dir/test.html");
  5730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5731. EXPECT_EQ(StatusCode::OK_200, res->status);
  5732. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5733. EXPECT_EQ("test.html", res->body);
  5734. }
  5735. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5736. auto res = cli_.Get("/dir/../dir/test.html");
  5737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5738. EXPECT_EQ(StatusCode::OK_200, res->status);
  5739. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5740. EXPECT_EQ("test.html", res->body);
  5741. }
  5742. TEST_F(ServerTest, GetMethodInvalidPath) {
  5743. auto res = cli_.Get("/dir/../test.html");
  5744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5745. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5746. }
  5747. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5748. auto res = cli_.Get("/../www/dir/test.html");
  5749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5750. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5751. }
  5752. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5753. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5755. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5756. }
  5757. TEST_F(ServerTest, GetMethodDirMountTest) {
  5758. auto res = cli_.Get("/mount/dir/test.html");
  5759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5760. EXPECT_EQ(StatusCode::OK_200, res->status);
  5761. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5762. EXPECT_EQ("test.html", res->body);
  5763. }
  5764. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5765. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5767. EXPECT_EQ(StatusCode::OK_200, res->status);
  5768. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5769. EXPECT_EQ("test.html", res->body);
  5770. }
  5771. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5772. auto res = cli_.Get("/mount/dir/../test.html");
  5773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5774. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5775. }
  5776. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5777. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5779. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5780. }
  5781. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5782. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5784. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5785. }
  5786. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5787. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5789. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5790. }
  5791. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5792. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5794. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5795. }
  5796. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  5797. auto res = cli_.Get("/mount/dir");
  5798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5799. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5800. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5801. }
  5802. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  5803. auto res = cli_.Get("//dir");
  5804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5805. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5806. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5807. }
  5808. TEST_F(ServerTest, PostMethod303) {
  5809. auto res = cli_.Post("/1", "body", "text/plain");
  5810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5811. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5812. EXPECT_EQ("/2", res->get_header_value("Location"));
  5813. }
  5814. TEST_F(ServerTest, PostMethod303Redirect) {
  5815. cli_.set_follow_location(true);
  5816. auto res = cli_.Post("/1", "body", "text/plain");
  5817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5818. EXPECT_EQ(StatusCode::OK_200, res->status);
  5819. EXPECT_EQ("redirected.", res->body);
  5820. EXPECT_EQ("/2", res->location);
  5821. }
  5822. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5823. auto res = cli_.Get("/dir/test.abcde");
  5824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5825. EXPECT_EQ(StatusCode::OK_200, res->status);
  5826. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5827. EXPECT_EQ("abcde", res->body);
  5828. }
  5829. TEST_F(ServerTest, StaticFileRange) {
  5830. auto res =
  5831. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5833. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5834. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5835. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5836. EXPECT_EQ(true, res->has_header("Content-Range"));
  5837. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5838. EXPECT_EQ(std::string("cd"), res->body);
  5839. }
  5840. TEST_F(ServerTest, StaticFileRanges) {
  5841. auto res = cli_.Get("/dir/test.abcde",
  5842. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5844. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5845. EXPECT_TRUE(
  5846. res->get_header_value("Content-Type")
  5847. .find(
  5848. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5849. 0);
  5850. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5851. }
  5852. TEST_F(ServerTest, StaticFileRangeHead) {
  5853. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5855. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5856. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5857. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5858. EXPECT_EQ(true, res->has_header("Content-Range"));
  5859. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5860. }
  5861. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5862. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5864. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5865. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5866. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5867. EXPECT_EQ(true, res->has_header("Content-Range"));
  5868. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5869. res->get_header_value("Content-Range"));
  5870. EXPECT_EQ("LAST\n", res->body);
  5871. }
  5872. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5873. auto res =
  5874. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5876. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5877. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5878. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5879. EXPECT_EQ(true, res->has_header("Content-Range"));
  5880. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5881. }
  5882. TEST_F(ServerTest, StaticFileBigFile) {
  5883. auto res = cli_.Get("/dir/1MB.txt");
  5884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5885. EXPECT_EQ(StatusCode::OK_200, res->status);
  5886. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5887. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5888. }
  5889. TEST_F(ServerTest, InvalidBaseDirMount) {
  5890. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5891. }
  5892. TEST_F(ServerTest, Binary) {
  5893. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5894. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5895. "application/octet-stream");
  5896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5897. ASSERT_EQ(StatusCode::OK_200, res->status);
  5898. ASSERT_EQ(4U, res->body.size());
  5899. res = cli_.Put("/binary", binary.data(), binary.size(),
  5900. "application/octet-stream");
  5901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5902. ASSERT_EQ(StatusCode::OK_200, res->status);
  5903. ASSERT_EQ(4U, res->body.size());
  5904. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5905. "application/octet-stream");
  5906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5907. ASSERT_EQ(StatusCode::OK_200, res->status);
  5908. ASSERT_EQ(4U, res->body.size());
  5909. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5910. "application/octet-stream");
  5911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5912. ASSERT_EQ(StatusCode::OK_200, res->status);
  5913. ASSERT_EQ(4U, res->body.size());
  5914. }
  5915. TEST_F(ServerTest, BinaryString) {
  5916. auto binary = std::string("\x00\x01\x02\x03", 4);
  5917. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5919. ASSERT_EQ(StatusCode::OK_200, res->status);
  5920. ASSERT_EQ(4U, res->body.size());
  5921. res = cli_.Put("/binary", binary, "application/octet-stream");
  5922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5923. ASSERT_EQ(StatusCode::OK_200, res->status);
  5924. ASSERT_EQ(4U, res->body.size());
  5925. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5927. ASSERT_EQ(StatusCode::OK_200, res->status);
  5928. ASSERT_EQ(4U, res->body.size());
  5929. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5931. ASSERT_EQ(StatusCode::OK_200, res->status);
  5932. ASSERT_EQ(4U, res->body.size());
  5933. }
  5934. TEST_F(ServerTest, EmptyRequest) {
  5935. auto res = cli_.Get("");
  5936. ASSERT_TRUE(!res);
  5937. EXPECT_EQ(Error::Connection, res.error());
  5938. }
  5939. TEST_F(ServerTest, LongRequest) {
  5940. std::string request;
  5941. for (size_t i = 0; i < 545; i++) {
  5942. request += "/TooLongRequest";
  5943. }
  5944. request += "OK";
  5945. auto res = cli_.Get(request.c_str());
  5946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5947. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5948. }
  5949. TEST_F(ServerTest, TooLongRequest) {
  5950. std::string request;
  5951. for (size_t i = 0; i < 546; i++) {
  5952. request += "/TooLongRequest";
  5953. }
  5954. request += "_NG";
  5955. auto start = std::chrono::high_resolution_clock::now();
  5956. cli_.set_keep_alive(true);
  5957. auto res = cli_.Get(request.c_str());
  5958. auto end = std::chrono::high_resolution_clock::now();
  5959. auto elapsed =
  5960. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5961. .count();
  5962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5963. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5964. EXPECT_LE(elapsed, 1000);
  5965. EXPECT_EQ("close", res->get_header_value("Connection"));
  5966. EXPECT_FALSE(cli_.is_socket_open());
  5967. }
  5968. TEST_F(ServerTest, AlmostTooLongRequest) {
  5969. // test for #2046 - URI length check shouldn't include other content on req
  5970. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5971. // leading /, space, HTTP/1.1)
  5972. std::string request =
  5973. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5974. auto res = cli_.Get(request.c_str());
  5975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5976. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5977. }
  5978. TEST_F(ServerTest, LongHeader) {
  5979. Request req;
  5980. req.method = "GET";
  5981. req.path = "/hi";
  5982. std::string host_and_port;
  5983. host_and_port += HOST;
  5984. host_and_port += ":";
  5985. host_and_port += std::to_string(PORT);
  5986. req.headers.emplace("Host", host_and_port.c_str());
  5987. req.headers.emplace("Accept", "*/*");
  5988. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5989. req.headers.emplace(
  5990. "Header-Name",
  5991. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5992. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5993. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5994. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5995. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5996. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5997. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5998. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5999. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6000. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6001. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6002. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6003. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6004. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6005. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6006. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6007. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6008. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6009. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6010. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6011. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6012. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6013. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6014. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6015. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6016. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6017. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6018. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6019. "@@@@@@@@@@@@@@@@");
  6020. auto res = std::make_shared<Response>();
  6021. auto error = Error::Success;
  6022. auto ret = cli_.send(req, *res, error);
  6023. ASSERT_TRUE(ret);
  6024. EXPECT_EQ(StatusCode::OK_200, res->status);
  6025. }
  6026. TEST_F(ServerTest, LongQueryValue) {
  6027. auto start = std::chrono::high_resolution_clock::now();
  6028. cli_.set_keep_alive(true);
  6029. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6030. auto end = std::chrono::high_resolution_clock::now();
  6031. auto elapsed =
  6032. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6033. .count();
  6034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6035. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6036. EXPECT_LE(elapsed, 1000);
  6037. EXPECT_EQ("close", res->get_header_value("Connection"));
  6038. EXPECT_FALSE(cli_.is_socket_open());
  6039. }
  6040. TEST_F(ServerTest, TooLongQueryValue) {
  6041. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6042. ASSERT_FALSE(res);
  6043. EXPECT_EQ(Error::Read, res.error());
  6044. }
  6045. TEST_F(ServerTest, TooLongHeader) {
  6046. Request req;
  6047. req.method = "GET";
  6048. req.path = "/hi";
  6049. std::string host_and_port;
  6050. host_and_port += HOST;
  6051. host_and_port += ":";
  6052. host_and_port += std::to_string(PORT);
  6053. req.headers.emplace("Host", host_and_port.c_str());
  6054. req.headers.emplace("Accept", "*/*");
  6055. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6056. req.headers.emplace(
  6057. "Header-Name",
  6058. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6059. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6060. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6061. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6062. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6063. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6064. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6065. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6066. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6067. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6068. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6069. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6070. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6071. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6072. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6073. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6074. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6075. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6076. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6077. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6078. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6079. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6080. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6081. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6082. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6083. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6084. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6085. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6086. "@@@@@@@@@@@@@@@@@");
  6087. auto res = std::make_shared<Response>();
  6088. auto error = Error::Success;
  6089. auto ret = cli_.send(req, *res, error);
  6090. ASSERT_TRUE(ret);
  6091. EXPECT_EQ(StatusCode::OK_200, res->status);
  6092. }
  6093. TEST_F(ServerTest, HeaderCountAtLimit) {
  6094. // Test with headers just under the 100 limit
  6095. httplib::Headers headers;
  6096. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6097. // This should keep us just under the 100 header limit
  6098. for (int i = 0; i < 95; i++) {
  6099. std::string name = "X-Test-Header-" + std::to_string(i);
  6100. std::string value = "value" + std::to_string(i);
  6101. headers.emplace(name, value);
  6102. }
  6103. // This should work fine as we're under the limit
  6104. auto res = cli_.Get("/hi", headers);
  6105. EXPECT_TRUE(res);
  6106. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6107. }
  6108. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6109. // Test with many headers to exceed the 100 limit
  6110. httplib::Headers headers;
  6111. // Add 150 headers to definitely exceed the 100 limit
  6112. for (int i = 0; i < 150; i++) {
  6113. std::string name = "X-Test-Header-" + std::to_string(i);
  6114. std::string value = "value" + std::to_string(i);
  6115. headers.emplace(name, value);
  6116. }
  6117. // This should fail due to exceeding header count limit
  6118. cli_.set_keep_alive(true);
  6119. auto res = cli_.Get("/hi", headers);
  6120. // The server should respond with 400 Bad Request
  6121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6122. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6123. EXPECT_EQ("close", res->get_header_value("Connection"));
  6124. EXPECT_FALSE(cli_.is_socket_open());
  6125. }
  6126. TEST_F(ServerTest, PercentEncoding) {
  6127. auto res = cli_.Get("/e%6edwith%");
  6128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6129. EXPECT_EQ(StatusCode::OK_200, res->status);
  6130. }
  6131. TEST_F(ServerTest, PercentEncodingUnicode) {
  6132. auto res = cli_.Get("/e%u006edwith%");
  6133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6134. EXPECT_EQ(StatusCode::OK_200, res->status);
  6135. }
  6136. TEST_F(ServerTest, InvalidPercentEncoding) {
  6137. auto res = cli_.Get("/%endwith%");
  6138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6139. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6140. }
  6141. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6142. auto res = cli_.Get("/%uendwith%");
  6143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6144. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6145. }
  6146. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6147. auto res = cli_.Get("/hello?aaa=bbb%");
  6148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6149. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6150. }
  6151. TEST_F(ServerTest, PlusSignEncoding) {
  6152. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6154. EXPECT_EQ(StatusCode::OK_200, res->status);
  6155. EXPECT_EQ("a +b", res->body);
  6156. }
  6157. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6158. // This test simulates a potential DoS attack using many headers
  6159. // to verify our security fix prevents memory exhaustion
  6160. httplib::Headers attack_headers;
  6161. // Attempt to add many headers like an attacker would (200 headers to far
  6162. // exceed limit)
  6163. for (int i = 0; i < 200; i++) {
  6164. std::string name = "X-Attack-Header-" + std::to_string(i);
  6165. std::string value = "attack_payload_" + std::to_string(i);
  6166. attack_headers.emplace(name, value);
  6167. }
  6168. // Try to POST with excessive headers
  6169. cli_.set_keep_alive(true);
  6170. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6171. // Should either fail or return 400 Bad Request due to security limit
  6172. if (res) {
  6173. // If we get a response, it should be 400 Bad Request
  6174. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6175. EXPECT_EQ("close", res->get_header_value("Connection"));
  6176. }
  6177. EXPECT_FALSE(cli_.is_socket_open());
  6178. }
  6179. TEST_F(ServerTest, MultipartFormData) {
  6180. UploadFormDataItems items = {
  6181. {"text1", "text default", "", ""},
  6182. {"text2", "aωb", "", ""},
  6183. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6184. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6185. {"file3", "", "", "application/octet-stream"},
  6186. {"file4", "", "", " application/json tmp-string "}};
  6187. auto res = cli_.Post("/multipart", items);
  6188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6189. EXPECT_EQ(StatusCode::OK_200, res->status);
  6190. }
  6191. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6192. UploadFormDataItems items = {
  6193. {"text", "default text", "", ""},
  6194. {"multi_text1", "aaaaa", "", ""},
  6195. {"multi_text1", "bbbbb", "", ""},
  6196. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6197. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6198. "application/json"},
  6199. };
  6200. auto res = cli_.Post("/multipart/multi_file_values", items);
  6201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6202. EXPECT_EQ(StatusCode::OK_200, res->status);
  6203. }
  6204. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6205. auto res = cli_.Get("/hi");
  6206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6207. EXPECT_EQ(StatusCode::OK_200, res->status);
  6208. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6209. EXPECT_EQ("Hello World!", res->body);
  6210. }
  6211. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6212. Request req;
  6213. req.method = "POST";
  6214. req.path = "/chunked";
  6215. std::string host_and_port;
  6216. host_and_port += HOST;
  6217. host_and_port += ":";
  6218. host_and_port += std::to_string(PORT);
  6219. req.headers.emplace("Host", host_and_port.c_str());
  6220. req.headers.emplace("Accept", "*/*");
  6221. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6222. req.headers.emplace("Content-Type", "text/plain");
  6223. req.headers.emplace("Content-Length", "0");
  6224. req.headers.emplace(
  6225. "Transfer-Encoding",
  6226. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6227. // Client does not chunk, so make a chunked body manually.
  6228. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6229. auto res = std::make_shared<Response>();
  6230. auto error = Error::Success;
  6231. auto ret = cli_.send(req, *res, error);
  6232. ASSERT_TRUE(ret);
  6233. EXPECT_EQ(StatusCode::OK_200, res->status);
  6234. }
  6235. template <typename ClientT>
  6236. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6237. int expected_status) {
  6238. Request req;
  6239. req.method = "POST";
  6240. req.path = "/chunked";
  6241. std::string host_and_port;
  6242. host_and_port += HOST;
  6243. host_and_port += ":";
  6244. host_and_port += std::to_string(PORT);
  6245. req.headers.emplace("Host", host_and_port.c_str());
  6246. req.headers.emplace("Content-Length", "0");
  6247. req.headers.emplace("Transfer-Encoding", "chunked");
  6248. req.body = body;
  6249. auto res = std::make_shared<Response>();
  6250. auto error = Error::Success;
  6251. ASSERT_TRUE(cli.send(req, *res, error));
  6252. EXPECT_EQ(expected_status, res->status);
  6253. }
  6254. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6255. // rather than treat them as valid lengths.
  6256. template <typename ClientT>
  6257. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6258. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6259. }
  6260. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6261. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6262. }
  6263. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6264. expect_chunked_body_rejected(
  6265. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6266. }
  6267. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6268. // chunk-size line carries no CR, LF or other control character ahead of its
  6269. // terminator. Such a line must be refused rather than read as extension text.
  6270. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6271. expect_chunked_body_rejected(
  6272. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6273. }
  6274. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6275. expect_chunked_body_rejected(
  6276. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6277. }
  6278. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6279. expect_chunked_body_rejected(
  6280. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6281. }
  6282. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6283. // The literal stays split: a hex escape consumes every hex digit that
  6284. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6285. expect_chunked_body_rejected(
  6286. cli_, "4;a\x01"
  6287. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6288. }
  6289. TEST_F(ServerTest, AcceptsChunkExtension) {
  6290. expect_chunked_body_status(cli_,
  6291. "4;name=value\r\ndech\r\n"
  6292. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6293. "0;last\r\n\r\n",
  6294. StatusCode::OK_200);
  6295. }
  6296. TEST_F(ServerTest, GetStreamed2) {
  6297. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6299. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6300. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6301. EXPECT_EQ(true, res->has_header("Content-Range"));
  6302. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6303. EXPECT_EQ(std::string("ab"), res->body);
  6304. }
  6305. TEST_F(ServerTest, GetStreamed) {
  6306. auto res = cli_.Get("/streamed");
  6307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6308. EXPECT_EQ(StatusCode::OK_200, res->status);
  6309. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6310. EXPECT_EQ(std::string("aaabbb"), res->body);
  6311. }
  6312. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6313. auto res = cli_.Get("/streamed-without-length",
  6314. Headers{make_range_header({{0, -1}})});
  6315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6316. EXPECT_EQ(StatusCode::OK_200, res->status);
  6317. EXPECT_EQ(false, res->has_header("Content-Length"));
  6318. EXPECT_EQ(false, res->has_header("Content-Range"));
  6319. EXPECT_EQ(std::string("abcdefg"), res->body);
  6320. }
  6321. TEST_F(ServerTest, GetStreamedWithRange1) {
  6322. auto res =
  6323. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6325. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6326. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6327. EXPECT_EQ(true, res->has_header("Content-Range"));
  6328. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6329. EXPECT_EQ(std::string("def"), res->body);
  6330. }
  6331. TEST_F(ServerTest, GetStreamedWithRange2) {
  6332. auto res =
  6333. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6335. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6336. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6337. EXPECT_EQ(true, res->has_header("Content-Range"));
  6338. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6339. EXPECT_EQ(std::string("bcdefg"), res->body);
  6340. }
  6341. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6342. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6344. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6345. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6346. EXPECT_EQ(true, res->has_header("Content-Range"));
  6347. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6348. EXPECT_EQ(std::string("efg"), res->body);
  6349. }
  6350. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6351. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6352. // the entire representation.
  6353. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6354. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6356. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6357. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6358. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6359. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6360. }
  6361. }
  6362. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6363. auto res =
  6364. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6366. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6367. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6368. EXPECT_EQ(false, res->has_header("Content-Range"));
  6369. EXPECT_EQ(0U, res->body.size());
  6370. }
  6371. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6372. // Only a 206 is served as a partial representation. Under any other status
  6373. // `apply_ranges()` reported the full content length, so the body must match
  6374. // that header, and the content provider must never be asked for an offset
  6375. // outside the representation.
  6376. auto check = [&](int status, const char *range) {
  6377. auto path =
  6378. std::string("/streamed-with-range?status=") + std::to_string(status);
  6379. auto ctx = path + " Range: " + range;
  6380. auto res = cli_.Get(path, Headers{{"Range", range}});
  6381. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6382. EXPECT_EQ(status, res->status) << ctx;
  6383. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6384. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6385. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6386. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6387. };
  6388. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6389. check(403, "bytes=3-5");
  6390. // The offset is far past the representation.
  6391. check(403, "bytes=100000-100200");
  6392. // `first_pos` is still -1 here, and the bounds asserts in
  6393. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6394. check(403, "bytes=-3");
  6395. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6396. // multipart branch would have written one that is empty.
  6397. check(403, "bytes=1-2, 4-5");
  6398. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6399. // covers the whole representation.
  6400. check(200, "bytes=3-5");
  6401. check(200, "bytes=1-2, 4-5");
  6402. }
  6403. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6404. auto res =
  6405. cli_.Get("/streamed-with-range",
  6406. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6407. "92233720368547758079223372036854775807"}});
  6408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6409. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6410. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6411. EXPECT_EQ(false, res->has_header("Content-Range"));
  6412. EXPECT_EQ(0U, res->body.size());
  6413. }
  6414. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6415. auto res = cli_.Get(
  6416. "/with-range",
  6417. Headers{{"Range",
  6418. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6419. {"Accept-Encoding", ""}});
  6420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6421. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6422. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6423. EXPECT_EQ(true, res->has_header("Content-Range"));
  6424. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6425. EXPECT_EQ(std::string("abcdefg"), res->body);
  6426. }
  6427. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6428. auto res = cli_.Get("/with-range", Headers{
  6429. {"Range", "bytes=0-"},
  6430. {"Accept-Encoding", ""},
  6431. });
  6432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6433. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6434. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6435. EXPECT_EQ(true, res->has_header("Content-Range"));
  6436. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6437. EXPECT_EQ(std::string("abcdefg"), res->body);
  6438. }
  6439. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6440. auto res = cli_.Get("/streamed-with-range",
  6441. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6443. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6444. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6445. EXPECT_EQ(false, res->has_header("Content-Range"));
  6446. EXPECT_EQ(267U, res->body.size());
  6447. // Check that both range contents are present
  6448. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6449. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6450. // Check that Content-Range headers are present for both ranges
  6451. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6452. std::string::npos);
  6453. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6454. std::string::npos);
  6455. }
  6456. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6457. Ranges ranges;
  6458. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6459. ranges.emplace_back(0, -1);
  6460. }
  6461. auto res = cli_.Get("/streamed-with-range?error",
  6462. Headers{{make_range_header(ranges)}});
  6463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6464. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6465. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6466. EXPECT_EQ(false, res->has_header("Content-Range"));
  6467. EXPECT_EQ(0U, res->body.size());
  6468. }
  6469. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6470. auto res = cli_.Get("/streamed-with-range",
  6471. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6473. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6474. EXPECT_EQ(5U, res->body.size());
  6475. // Check that overlapping ranges are coalesced into a single range
  6476. EXPECT_EQ("bcdef", res->body);
  6477. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6478. // Should be single range, not multipart
  6479. EXPECT_TRUE(res->has_header("Content-Range"));
  6480. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6481. }
  6482. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6483. auto res = cli_.Get("/streamed-with-range",
  6484. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6486. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6487. EXPECT_EQ(268U, res->body.size());
  6488. // Check that both range contents are present
  6489. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6490. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6491. // Check that Content-Range headers are present for both ranges
  6492. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6493. std::string::npos);
  6494. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6495. std::string::npos);
  6496. }
  6497. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6498. auto res = cli_.Get("/streamed-with-range",
  6499. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6501. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6502. EXPECT_EQ(269U, res->body.size());
  6503. // Check that both duplicate range contents are present
  6504. size_t first_abc = res->body.find("abc\r\n");
  6505. EXPECT_TRUE(first_abc != std::string::npos);
  6506. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6507. EXPECT_TRUE(second_abc != std::string::npos);
  6508. // Check that Content-Range headers are present for both ranges
  6509. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6510. EXPECT_TRUE(first_range != std::string::npos);
  6511. size_t second_range =
  6512. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6513. EXPECT_TRUE(second_range != std::string::npos);
  6514. }
  6515. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6516. auto res =
  6517. cli_.Get("/streamed-with-range?error",
  6518. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6520. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6521. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6522. EXPECT_EQ(false, res->has_header("Content-Range"));
  6523. EXPECT_EQ(0U, res->body.size());
  6524. }
  6525. TEST_F(ServerTest, GetStreamedEndless) {
  6526. uint64_t offset = 0;
  6527. auto res = cli_.Get("/streamed-cancel",
  6528. [&](const char * /*data*/, uint64_t data_length) {
  6529. if (offset < 100) {
  6530. offset += data_length;
  6531. return true;
  6532. }
  6533. return false;
  6534. });
  6535. ASSERT_TRUE(!res);
  6536. EXPECT_EQ(Error::Canceled, res.error());
  6537. }
  6538. TEST_F(ServerTest, ClientStop) {
  6539. std::atomic_size_t count{4};
  6540. std::vector<std::thread> threads;
  6541. for (auto i = count.load(); i != 0; --i) {
  6542. threads.emplace_back([&]() {
  6543. auto res = cli_.Get("/streamed-cancel",
  6544. [&](const char *, uint64_t) { return true; });
  6545. --count;
  6546. ASSERT_TRUE(!res);
  6547. EXPECT_TRUE(res.error() == Error::Canceled ||
  6548. res.error() == Error::Read || res.error() == Error::Write);
  6549. });
  6550. }
  6551. std::this_thread::sleep_for(std::chrono::seconds(2));
  6552. while (count != 0) {
  6553. cli_.stop();
  6554. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6555. }
  6556. for (auto &t : threads) {
  6557. t.join();
  6558. }
  6559. }
  6560. TEST_F(ServerTest, GetWithRange1) {
  6561. auto res = cli_.Get("/with-range", Headers{
  6562. make_range_header({{3, 5}}),
  6563. {"Accept-Encoding", ""},
  6564. });
  6565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6566. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6567. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6568. EXPECT_EQ(true, res->has_header("Content-Range"));
  6569. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6570. EXPECT_EQ(std::string("def"), res->body);
  6571. }
  6572. TEST_F(ServerTest, GetWithRange2) {
  6573. auto res = cli_.Get("/with-range", Headers{
  6574. make_range_header({{1, -1}}),
  6575. {"Accept-Encoding", ""},
  6576. });
  6577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6578. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6579. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6580. EXPECT_EQ(true, res->has_header("Content-Range"));
  6581. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6582. EXPECT_EQ(std::string("bcdefg"), res->body);
  6583. }
  6584. TEST_F(ServerTest, GetWithRange3) {
  6585. auto res = cli_.Get("/with-range", Headers{
  6586. make_range_header({{0, 0}}),
  6587. {"Accept-Encoding", ""},
  6588. });
  6589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6590. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6591. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6592. EXPECT_EQ(true, res->has_header("Content-Range"));
  6593. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6594. EXPECT_EQ(std::string("a"), res->body);
  6595. }
  6596. TEST_F(ServerTest, GetWithRange4) {
  6597. auto res = cli_.Get("/with-range", Headers{
  6598. make_range_header({{-1, 2}}),
  6599. {"Accept-Encoding", ""},
  6600. });
  6601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6602. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6603. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6604. EXPECT_EQ(true, res->has_header("Content-Range"));
  6605. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6606. EXPECT_EQ(std::string("fg"), res->body);
  6607. }
  6608. TEST_F(ServerTest, GetWithRange5) {
  6609. auto res = cli_.Get("/with-range", Headers{
  6610. make_range_header({{0, 5}}),
  6611. {"Accept-Encoding", ""},
  6612. });
  6613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6614. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6615. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6616. EXPECT_EQ(true, res->has_header("Content-Range"));
  6617. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6618. EXPECT_EQ(std::string("abcdef"), res->body);
  6619. }
  6620. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6621. auto res =
  6622. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6624. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6625. }
  6626. TEST_F(ServerTest, GetWithRangeMultipart) {
  6627. auto res =
  6628. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6630. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6631. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6632. EXPECT_EQ(false, res->has_header("Content-Range"));
  6633. EXPECT_EQ(267U, res->body.size());
  6634. }
  6635. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6636. auto res = cli_.Get("/with-range",
  6637. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6639. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6640. }
  6641. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6642. auto res = cli_.Get("/with-range-customized-response",
  6643. Headers{{make_range_header({{1, 2}})}});
  6644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6645. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6646. EXPECT_EQ(true, res->has_header("Content-Length"));
  6647. EXPECT_EQ(false, res->has_header("Content-Range"));
  6648. EXPECT_EQ(JSON_DATA, res->body);
  6649. }
  6650. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6651. auto res = cli_.Get("/with-range-customized-response",
  6652. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6654. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6655. EXPECT_EQ(true, res->has_header("Content-Length"));
  6656. EXPECT_EQ(false, res->has_header("Content-Range"));
  6657. EXPECT_EQ(JSON_DATA, res->body);
  6658. }
  6659. TEST_F(ServerTest, Issue1772) {
  6660. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6662. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6663. }
  6664. TEST_F(ServerTest, Issue609) {
  6665. auto res = cli_.Delete("/issue609");
  6666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6667. EXPECT_EQ(StatusCode::OK_200, res->status);
  6668. EXPECT_EQ(std::string("ok"), res->body);
  6669. }
  6670. TEST_F(ServerTest, GetStreamedChunked) {
  6671. auto res = cli_.Get("/streamed-chunked");
  6672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6673. EXPECT_EQ(StatusCode::OK_200, res->status);
  6674. EXPECT_EQ(std::string("123456789"), res->body);
  6675. }
  6676. TEST_F(ServerTest, GetStreamedChunked2) {
  6677. auto res = cli_.Get("/streamed-chunked2");
  6678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6679. EXPECT_EQ(StatusCode::OK_200, res->status);
  6680. EXPECT_EQ(std::string("123456789"), res->body);
  6681. }
  6682. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6683. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6685. EXPECT_EQ(StatusCode::OK_200, res->status);
  6686. EXPECT_EQ(std::string("123456789"), res->body);
  6687. EXPECT_TRUE(res->has_header("Trailer"));
  6688. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6689. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6690. // Trailers are now stored separately from headers (security fix)
  6691. EXPECT_EQ(2U, res->trailers.size());
  6692. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6693. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6694. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6695. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6696. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6697. // Verify trailers are NOT in headers (security verification)
  6698. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6699. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6700. }
  6701. TEST_F(ServerTest, LargeChunkedPost) {
  6702. Request req;
  6703. req.method = "POST";
  6704. req.path = "/large-chunked";
  6705. std::string host_and_port;
  6706. host_and_port += HOST;
  6707. host_and_port += ":";
  6708. host_and_port += std::to_string(PORT);
  6709. req.headers.emplace("Host", host_and_port.c_str());
  6710. req.headers.emplace("Accept", "*/*");
  6711. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6712. req.headers.emplace("Content-Type", "text/plain");
  6713. req.headers.emplace("Content-Length", "0");
  6714. req.headers.emplace("Transfer-Encoding", "chunked");
  6715. std::string long_string(30 * 1024u, 'a');
  6716. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6717. // Attempt to make a large enough post to exceed OS buffers, to test that
  6718. // the server handles short reads if the full chunk data isn't available.
  6719. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6720. auto res = std::make_shared<Response>();
  6721. auto error = Error::Success;
  6722. auto ret = cli_.send(req, *res, error);
  6723. ASSERT_TRUE(ret);
  6724. EXPECT_EQ(StatusCode::OK_200, res->status);
  6725. }
  6726. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6727. auto res = cli_.Get("/remote_addr");
  6728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6729. EXPECT_EQ(StatusCode::OK_200, res->status);
  6730. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6731. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6732. }
  6733. TEST_F(ServerTest, GetMethodLocalAddr) {
  6734. auto res = cli_.Get("/local_addr");
  6735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6736. EXPECT_EQ(StatusCode::OK_200, res->status);
  6737. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6738. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6739. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6740. }
  6741. TEST_F(ServerTest, HTTPResponseSplitting) {
  6742. auto res = cli_.Get("/http_response_splitting");
  6743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6744. EXPECT_EQ(StatusCode::OK_200, res->status);
  6745. }
  6746. TEST_F(ServerTest, SlowRequest) {
  6747. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6748. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6749. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6750. }
  6751. #if 0
  6752. TEST_F(ServerTest, SlowPost) {
  6753. char buffer[64 * 1024];
  6754. memset(buffer, 0x42, sizeof(buffer));
  6755. auto res = cli_.Post(
  6756. "/slowpost", 64 * 1024 * 1024,
  6757. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6758. auto ret = sink.write(buffer, sizeof(buffer));
  6759. EXPECT_TRUE(ret);
  6760. return true;
  6761. },
  6762. "text/plain");
  6763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6764. EXPECT_EQ(StatusCode::OK_200, res->status);
  6765. }
  6766. TEST_F(ServerTest, SlowPostFail) {
  6767. char buffer[64 * 1024];
  6768. memset(buffer, 0x42, sizeof(buffer));
  6769. cli_.set_write_timeout(std::chrono::seconds(0));
  6770. auto res = cli_.Post(
  6771. "/slowpost", 64 * 1024 * 1024,
  6772. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6773. sink.write(buffer, sizeof(buffer));
  6774. return true;
  6775. },
  6776. "text/plain");
  6777. ASSERT_TRUE(!res);
  6778. EXPECT_EQ(Error::Write, res.error());
  6779. }
  6780. #endif
  6781. TEST_F(ServerTest, Put) {
  6782. auto res = cli_.Put("/put", "PUT", "text/plain");
  6783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6784. EXPECT_EQ(StatusCode::OK_200, res->status);
  6785. EXPECT_EQ("PUT", res->body);
  6786. }
  6787. TEST_F(ServerTest, PutWithContentProvider) {
  6788. auto res = cli_.Put(
  6789. "/put", 3,
  6790. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6791. sink.os << "PUT";
  6792. return true;
  6793. },
  6794. "text/plain");
  6795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6796. EXPECT_EQ(StatusCode::OK_200, res->status);
  6797. EXPECT_EQ("PUT", res->body);
  6798. }
  6799. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6800. auto res = cli_.Post(
  6801. "/post", 42,
  6802. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6803. return false;
  6804. },
  6805. "text/plain");
  6806. ASSERT_TRUE(!res);
  6807. EXPECT_EQ(Error::Canceled, res.error());
  6808. }
  6809. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6810. auto res = cli_.Put(
  6811. "/put",
  6812. [](size_t /*offset*/, DataSink &sink) {
  6813. sink.os << "PUT";
  6814. sink.done();
  6815. return true;
  6816. },
  6817. "text/plain");
  6818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6819. EXPECT_EQ(StatusCode::OK_200, res->status);
  6820. EXPECT_EQ("PUT", res->body);
  6821. }
  6822. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6823. auto res = cli_.Post(
  6824. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6825. "text/plain");
  6826. ASSERT_TRUE(!res);
  6827. EXPECT_EQ(Error::Canceled, res.error());
  6828. }
  6829. TEST_F(ServerTest, PostLoopBack) {
  6830. std::string body;
  6831. auto res = cli_.Post(
  6832. "/post-loopback", 9,
  6833. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6834. EXPECT_EQ(9u, length);
  6835. sink.write("123", 3);
  6836. sink.write("456", 3);
  6837. sink.write("789", 3);
  6838. return true;
  6839. },
  6840. "text/plain",
  6841. [&body](const char *data, size_t data_length) {
  6842. body.append(data, data_length);
  6843. return true;
  6844. });
  6845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6846. EXPECT_EQ(StatusCode::OK_200, res->status);
  6847. EXPECT_EQ("123456789", body);
  6848. }
  6849. TEST_F(ServerTest, PutLoopBack) {
  6850. std::string body;
  6851. auto res = cli_.Put(
  6852. "/put-loopback", 9,
  6853. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6854. EXPECT_EQ(9u, length);
  6855. sink.write("123", 3);
  6856. sink.write("456", 3);
  6857. sink.write("789", 3);
  6858. return true;
  6859. },
  6860. "text/plain",
  6861. [&body](const char *data, size_t data_length) {
  6862. body.append(data, data_length);
  6863. return true;
  6864. });
  6865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6866. EXPECT_EQ(StatusCode::OK_200, res->status);
  6867. EXPECT_EQ("123456789", body);
  6868. }
  6869. TEST_F(ServerTest, PatchLoopBack) {
  6870. std::string body;
  6871. auto res = cli_.Patch(
  6872. "/patch-loopback", 9,
  6873. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6874. EXPECT_EQ(9u, length);
  6875. sink.write("123", 3);
  6876. sink.write("456", 3);
  6877. sink.write("789", 3);
  6878. return true;
  6879. },
  6880. "text/plain",
  6881. [&body](const char *data, size_t data_length) {
  6882. body.append(data, data_length);
  6883. return true;
  6884. });
  6885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6886. EXPECT_EQ(StatusCode::OK_200, res->status);
  6887. EXPECT_EQ("123456789", body);
  6888. }
  6889. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6890. std::string body;
  6891. auto res = cli_.Post(
  6892. "/post-loopback",
  6893. [](size_t /*offset*/, DataSink &sink) {
  6894. sink.write("123", 3);
  6895. sink.write("456", 3);
  6896. sink.write("789", 3);
  6897. sink.done();
  6898. return true;
  6899. },
  6900. "text/plain",
  6901. [&body](const char *data, size_t data_length) {
  6902. body.append(data, data_length);
  6903. return true;
  6904. });
  6905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6906. EXPECT_EQ(StatusCode::OK_200, res->status);
  6907. EXPECT_EQ("123456789", body);
  6908. }
  6909. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6910. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6911. cli_.set_compress(true);
  6912. auto res = cli_.Put(
  6913. "/put", 3,
  6914. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6915. sink.os << "PUT";
  6916. return true;
  6917. },
  6918. "text/plain");
  6919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6920. EXPECT_EQ(StatusCode::OK_200, res->status);
  6921. EXPECT_EQ("PUT", res->body);
  6922. }
  6923. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6924. cli_.set_compress(true);
  6925. auto res = cli_.Post(
  6926. "/post", 42,
  6927. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6928. return false;
  6929. },
  6930. "text/plain");
  6931. ASSERT_TRUE(!res);
  6932. EXPECT_EQ(Error::Canceled, res.error());
  6933. }
  6934. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6935. cli_.set_compress(true);
  6936. auto res = cli_.Put(
  6937. "/put",
  6938. [](size_t /*offset*/, DataSink &sink) {
  6939. sink.os << "PUT";
  6940. sink.done();
  6941. return true;
  6942. },
  6943. "text/plain");
  6944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6945. EXPECT_EQ(StatusCode::OK_200, res->status);
  6946. EXPECT_EQ("PUT", res->body);
  6947. }
  6948. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6949. cli_.set_compress(true);
  6950. auto res = cli_.Post(
  6951. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6952. "text/plain");
  6953. ASSERT_TRUE(!res);
  6954. EXPECT_EQ(Error::Canceled, res.error());
  6955. }
  6956. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6957. cli_.set_compress(true);
  6958. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6960. EXPECT_EQ(StatusCode::OK_200, res->status);
  6961. EXPECT_EQ(LARGE_DATA, res->body);
  6962. }
  6963. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6964. #ifdef CPPHTTPLIB_SSL_ENABLED
  6965. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6966. Client cli(s.c_str());
  6967. cli.enable_server_certificate_verification(false);
  6968. #else
  6969. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6970. Client cli(s.c_str());
  6971. #endif
  6972. cli.set_compress(true);
  6973. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6975. EXPECT_EQ(StatusCode::OK_200, res->status);
  6976. EXPECT_EQ(LARGE_DATA, res->body);
  6977. // The compressed size should be less than a 10th of the original. May vary
  6978. // depending on the zlib library.
  6979. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6980. static_cast<uint64_t>(10 * 1024 * 1024));
  6981. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6982. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6983. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6984. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6985. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6986. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6987. #endif
  6988. }
  6989. TEST_F(ServerTest, PutContentWithDeflate) {
  6990. cli_.set_compress(false);
  6991. Headers headers;
  6992. headers.emplace("Content-Encoding", "deflate");
  6993. // PUT in deflate format:
  6994. auto res = cli_.Put("/put", headers,
  6995. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6997. EXPECT_EQ(StatusCode::OK_200, res->status);
  6998. EXPECT_EQ("PUT", res->body);
  6999. }
  7000. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7001. Headers headers;
  7002. headers.emplace("Accept-Encoding", "gzip, deflate");
  7003. auto res = cli_.Get("/streamed-chunked", headers);
  7004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7005. EXPECT_EQ(StatusCode::OK_200, res->status);
  7006. EXPECT_EQ(std::string("123456789"), res->body);
  7007. }
  7008. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7009. Headers headers;
  7010. headers.emplace("Accept-Encoding", "gzip, deflate");
  7011. auto res = cli_.Get("/streamed-chunked2", headers);
  7012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7013. EXPECT_EQ(StatusCode::OK_200, res->status);
  7014. EXPECT_EQ(std::string("123456789"), res->body);
  7015. }
  7016. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7017. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7019. EXPECT_EQ(StatusCode::OK_200, res->status);
  7020. }
  7021. TEST(GzipDecompressor, ChunkedDecompression) {
  7022. std::string data;
  7023. for (size_t i = 0; i < 32 * 1024; ++i) {
  7024. data.push_back(static_cast<char>('a' + i % 26));
  7025. }
  7026. std::string compressed_data;
  7027. {
  7028. httplib::detail::gzip_compressor compressor;
  7029. bool result = compressor.compress(
  7030. data.data(), data.size(),
  7031. /*last=*/true,
  7032. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7033. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7034. compressed_data_size);
  7035. return true;
  7036. });
  7037. ASSERT_TRUE(result);
  7038. }
  7039. std::string decompressed_data;
  7040. {
  7041. httplib::detail::gzip_decompressor decompressor;
  7042. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7043. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7044. size_t chunk_size = 130;
  7045. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7046. chunk_begin += chunk_size) {
  7047. size_t current_chunk_size =
  7048. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7049. bool result = decompressor.decompress(
  7050. compressed_data.data() + chunk_begin, current_chunk_size,
  7051. [&](const char *decompressed_data_chunk,
  7052. size_t decompressed_data_chunk_size) {
  7053. decompressed_data.insert(decompressed_data.size(),
  7054. decompressed_data_chunk,
  7055. decompressed_data_chunk_size);
  7056. return true;
  7057. });
  7058. ASSERT_TRUE(result);
  7059. }
  7060. }
  7061. ASSERT_EQ(data, decompressed_data);
  7062. }
  7063. TEST(GzipDecompressor, DeflateDecompression) {
  7064. std::string original_text = "Raw deflate without gzip";
  7065. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7066. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7067. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7068. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7069. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7070. std::string decompressed_data;
  7071. {
  7072. httplib::detail::gzip_decompressor decompressor;
  7073. bool result = decompressor.decompress(
  7074. compressed_data.data(), compressed_data.size(),
  7075. [&](const char *decompressed_data_chunk,
  7076. size_t decompressed_data_chunk_size) {
  7077. decompressed_data.insert(decompressed_data.size(),
  7078. decompressed_data_chunk,
  7079. decompressed_data_chunk_size);
  7080. return true;
  7081. });
  7082. ASSERT_TRUE(result);
  7083. }
  7084. ASSERT_EQ(original_text, decompressed_data);
  7085. }
  7086. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7087. std::string original_text = "Raw deflate without gzip";
  7088. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7089. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7090. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7091. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7092. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7093. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7094. std::string decompressed_data;
  7095. {
  7096. httplib::detail::gzip_decompressor decompressor;
  7097. bool result = decompressor.decompress(
  7098. compressed_data.data(), compressed_data.size(),
  7099. [&](const char *decompressed_data_chunk,
  7100. size_t decompressed_data_chunk_size) {
  7101. decompressed_data.insert(decompressed_data.size(),
  7102. decompressed_data_chunk,
  7103. decompressed_data_chunk_size);
  7104. return true;
  7105. });
  7106. ASSERT_TRUE(result);
  7107. }
  7108. ASSERT_EQ(original_text, decompressed_data);
  7109. }
  7110. #endif
  7111. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7112. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7113. Headers headers;
  7114. headers.emplace("Accept-Encoding", "br");
  7115. auto res = cli_.Get("/streamed-chunked", headers);
  7116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7117. EXPECT_EQ(StatusCode::OK_200, res->status);
  7118. EXPECT_EQ(std::string("123456789"), res->body);
  7119. }
  7120. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7121. Headers headers;
  7122. headers.emplace("Accept-Encoding", "br");
  7123. auto res = cli_.Get("/streamed-chunked2", headers);
  7124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7125. EXPECT_EQ(StatusCode::OK_200, res->status);
  7126. EXPECT_EQ(std::string("123456789"), res->body);
  7127. }
  7128. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7129. cli_.set_compress(true);
  7130. auto res = cli_.Put(
  7131. "/put", 3,
  7132. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7133. sink.os << "PUT";
  7134. return true;
  7135. },
  7136. "text/plain");
  7137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7138. EXPECT_EQ(StatusCode::OK_200, res->status);
  7139. EXPECT_EQ("PUT", res->body);
  7140. }
  7141. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7142. cli_.set_compress(true);
  7143. auto res = cli_.Put(
  7144. "/put",
  7145. [](size_t /*offset*/, DataSink &sink) {
  7146. sink.os << "PUT";
  7147. sink.done();
  7148. return true;
  7149. },
  7150. "text/plain");
  7151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7152. EXPECT_EQ(StatusCode::OK_200, res->status);
  7153. EXPECT_EQ("PUT", res->body);
  7154. }
  7155. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7156. cli_.set_compress(true);
  7157. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7159. EXPECT_EQ(StatusCode::OK_200, res->status);
  7160. EXPECT_EQ(LARGE_DATA, res->body);
  7161. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7162. }
  7163. #endif
  7164. TEST_F(ServerTest, Patch) {
  7165. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7167. EXPECT_EQ(StatusCode::OK_200, res->status);
  7168. EXPECT_EQ("PATCH", res->body);
  7169. }
  7170. TEST_F(ServerTest, Delete) {
  7171. auto res = cli_.Delete("/delete");
  7172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7173. EXPECT_EQ(StatusCode::OK_200, res->status);
  7174. EXPECT_EQ("DELETE", res->body);
  7175. }
  7176. TEST_F(ServerTest, DeleteContentReceiver) {
  7177. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7179. EXPECT_EQ(StatusCode::OK_200, res->status);
  7180. EXPECT_EQ("content", res->body);
  7181. }
  7182. TEST_F(ServerTest, Options) {
  7183. auto res = cli_.Options("*");
  7184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7185. EXPECT_EQ(StatusCode::OK_200, res->status);
  7186. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7187. EXPECT_TRUE(res->body.empty());
  7188. }
  7189. TEST_F(ServerTest, URL) {
  7190. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7192. EXPECT_EQ(StatusCode::OK_200, res->status);
  7193. }
  7194. TEST_F(ServerTest, ArrayParam) {
  7195. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7197. EXPECT_EQ(StatusCode::OK_200, res->status);
  7198. }
  7199. TEST_F(ServerTest, ArrayParamValues) {
  7200. auto res =
  7201. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7203. EXPECT_EQ(StatusCode::OK_200, res->status);
  7204. }
  7205. TEST_F(ServerTest, NoMultipleHeaders) {
  7206. Headers headers = {{"Content-Length", "5"}};
  7207. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7208. "text/plain");
  7209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7210. EXPECT_EQ(StatusCode::OK_200, res->status);
  7211. }
  7212. TEST_F(ServerTest, PostContentReceiver) {
  7213. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7215. ASSERT_EQ(StatusCode::OK_200, res->status);
  7216. ASSERT_EQ("content", res->body);
  7217. }
  7218. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7219. UploadFormDataItems items = {
  7220. {"text1", "text default", "", ""},
  7221. {"text2", "aωb", "", ""},
  7222. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7223. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7224. {"file3", "", "", "application/octet-stream"},
  7225. };
  7226. auto res = cli_.Post("/content_receiver", items);
  7227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7228. EXPECT_EQ(StatusCode::OK_200, res->status);
  7229. }
  7230. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7231. UploadFormDataItems items = {
  7232. {"text1", "text default", "", ""},
  7233. {"text2", "aωb", "", ""},
  7234. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7235. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7236. {"file3", "", "", "application/octet-stream"},
  7237. };
  7238. auto boundary = std::string("+++++");
  7239. std::string body;
  7240. for (const auto &item : items) {
  7241. body += "--" + boundary + "\r\n";
  7242. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7243. if (!item.filename.empty()) {
  7244. body += "; filename=\"" + item.filename + "\"";
  7245. }
  7246. body += "\r\n";
  7247. if (!item.content_type.empty()) {
  7248. body += "Content-Type: " + item.content_type + "\r\n";
  7249. }
  7250. body += "\r\n";
  7251. body += item.content + "\r\n";
  7252. }
  7253. body += "--" + boundary + "--\r\n";
  7254. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7255. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7257. EXPECT_EQ(StatusCode::OK_200, res->status);
  7258. }
  7259. TEST(MultipartFormDataTest, FieldEscaping) {
  7260. Server svr;
  7261. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7262. const ContentReader &content_reader) {
  7263. ASSERT_TRUE(req.is_multipart_form_data());
  7264. std::vector<FormData> received;
  7265. content_reader(
  7266. [&](const FormData &file) {
  7267. received.push_back(file);
  7268. return true;
  7269. },
  7270. [&](const char *data, size_t data_length) {
  7271. received.back().content.append(data, data_length);
  7272. return true;
  7273. });
  7274. // '"', CR and LF in names and filenames are escaped following the
  7275. // WHATWG HTML standard, so each part still parses as a single part
  7276. // with no injected headers. Content types get CR/LF escaped too,
  7277. // while '"' (legal there, e.g. quoted charset) is preserved.
  7278. ASSERT_EQ(4U, received.size());
  7279. EXPECT_EQ("na%22me", received[0].name);
  7280. EXPECT_EQ("quoted name", received[0].content);
  7281. EXPECT_EQ("file", received[1].name);
  7282. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7283. received[1].filename);
  7284. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7285. EXPECT_EQ("injected", received[1].content);
  7286. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7287. EXPECT_EQ("my%22file.txt", received[2].filename);
  7288. EXPECT_EQ("cr lf name", received[2].content);
  7289. EXPECT_EQ("typed", received[3].name);
  7290. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7291. received[3].content_type);
  7292. EXPECT_EQ("typed content", received[3].content);
  7293. });
  7294. auto port = svr.bind_to_any_port("localhost");
  7295. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7296. auto se = detail::scope_exit([&] {
  7297. svr.stop();
  7298. t.join();
  7299. ASSERT_FALSE(svr.is_running());
  7300. });
  7301. svr.wait_until_ready();
  7302. Client cli("localhost", port);
  7303. UploadFormDataItems items = {
  7304. {"na\"me", "quoted name", "", ""},
  7305. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7306. "application/octet-stream"},
  7307. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7308. {"typed", "typed content", "",
  7309. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7310. };
  7311. auto res = cli.Post("/post", items);
  7312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7313. EXPECT_EQ(StatusCode::OK_200, res->status);
  7314. }
  7315. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7316. const UploadFormDataItems items = {
  7317. {"name1", "Content 1", "", ""},
  7318. {"name2", "Content 2", "file2.txt", "text/plain"},
  7319. };
  7320. Server svr;
  7321. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7322. const ContentReader &content_reader) {
  7323. ASSERT_TRUE(req.is_multipart_form_data());
  7324. std::vector<FormData> received;
  7325. content_reader(
  7326. [&](const FormData &file) {
  7327. received.push_back(file);
  7328. return true;
  7329. },
  7330. [&](const char *data, size_t data_length) {
  7331. received.back().content.append(data, data_length);
  7332. return true;
  7333. });
  7334. ASSERT_EQ(2U, received.size());
  7335. EXPECT_EQ("name1", received[0].name);
  7336. EXPECT_EQ("Content 1", received[0].content);
  7337. EXPECT_EQ("name2", received[1].name);
  7338. EXPECT_EQ("Content 2", received[1].content);
  7339. EXPECT_EQ("file2.txt", received[1].filename);
  7340. EXPECT_EQ("text/plain", received[1].content_type);
  7341. });
  7342. auto port = svr.bind_to_any_port("localhost");
  7343. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7344. auto se = detail::scope_exit([&] {
  7345. svr.stop();
  7346. t.join();
  7347. ASSERT_FALSE(svr.is_running());
  7348. });
  7349. svr.wait_until_ready();
  7350. Client cli("localhost", port);
  7351. // Whole-body serialization with a generated boundary
  7352. {
  7353. MultipartFormDataWriter writer;
  7354. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7355. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7356. writer.content_type());
  7357. auto body = writer.serialize(items);
  7358. EXPECT_EQ(body.size(), writer.content_length(items));
  7359. auto res = cli.Post("/post", body, writer.content_type());
  7360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7361. EXPECT_EQ(StatusCode::OK_200, res->status);
  7362. }
  7363. // Per-part framing with a custom boundary via a content provider
  7364. {
  7365. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7366. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7367. MultipartFormDataWriter writer("custom-boundary_123");
  7368. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7369. std::string body;
  7370. for (const auto &item : items) {
  7371. body += writer.item_begin(item);
  7372. body += item.content;
  7373. body += MultipartFormDataWriter::item_end();
  7374. }
  7375. body += writer.finish();
  7376. EXPECT_EQ(body.size(), writer.content_length(items));
  7377. auto res = cli.Post(
  7378. "/post", body.size(),
  7379. [&](size_t offset, size_t length, DataSink &sink) {
  7380. sink.write(body.data() + offset, length);
  7381. return true;
  7382. },
  7383. writer.content_type());
  7384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7385. EXPECT_EQ(StatusCode::OK_200, res->status);
  7386. }
  7387. }
  7388. TEST_F(ServerTest, PostContentReceiverGzip) {
  7389. cli_.set_compress(true);
  7390. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7392. ASSERT_EQ(StatusCode::OK_200, res->status);
  7393. ASSERT_EQ("content", res->body);
  7394. }
  7395. TEST_F(ServerTest, PutContentReceiver) {
  7396. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7398. ASSERT_EQ(StatusCode::OK_200, res->status);
  7399. ASSERT_EQ("content", res->body);
  7400. }
  7401. TEST_F(ServerTest, PatchContentReceiver) {
  7402. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7404. ASSERT_EQ(StatusCode::OK_200, res->status);
  7405. ASSERT_EQ("content", res->body);
  7406. }
  7407. template <typename ClientType>
  7408. void TestWithHeadersAndContentReceiver(
  7409. ClientType &cli,
  7410. std::function<Result(ClientType &, const std::string &, const Headers &,
  7411. const std::string &, const std::string &,
  7412. ContentReceiver, DownloadProgress)>
  7413. request_func) {
  7414. Headers headers;
  7415. headers.emplace("X-Custom-Header", "test-value");
  7416. std::string received_body;
  7417. auto res = request_func(
  7418. cli, "/content_receiver", headers, "content", "application/json",
  7419. [&](const char *data, size_t data_length) {
  7420. received_body.append(data, data_length);
  7421. return true;
  7422. },
  7423. nullptr);
  7424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7425. EXPECT_EQ(StatusCode::OK_200, res->status);
  7426. EXPECT_EQ("content", received_body);
  7427. }
  7428. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7429. #ifdef CPPHTTPLIB_SSL_ENABLED
  7430. using ClientT = SSLClient;
  7431. #else
  7432. using ClientT = Client;
  7433. #endif
  7434. TestWithHeadersAndContentReceiver<ClientT>(
  7435. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7436. const std::string &body, const std::string &content_type,
  7437. ContentReceiver receiver, DownloadProgress progress) {
  7438. return cli.Post(path, headers, body, content_type, receiver, progress);
  7439. });
  7440. }
  7441. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7442. #ifdef CPPHTTPLIB_SSL_ENABLED
  7443. using ClientT = SSLClient;
  7444. #else
  7445. using ClientT = Client;
  7446. #endif
  7447. TestWithHeadersAndContentReceiver<ClientT>(
  7448. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7449. const std::string &body, const std::string &content_type,
  7450. ContentReceiver receiver, DownloadProgress progress) {
  7451. return cli.Put(path, headers, body, content_type, receiver, progress);
  7452. });
  7453. }
  7454. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7455. #ifdef CPPHTTPLIB_SSL_ENABLED
  7456. using ClientT = SSLClient;
  7457. #else
  7458. using ClientT = Client;
  7459. #endif
  7460. TestWithHeadersAndContentReceiver<ClientT>(
  7461. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7462. const std::string &body, const std::string &content_type,
  7463. ContentReceiver receiver, DownloadProgress progress) {
  7464. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7465. });
  7466. }
  7467. template <typename ClientType>
  7468. void TestWithHeadersAndContentReceiverWithProgress(
  7469. ClientType &cli,
  7470. std::function<Result(ClientType &, const std::string &, const Headers &,
  7471. const std::string &, const std::string &,
  7472. ContentReceiver, DownloadProgress)>
  7473. request_func) {
  7474. Headers headers;
  7475. headers.emplace("X-Test-Header", "progress-test");
  7476. std::string received_body;
  7477. auto progress_called = false;
  7478. auto res = request_func(
  7479. cli, "/content_receiver", headers, "content", "text/plain",
  7480. [&](const char *data, size_t data_length) {
  7481. received_body.append(data, data_length);
  7482. return true;
  7483. },
  7484. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7485. progress_called = true;
  7486. return true;
  7487. });
  7488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7489. EXPECT_EQ(StatusCode::OK_200, res->status);
  7490. EXPECT_EQ("content", received_body);
  7491. EXPECT_TRUE(progress_called);
  7492. }
  7493. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7494. #ifdef CPPHTTPLIB_SSL_ENABLED
  7495. using ClientT = SSLClient;
  7496. #else
  7497. using ClientT = Client;
  7498. #endif
  7499. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7500. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7501. const std::string &body, const std::string &content_type,
  7502. ContentReceiver receiver, DownloadProgress progress) {
  7503. return cli.Post(path, headers, body, content_type, receiver, progress);
  7504. });
  7505. }
  7506. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7507. #ifdef CPPHTTPLIB_SSL_ENABLED
  7508. using ClientT = SSLClient;
  7509. #else
  7510. using ClientT = Client;
  7511. #endif
  7512. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7513. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7514. const std::string &body, const std::string &content_type,
  7515. ContentReceiver receiver, DownloadProgress progress) {
  7516. return cli.Put(path, headers, body, content_type, receiver, progress);
  7517. });
  7518. }
  7519. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7520. #ifdef CPPHTTPLIB_SSL_ENABLED
  7521. using ClientT = SSLClient;
  7522. #else
  7523. using ClientT = Client;
  7524. #endif
  7525. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7526. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7527. const std::string &body, const std::string &content_type,
  7528. ContentReceiver receiver, DownloadProgress progress) {
  7529. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7530. });
  7531. }
  7532. template <typename ClientType>
  7533. void TestWithHeadersAndContentReceiverError(
  7534. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7535. const Headers &, const std::string &,
  7536. const std::string &, ContentReceiver)>
  7537. request_func) {
  7538. Headers headers;
  7539. headers.emplace("X-Error-Test", "true");
  7540. std::string received_body;
  7541. auto receiver_failed = false;
  7542. auto res =
  7543. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7544. [&](const char *data, size_t data_length) {
  7545. received_body.append(data, data_length);
  7546. receiver_failed = true;
  7547. return false;
  7548. });
  7549. ASSERT_FALSE(res);
  7550. EXPECT_TRUE(receiver_failed);
  7551. }
  7552. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7553. #ifdef CPPHTTPLIB_SSL_ENABLED
  7554. using ClientT = SSLClient;
  7555. #else
  7556. using ClientT = Client;
  7557. #endif
  7558. TestWithHeadersAndContentReceiverError<ClientT>(
  7559. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7560. const std::string &body, const std::string &content_type,
  7561. ContentReceiver receiver) {
  7562. return cli.Post(path, headers, body, content_type, receiver);
  7563. });
  7564. }
  7565. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7566. #ifdef CPPHTTPLIB_SSL_ENABLED
  7567. using ClientT = SSLClient;
  7568. #else
  7569. using ClientT = Client;
  7570. #endif
  7571. TestWithHeadersAndContentReceiverError<ClientT>(
  7572. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7573. const std::string &body, const std::string &content_type,
  7574. ContentReceiver receiver) {
  7575. return cli.Put(path, headers, body, content_type, receiver);
  7576. });
  7577. }
  7578. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7579. #ifdef CPPHTTPLIB_SSL_ENABLED
  7580. using ClientT = SSLClient;
  7581. #else
  7582. using ClientT = Client;
  7583. #endif
  7584. TestWithHeadersAndContentReceiverError<ClientT>(
  7585. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7586. const std::string &body, const std::string &content_type,
  7587. ContentReceiver receiver) {
  7588. return cli.Patch(path, headers, body, content_type, receiver);
  7589. });
  7590. }
  7591. TEST_F(ServerTest, PostQueryStringAndBody) {
  7592. auto res =
  7593. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7595. ASSERT_EQ(StatusCode::OK_200, res->status);
  7596. }
  7597. TEST_F(ServerTest, HTTP2Magic) {
  7598. Request req;
  7599. req.method = "PRI";
  7600. req.path = "*";
  7601. req.body = "SM";
  7602. auto res = std::make_shared<Response>();
  7603. auto error = Error::Success;
  7604. auto ret = cli_.send(req, *res, error);
  7605. ASSERT_TRUE(ret);
  7606. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7607. }
  7608. TEST_F(ServerTest, KeepAlive) {
  7609. auto res = cli_.Get("/hi");
  7610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7611. EXPECT_EQ(StatusCode::OK_200, res->status);
  7612. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7613. EXPECT_EQ("Hello World!", res->body);
  7614. res = cli_.Get("/hi");
  7615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7616. EXPECT_EQ(StatusCode::OK_200, res->status);
  7617. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7618. EXPECT_EQ("Hello World!", res->body);
  7619. res = cli_.Get("/hi");
  7620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7621. EXPECT_EQ(StatusCode::OK_200, res->status);
  7622. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7623. EXPECT_EQ("Hello World!", res->body);
  7624. res = cli_.Get("/not-exist");
  7625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7626. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7627. res = cli_.Post("/empty", "", "text/plain");
  7628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7629. EXPECT_EQ(StatusCode::OK_200, res->status);
  7630. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7631. EXPECT_EQ("empty", res->body);
  7632. EXPECT_EQ("close", res->get_header_value("Connection"));
  7633. res = cli_.Post(
  7634. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7635. "text/plain");
  7636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7637. EXPECT_EQ(StatusCode::OK_200, res->status);
  7638. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7639. EXPECT_EQ("empty", res->body);
  7640. cli_.set_keep_alive(false);
  7641. res = cli_.Get("/last-request");
  7642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7643. EXPECT_EQ(StatusCode::OK_200, res->status);
  7644. EXPECT_EQ("close", res->get_header_value("Connection"));
  7645. }
  7646. TEST_F(ServerTest, TooManyRedirect) {
  7647. cli_.set_follow_location(true);
  7648. auto res = cli_.Get("/redirect/0");
  7649. ASSERT_TRUE(!res);
  7650. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7651. }
  7652. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7653. Request req;
  7654. req.method = "FOOBAR";
  7655. req.path = "/hi";
  7656. cli_.set_keep_alive(true);
  7657. auto res = cli_.send(req);
  7658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7659. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7660. EXPECT_EQ("close", res->get_header_value("Connection"));
  7661. EXPECT_FALSE(cli_.is_socket_open());
  7662. }
  7663. TEST_F(ServerTest, CustomRouteReadsBody) {
  7664. const std::string xml =
  7665. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7666. Request req;
  7667. req.method = "PROPFIND";
  7668. req.path = "/dav/dir";
  7669. req.set_header("Depth", "1");
  7670. req.body = xml;
  7671. auto res = cli_.send(req);
  7672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7673. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7674. EXPECT_EQ(xml, res->body);
  7675. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7676. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7677. }
  7678. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7679. Request req;
  7680. req.method = "PROPFIND";
  7681. req.path = "/dav/42";
  7682. auto res = cli_.send(req);
  7683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7684. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7685. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7686. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7687. }
  7688. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7689. Request req;
  7690. req.method = "PROPFIND";
  7691. req.path = "/dav-re/123";
  7692. auto res = cli_.send(req);
  7693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7694. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7695. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7696. }
  7697. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7698. Request req;
  7699. req.method = "MKCOL";
  7700. req.path = "/dav-mkcol";
  7701. auto res = cli_.send(req);
  7702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7703. EXPECT_EQ(StatusCode::Created_201, res->status);
  7704. }
  7705. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7706. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7707. Request req;
  7708. req.method = "REPORT";
  7709. req.path = "/dav-report";
  7710. req.body = xml;
  7711. auto res = cli_.send(req);
  7712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7713. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7714. EXPECT_EQ(xml, res->body);
  7715. }
  7716. // A content reader route must fire even when the request carries no body,
  7717. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7718. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7719. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7720. Request req;
  7721. req.method = "REPORT";
  7722. req.path = "/dav-report";
  7723. auto res = cli_.send(req);
  7724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7725. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7726. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7727. }
  7728. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7729. Request req;
  7730. req.method = "PROPFIND";
  7731. req.path = "/not-dav";
  7732. auto res = cli_.send(req);
  7733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7734. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7735. }
  7736. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7737. Request req;
  7738. req.method = "UNLOCK";
  7739. req.path = "/dav/dir";
  7740. cli_.set_keep_alive(true);
  7741. auto res = cli_.send(req);
  7742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7743. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7744. EXPECT_EQ("close", res->get_header_value("Connection"));
  7745. EXPECT_FALSE(cli_.is_socket_open());
  7746. }
  7747. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7748. // The mount point serves this path, but only for GET and HEAD.
  7749. auto get_res = cli_.Get("/dir/index.html");
  7750. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7751. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7752. Request req;
  7753. req.method = "PROPFIND";
  7754. req.path = "/dir/index.html";
  7755. auto res = cli_.send(req);
  7756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7757. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7758. }
  7759. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7760. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7761. cli_.set_keep_alive(true);
  7762. for (auto i = 0; i < 2; i++) {
  7763. Request req;
  7764. req.method = "PROPFIND";
  7765. req.path = "/dav/dir";
  7766. req.body = xml;
  7767. auto res = cli_.send(req);
  7768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7769. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7770. EXPECT_EQ(xml, res->body);
  7771. EXPECT_TRUE(cli_.is_socket_open());
  7772. }
  7773. // A built-in method must still be served on the same connection.
  7774. cli_.set_keep_alive(false);
  7775. auto res = cli_.Get("/hi");
  7776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7777. EXPECT_EQ(StatusCode::OK_200, res->status);
  7778. EXPECT_EQ("close", res->get_header_value("Connection"));
  7779. }
  7780. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7781. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7782. Request req;
  7783. req.method = "PROPFIND";
  7784. req.path = "/dav/dir";
  7785. req.set_header("Expect", "100-continue");
  7786. req.body = xml;
  7787. auto res = cli_.send(req);
  7788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7789. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7790. EXPECT_EQ(xml, res->body);
  7791. }
  7792. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7793. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7794. TEST_F(ServerTest, Gzip) {
  7795. Headers headers;
  7796. headers.emplace("Accept-Encoding", "gzip, deflate");
  7797. auto res = cli_.Get("/compress", headers);
  7798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7799. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7800. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7801. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7802. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7803. "7890123456789012345678901234567890",
  7804. res->body);
  7805. EXPECT_EQ(StatusCode::OK_200, res->status);
  7806. }
  7807. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7808. Headers headers;
  7809. headers.emplace("Accept-Encoding", "gzip, deflate");
  7810. auto res = cli_.Get("/compress-with-charset", headers);
  7811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7812. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7813. EXPECT_EQ("application/json; charset=utf-8",
  7814. res->get_header_value("Content-Type"));
  7815. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7816. "7890123456789012345678901234567890",
  7817. res->body);
  7818. EXPECT_EQ(StatusCode::OK_200, res->status);
  7819. }
  7820. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7821. Headers headers;
  7822. headers.emplace("Accept-Encoding", "");
  7823. auto res = cli_.Get("/compress", headers);
  7824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7825. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7826. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7827. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7828. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7829. "7890123456789012345678901234567890",
  7830. res->body);
  7831. EXPECT_EQ(StatusCode::OK_200, res->status);
  7832. }
  7833. TEST_F(ServerTest, GzipWithContentReceiver) {
  7834. Headers headers;
  7835. headers.emplace("Accept-Encoding", "gzip, deflate");
  7836. std::string body;
  7837. auto res = cli_.Get("/compress", headers,
  7838. [&](const char *data, uint64_t data_length) {
  7839. EXPECT_EQ(100U, data_length);
  7840. body.append(data, data_length);
  7841. return true;
  7842. });
  7843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7844. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7845. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7846. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7847. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7848. "7890123456789012345678901234567890",
  7849. body);
  7850. EXPECT_EQ(StatusCode::OK_200, res->status);
  7851. }
  7852. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7853. Headers headers;
  7854. headers.emplace("Accept-Encoding", "gzip, deflate");
  7855. cli_.set_decompress(false);
  7856. auto res = cli_.Get("/compress", headers);
  7857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7858. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7859. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7860. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7861. EXPECT_EQ(33U, res->body.size());
  7862. EXPECT_EQ(StatusCode::OK_200, res->status);
  7863. }
  7864. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7865. Headers headers;
  7866. headers.emplace("Accept-Encoding", "");
  7867. std::string body;
  7868. auto res = cli_.Get("/compress", headers,
  7869. [&](const char *data, uint64_t data_length) {
  7870. EXPECT_EQ(100U, data_length);
  7871. body.append(data, data_length);
  7872. return true;
  7873. });
  7874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7875. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7876. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7877. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7878. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7879. "7890123456789012345678901234567890",
  7880. body);
  7881. EXPECT_EQ(StatusCode::OK_200, res->status);
  7882. }
  7883. TEST_F(ServerTest, NoGzip) {
  7884. Headers headers;
  7885. headers.emplace("Accept-Encoding", "gzip, deflate");
  7886. auto res = cli_.Get("/nocompress", headers);
  7887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7888. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7889. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7890. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7891. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7892. "7890123456789012345678901234567890",
  7893. res->body);
  7894. EXPECT_EQ(StatusCode::OK_200, res->status);
  7895. }
  7896. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7897. Headers headers;
  7898. headers.emplace("Accept-Encoding", "gzip, deflate");
  7899. std::string body;
  7900. auto res = cli_.Get("/nocompress", headers,
  7901. [&](const char *data, uint64_t data_length) {
  7902. EXPECT_EQ(100U, data_length);
  7903. body.append(data, data_length);
  7904. return true;
  7905. });
  7906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7907. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7908. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7909. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7910. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7911. "7890123456789012345678901234567890",
  7912. body);
  7913. EXPECT_EQ(StatusCode::OK_200, res->status);
  7914. }
  7915. TEST_F(ServerTest, MultipartFormDataGzip) {
  7916. UploadFormDataItems items = {
  7917. {"key1", "test", "", ""},
  7918. {"key2", "--abcdefg123", "", ""},
  7919. };
  7920. cli_.set_compress(true);
  7921. auto res = cli_.Post("/compress-multipart", items);
  7922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7923. EXPECT_EQ(StatusCode::OK_200, res->status);
  7924. }
  7925. #endif
  7926. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7927. // Static file compression is opt-in, so these run their own server rather than
  7928. // flipping it on for the shared ServerTest fixture, which would silently
  7929. // rewrite what every other static file test is asserting.
  7930. class StaticFileCompressionTest : public ::testing::Test {
  7931. protected:
  7932. void TearDown() override {
  7933. if (t_.joinable()) {
  7934. svr_.stop();
  7935. t_.join();
  7936. }
  7937. }
  7938. int start(const std::function<void(Server &)> &configure = nullptr) {
  7939. // Serves the same tree as a directory of build-time compressed assets
  7940. // would be served: the mount point names the coding the files are already
  7941. // stored in. Registered before "/" so it is the one that matches.
  7942. svr_.set_mount_point("/pre-encoded", "./www",
  7943. {{"Content-Encoding", "gzip"}});
  7944. svr_.set_mount_point("/", "./www");
  7945. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7946. res.set_file_content("./www/dir/index.html", "text/html");
  7947. });
  7948. svr_.Get("/pre-encoded-file-content",
  7949. [](const Request & /*req*/, Response &res) {
  7950. res.set_header("Content-Encoding", "gzip");
  7951. res.set_file_content("./www/dir/index.html", "text/html");
  7952. });
  7953. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7954. res.set_content_provider(
  7955. 6, "text/plain",
  7956. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7957. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7958. return true;
  7959. });
  7960. });
  7961. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7962. res.set_content_provider(
  7963. 1000, "text/plain",
  7964. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7965. if (offset < 100) {
  7966. std::string data(100, 'A');
  7967. sink.write(data.data(), data.size());
  7968. return true;
  7969. }
  7970. std::this_thread::sleep_for(std::chrono::seconds(2));
  7971. std::string data(900, 'B');
  7972. sink.write(data.data(), data.size());
  7973. return true;
  7974. });
  7975. });
  7976. if (configure) { configure(svr_); }
  7977. auto port = svr_.bind_to_any_port(HOST);
  7978. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7979. svr_.wait_until_ready();
  7980. return port;
  7981. }
  7982. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7983. // Every file under ./www except 1MB.txt is smaller than the default
  7984. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7985. // it out of the way.
  7986. static void enable_without_floor(Server &svr) {
  7987. svr.set_static_file_compression(true);
  7988. svr.set_static_file_compression_min_length(0);
  7989. }
  7990. Server svr_;
  7991. std::thread t_;
  7992. };
  7993. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7994. auto port = start();
  7995. Client cli(HOST, port);
  7996. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7998. EXPECT_EQ(StatusCode::OK_200, res->status);
  7999. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8000. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8001. EXPECT_EQ(1048576U, res->body.size());
  8002. }
  8003. TEST_F(StaticFileCompressionTest, MountPoint) {
  8004. auto port = start(enable);
  8005. Client cli(HOST, port);
  8006. cli.set_decompress(false);
  8007. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8009. EXPECT_EQ(StatusCode::OK_200, res->status);
  8010. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8011. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8012. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8013. // The response stays self-delimiting: a length, not a chunked body.
  8014. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8015. EXPECT_EQ(std::to_string(res->body.size()),
  8016. res->get_header_value("Content-Length"));
  8017. EXPECT_LT(res->body.size(), 1048576U);
  8018. EXPECT_FALSE(res->body.empty());
  8019. }
  8020. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8021. auto port = start(enable);
  8022. Client cli(HOST, port);
  8023. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8025. EXPECT_EQ(StatusCode::OK_200, res->status);
  8026. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8027. EXPECT_EQ(1048576U, res->body.size());
  8028. }
  8029. TEST_F(StaticFileCompressionTest, FileContent) {
  8030. auto port = start(enable_without_floor);
  8031. Client cli(HOST, port);
  8032. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8034. EXPECT_EQ(StatusCode::OK_200, res->status);
  8035. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8036. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8037. EXPECT_EQ(104U, res->body.size());
  8038. }
  8039. // A handler that serves an already-encoded file names the coding itself. The
  8040. // file-backed path decided its coding from Accept-Encoding and the content
  8041. // type alone, so it compressed the stored bytes a second time and appended a
  8042. // second Content-Encoding field line.
  8043. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8044. auto port = start(enable_without_floor);
  8045. Client cli(HOST, port);
  8046. cli.set_decompress(false);
  8047. auto res = cli.Get("/pre-encoded-file-content",
  8048. Headers{{"Accept-Encoding", "gzip"}});
  8049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8050. EXPECT_EQ(StatusCode::OK_200, res->status);
  8051. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8052. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8053. // Vary belongs to a coding the server chose, and it chose none here.
  8054. EXPECT_FALSE(res->has_header("Vary"));
  8055. // The file travels exactly as it is stored on disk.
  8056. EXPECT_EQ(104U, res->body.size());
  8057. }
  8058. // The 1MB file clears the default floor, so this one runs the configuration a
  8059. // deployment would actually have.
  8060. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8061. auto port = start(enable);
  8062. Client cli(HOST, port);
  8063. cli.set_decompress(false);
  8064. auto res =
  8065. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8067. EXPECT_EQ(StatusCode::OK_200, res->status);
  8068. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8069. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8070. EXPECT_FALSE(res->has_header("Vary"));
  8071. EXPECT_EQ(1048576U, res->body.size());
  8072. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8073. }
  8074. TEST_F(StaticFileCompressionTest, Head) {
  8075. auto port = start(enable);
  8076. Client cli(HOST, port);
  8077. cli.set_decompress(false);
  8078. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8079. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8080. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8082. EXPECT_EQ(StatusCode::OK_200, res->status);
  8083. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8084. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8085. // HEAD still reports the size a GET would return.
  8086. EXPECT_EQ(get->get_header_value("Content-Length"),
  8087. res->get_header_value("Content-Length"));
  8088. EXPECT_TRUE(res->body.empty());
  8089. }
  8090. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8091. auto port = start(enable);
  8092. Client cli(HOST, port);
  8093. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8094. {"Accept-Encoding", "gzip"}});
  8095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8096. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8097. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8098. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8099. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8100. EXPECT_EQ("cd", res->body);
  8101. }
  8102. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8103. auto port = start(enable);
  8104. Client cli(HOST, port);
  8105. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8107. EXPECT_EQ(StatusCode::OK_200, res->status);
  8108. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8109. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8110. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8111. }
  8112. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8113. auto port = start(enable);
  8114. Client cli(HOST, port);
  8115. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8117. EXPECT_EQ(StatusCode::OK_200, res->status);
  8118. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8119. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8120. EXPECT_TRUE(res->body.empty());
  8121. }
  8122. TEST_F(StaticFileCompressionTest, MinLength) {
  8123. auto port = start(enable);
  8124. Client cli(HOST, port);
  8125. // 104 bytes, well under the default floor. Compressing it would add the
  8126. // gzip header and trailer to a body that already fits in one packet.
  8127. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8129. EXPECT_EQ(StatusCode::OK_200, res->status);
  8130. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8131. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8132. }
  8133. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8134. auto port = start([](Server &svr) {
  8135. svr.set_static_file_compression(true);
  8136. svr.set_static_file_compression_min_length(1);
  8137. });
  8138. Client cli(HOST, port);
  8139. cli.set_decompress(false);
  8140. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8142. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8143. // A 9-byte file comes back larger than it went in, because gzip's header and
  8144. // trailer outweigh anything deflate can save. That is the end of the range
  8145. // the floor exists to keep out.
  8146. EXPECT_GT(res->body.size(), 9U);
  8147. }
  8148. TEST_F(StaticFileCompressionTest, MaxLength) {
  8149. auto port = start([](Server &svr) {
  8150. svr.set_static_file_compression(true);
  8151. svr.set_static_file_compression_min_length(0);
  8152. svr.set_static_file_compression_max_length(1024);
  8153. });
  8154. Client cli(HOST, port);
  8155. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8156. // defines `small` as a macro on Windows.
  8157. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8158. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8159. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8160. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8161. // Under it: compressed.
  8162. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8163. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8164. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8165. }
  8166. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8167. auto port = start(enable_without_floor);
  8168. Client cli(HOST, port);
  8169. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8170. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8171. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8172. auto identity_etag = identity->get_header_value("ETag");
  8173. ASSERT_FALSE(identity_etag.empty());
  8174. auto gzipped =
  8175. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8176. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8177. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8178. auto gzip_etag = gzipped->get_header_value("ETag");
  8179. ASSERT_FALSE(gzip_etag.empty());
  8180. // Two representations, two validators.
  8181. EXPECT_NE(identity_etag, gzip_etag);
  8182. // Each one revalidates against the request that would produce it...
  8183. auto fresh =
  8184. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8185. {"If-None-Match", gzip_etag}});
  8186. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8187. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8188. auto fresh_identity =
  8189. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8190. {"If-None-Match", identity_etag}});
  8191. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8192. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8193. // ...and not against the other representation.
  8194. auto crossed =
  8195. cli.Get("/dir/index.html",
  8196. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8197. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8198. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8199. }
  8200. // The opt-in covers responses the server reads off disk itself. A caller's own
  8201. // known-length provider keeps its Content-Length and, more importantly, keeps
  8202. // delivering incrementally: routing it through a compressor would hold every
  8203. // write back until zlib's window filled.
  8204. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8205. auto port = start(enable);
  8206. Client cli(HOST, port);
  8207. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8209. EXPECT_EQ(StatusCode::OK_200, res->status);
  8210. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8211. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8212. EXPECT_EQ("aaabbb", res->body);
  8213. }
  8214. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8215. auto port = start(enable);
  8216. Client cli(HOST, port);
  8217. cli.set_read_timeout(1, 0);
  8218. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8219. Headers{{"Accept-Encoding", "gzip"}});
  8220. ASSERT_TRUE(handle.is_valid());
  8221. // The provider writes 100 bytes and then stalls for longer than the read
  8222. // timeout. Those first bytes have to arrive anyway: run the response through
  8223. // a compressor and zlib holds them until its window fills, so the read would
  8224. // come back empty instead.
  8225. char buf[256];
  8226. auto n = handle.read(buf, sizeof(buf));
  8227. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8228. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8229. }
  8230. #endif
  8231. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8232. TEST_F(ServerTest, Brotli) {
  8233. Headers headers;
  8234. headers.emplace("Accept-Encoding", "br");
  8235. auto res = cli_.Get("/compress", headers);
  8236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8237. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8238. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8239. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8240. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8241. "7890123456789012345678901234567890",
  8242. res->body);
  8243. EXPECT_EQ(StatusCode::OK_200, res->status);
  8244. }
  8245. #endif
  8246. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8247. TEST_F(ServerTest, Zstd) {
  8248. Headers headers;
  8249. headers.emplace("Accept-Encoding", "zstd");
  8250. auto res = cli_.Get("/compress", headers);
  8251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8252. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8253. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8254. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8255. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8256. "7890123456789012345678901234567890",
  8257. res->body);
  8258. EXPECT_EQ(StatusCode::OK_200, res->status);
  8259. }
  8260. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8261. Headers headers;
  8262. headers.emplace("Accept-Encoding", "");
  8263. auto res = cli_.Get("/compress", headers);
  8264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8265. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8266. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8267. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8268. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8269. "7890123456789012345678901234567890",
  8270. res->body);
  8271. EXPECT_EQ(StatusCode::OK_200, res->status);
  8272. }
  8273. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8274. Headers headers;
  8275. headers.emplace("Accept-Encoding", "zstd");
  8276. std::string body;
  8277. auto res = cli_.Get("/compress", headers,
  8278. [&](const char *data, uint64_t data_length) {
  8279. EXPECT_EQ(100U, data_length);
  8280. body.append(data, data_length);
  8281. return true;
  8282. });
  8283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8284. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8285. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8286. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8287. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8288. "7890123456789012345678901234567890",
  8289. body);
  8290. EXPECT_EQ(StatusCode::OK_200, res->status);
  8291. }
  8292. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8293. Headers headers;
  8294. headers.emplace("Accept-Encoding", "zstd");
  8295. cli_.set_decompress(false);
  8296. auto res = cli_.Get("/compress", headers);
  8297. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8298. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8299. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8300. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8302. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8303. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8304. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8305. EXPECT_EQ(StatusCode::OK_200, res->status);
  8306. ASSERT_EQ(26U, res->body.size());
  8307. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8308. 0);
  8309. }
  8310. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8311. Headers headers;
  8312. headers.emplace("Accept-Encoding", "");
  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_TRUE(res->get_header_value("Content-Encoding").empty());
  8322. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8323. EXPECT_EQ("100", 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, NoZstd) {
  8330. Headers headers;
  8331. headers.emplace("Accept-Encoding", "zstd");
  8332. auto res = cli_.Get("/nocompress", headers);
  8333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8334. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8335. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8336. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8337. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8338. "7890123456789012345678901234567890",
  8339. res->body);
  8340. EXPECT_EQ(StatusCode::OK_200, res->status);
  8341. }
  8342. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8343. Headers headers;
  8344. headers.emplace("Accept-Encoding", "zstd");
  8345. std::string body;
  8346. auto res = cli_.Get("/nocompress", headers,
  8347. [&](const char *data, uint64_t data_length) {
  8348. EXPECT_EQ(100U, data_length);
  8349. body.append(data, data_length);
  8350. return true;
  8351. });
  8352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8353. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8354. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8355. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8356. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8357. "7890123456789012345678901234567890",
  8358. body);
  8359. EXPECT_EQ(StatusCode::OK_200, res->status);
  8360. }
  8361. // TODO: How to enable zstd ??
  8362. TEST_F(ServerTest, MultipartFormDataZstd) {
  8363. UploadFormDataItems items = {
  8364. {"key1", "test", "", ""},
  8365. {"key2", "--abcdefg123", "", ""},
  8366. };
  8367. Headers headers;
  8368. headers.emplace("Accept-Encoding", "zstd");
  8369. cli_.set_compress(true);
  8370. auto res = cli_.Post("/compress-multipart", headers, items);
  8371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8372. EXPECT_EQ(StatusCode::OK_200, res->status);
  8373. }
  8374. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8375. Headers headers;
  8376. headers.emplace("Accept-Encoding", "zstd");
  8377. cli_.set_compress(true);
  8378. auto res = cli_.Put(
  8379. "/put", headers, 3,
  8380. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8381. sink.os << "PUT";
  8382. return true;
  8383. },
  8384. "text/plain");
  8385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8386. EXPECT_EQ(StatusCode::OK_200, res->status);
  8387. EXPECT_EQ("PUT", res->body);
  8388. }
  8389. // Pre-compression logging tests
  8390. TEST_F(ServerTest, PreCompressionLogging) {
  8391. // Test data for compression (matches the actual /compress endpoint content)
  8392. const std::string test_content =
  8393. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8394. "3456789012345678901234567890";
  8395. // Variables to capture logging data
  8396. std::string pre_compression_body;
  8397. std::string pre_compression_content_type;
  8398. std::string pre_compression_content_encoding;
  8399. std::string post_compression_body;
  8400. std::string post_compression_content_type;
  8401. std::string post_compression_content_encoding;
  8402. // Set up pre-compression logger
  8403. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8404. const Response &res) {
  8405. pre_compression_body = res.body;
  8406. pre_compression_content_type = res.get_header_value("Content-Type");
  8407. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8408. });
  8409. // Set up post-compression logger
  8410. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8411. post_compression_body = res.body;
  8412. post_compression_content_type = res.get_header_value("Content-Type");
  8413. post_compression_content_encoding =
  8414. res.get_header_value("Content-Encoding");
  8415. });
  8416. // Test with gzip compression
  8417. Headers headers;
  8418. headers.emplace("Accept-Encoding", "gzip");
  8419. auto res = cli_.Get("/compress", headers);
  8420. // Verify response was compressed
  8421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8422. EXPECT_EQ(StatusCode::OK_200, res->status);
  8423. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8424. // Verify pre-compression logger captured uncompressed content
  8425. EXPECT_EQ(test_content, pre_compression_body);
  8426. EXPECT_EQ("text/plain", pre_compression_content_type);
  8427. EXPECT_TRUE(pre_compression_content_encoding
  8428. .empty()); // No encoding header before compression
  8429. // Verify post-compression logger captured compressed content
  8430. EXPECT_NE(test_content,
  8431. post_compression_body); // Should be different after compression
  8432. EXPECT_EQ("text/plain", post_compression_content_type);
  8433. EXPECT_EQ("gzip", post_compression_content_encoding);
  8434. // Verify compressed content is smaller
  8435. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8436. }
  8437. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8438. const std::string test_content =
  8439. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8440. "3456789012345678901234567890";
  8441. std::string pre_compression_body;
  8442. std::string post_compression_body;
  8443. svr_.set_pre_compression_logger(
  8444. [&](const Request & /*req*/, const Response &res) {
  8445. pre_compression_body = res.body;
  8446. });
  8447. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8448. post_compression_body = res.body;
  8449. });
  8450. Headers headers;
  8451. headers.emplace("Accept-Encoding", "br");
  8452. auto res = cli_.Get("/compress", headers);
  8453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8454. EXPECT_EQ(StatusCode::OK_200, res->status);
  8455. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8456. // Verify pre-compression content is uncompressed
  8457. EXPECT_EQ(test_content, pre_compression_body);
  8458. // Verify post-compression content is compressed
  8459. EXPECT_NE(test_content, post_compression_body);
  8460. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8461. }
  8462. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8463. const std::string test_content =
  8464. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8465. "3456789012345678901234567890";
  8466. std::string pre_compression_body;
  8467. std::string post_compression_body;
  8468. svr_.set_pre_compression_logger(
  8469. [&](const Request & /*req*/, const Response &res) {
  8470. pre_compression_body = res.body;
  8471. });
  8472. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8473. post_compression_body = res.body;
  8474. });
  8475. // Request without compression (use /nocompress endpoint)
  8476. Headers headers;
  8477. auto res = cli_.Get("/nocompress", headers);
  8478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8479. EXPECT_EQ(StatusCode::OK_200, res->status);
  8480. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8481. // Pre-compression logger should not be called when no compression is applied
  8482. EXPECT_TRUE(
  8483. pre_compression_body.empty()); // Pre-compression logger not called
  8484. EXPECT_EQ(
  8485. test_content,
  8486. post_compression_body); // Post-compression logger captures final content
  8487. }
  8488. TEST_F(ServerTest, LoggerSeesContentLength) {
  8489. size_t logged_content_length = 0;
  8490. std::string logged_content_length_header;
  8491. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8492. logged_content_length = res.content_length_;
  8493. logged_content_length_header = res.get_header_value("Content-Length");
  8494. });
  8495. auto res = cli_.Get("/nocompress");
  8496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8497. EXPECT_EQ(StatusCode::OK_200, res->status);
  8498. EXPECT_EQ(res->body.size(), logged_content_length);
  8499. EXPECT_EQ(std::to_string(logged_content_length),
  8500. logged_content_length_header);
  8501. }
  8502. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8503. const std::string test_content =
  8504. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8505. "3456789012345678901234567890";
  8506. std::string pre_compression_body;
  8507. bool pre_logger_called = false;
  8508. // Set only pre-compression logger
  8509. svr_.set_pre_compression_logger(
  8510. [&](const Request & /*req*/, const Response &res) {
  8511. pre_compression_body = res.body;
  8512. pre_logger_called = true;
  8513. });
  8514. Headers headers;
  8515. headers.emplace("Accept-Encoding", "gzip");
  8516. auto res = cli_.Get("/compress", headers);
  8517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8518. EXPECT_EQ(StatusCode::OK_200, res->status);
  8519. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8520. // Verify pre-compression logger was called
  8521. EXPECT_TRUE(pre_logger_called);
  8522. EXPECT_EQ(test_content, pre_compression_body);
  8523. }
  8524. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8525. {
  8526. // Test with Expect: 100-continue header - success case
  8527. // Server returns 100 Continue, client sends body, server returns 200 OK
  8528. Request req;
  8529. req.method = "POST";
  8530. req.path = "/post-large";
  8531. req.set_header("Expect", "100-continue");
  8532. req.body = LARGE_DATA;
  8533. Response res;
  8534. auto error = Error::Success;
  8535. cli_.set_keep_alive(true);
  8536. auto ret = cli_.send(req, res, error);
  8537. EXPECT_TRUE(ret);
  8538. EXPECT_EQ(StatusCode::OK_200, res.status);
  8539. EXPECT_EQ(LARGE_DATA, res.body);
  8540. }
  8541. {
  8542. // Test with Expect: 100-continue header - error case
  8543. // Client should not send the body when server returns an error
  8544. Request req;
  8545. req.method = "POST";
  8546. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8547. req.set_header("Expect", "100-continue");
  8548. req.body = LARGE_DATA;
  8549. Response res;
  8550. auto error = Error::Success;
  8551. auto start = std::chrono::high_resolution_clock::now();
  8552. cli_.set_keep_alive(true);
  8553. auto ret = cli_.send(req, res, error);
  8554. auto end = std::chrono::high_resolution_clock::now();
  8555. auto elapsed =
  8556. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8557. .count();
  8558. // With Expect: 100-continue, request completes successfully but with error
  8559. EXPECT_TRUE(ret);
  8560. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8561. EXPECT_EQ("close", res.get_header_value("Connection"));
  8562. EXPECT_FALSE(cli_.is_socket_open());
  8563. EXPECT_LE(elapsed, 2000);
  8564. }
  8565. {
  8566. // Send an extra GET request to ensure error recovery without hanging
  8567. Request req;
  8568. req.method = "GET";
  8569. req.path = "/hi";
  8570. auto start = std::chrono::high_resolution_clock::now();
  8571. auto res = cli_.send(req);
  8572. auto end = std::chrono::high_resolution_clock::now();
  8573. auto elapsed =
  8574. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8575. .count();
  8576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8577. EXPECT_EQ(StatusCode::OK_200, res->status);
  8578. EXPECT_EQ("Hello World!", res->body);
  8579. EXPECT_LE(elapsed, 500);
  8580. }
  8581. }
  8582. TEST(ZstdDecompressor, ChunkedDecompression) {
  8583. std::string data;
  8584. for (size_t i = 0; i < 32 * 1024; ++i) {
  8585. data.push_back(static_cast<char>('a' + i % 26));
  8586. }
  8587. std::string compressed_data;
  8588. {
  8589. httplib::detail::zstd_compressor compressor;
  8590. bool result = compressor.compress(
  8591. data.data(), data.size(),
  8592. /*last=*/true,
  8593. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8594. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8595. compressed_data_size);
  8596. return true;
  8597. });
  8598. ASSERT_TRUE(result);
  8599. }
  8600. std::string decompressed_data;
  8601. {
  8602. httplib::detail::zstd_decompressor decompressor;
  8603. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8604. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8605. size_t chunk_size = 130;
  8606. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8607. chunk_begin += chunk_size) {
  8608. size_t current_chunk_size =
  8609. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8610. bool result = decompressor.decompress(
  8611. compressed_data.data() + chunk_begin, current_chunk_size,
  8612. [&](const char *decompressed_data_chunk,
  8613. size_t decompressed_data_chunk_size) {
  8614. decompressed_data.insert(decompressed_data.size(),
  8615. decompressed_data_chunk,
  8616. decompressed_data_chunk_size);
  8617. return true;
  8618. });
  8619. ASSERT_TRUE(result);
  8620. }
  8621. }
  8622. ASSERT_EQ(data, decompressed_data);
  8623. }
  8624. TEST(ZstdDecompressor, Decompress) {
  8625. std::string original_text = "Compressed with ZSTD";
  8626. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8627. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8628. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8629. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8630. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8631. std::string decompressed_data;
  8632. {
  8633. httplib::detail::zstd_decompressor decompressor;
  8634. bool result = decompressor.decompress(
  8635. compressed_data.data(), compressed_data.size(),
  8636. [&](const char *decompressed_data_chunk,
  8637. size_t decompressed_data_chunk_size) {
  8638. decompressed_data.insert(decompressed_data.size(),
  8639. decompressed_data_chunk,
  8640. decompressed_data_chunk_size);
  8641. return true;
  8642. });
  8643. ASSERT_TRUE(result);
  8644. }
  8645. ASSERT_EQ(original_text, decompressed_data);
  8646. }
  8647. #endif
  8648. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8649. // separate chunks so that the server sees each part in its own read(). Used to
  8650. // place a read boundary at a specific offset of a request body.
  8651. static bool send_request_in_parts(time_t read_timeout_sec,
  8652. const std::vector<std::string> &parts,
  8653. std::string *resp = nullptr,
  8654. int port = PORT) {
  8655. auto error = Error::Success;
  8656. auto client_sock = detail::create_client_socket(
  8657. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8658. /*connection_timeout_sec=*/5, 0,
  8659. /*read_timeout_sec=*/5, 0,
  8660. /*write_timeout_sec=*/5, 0, std::string(), error);
  8661. if (client_sock == INVALID_SOCKET) { return false; }
  8662. auto ret = detail::process_client_socket(
  8663. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8664. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8665. for (size_t i = 0; i < parts.size(); i++) {
  8666. const auto &part = parts[i];
  8667. if (part.size() !=
  8668. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8669. return false;
  8670. }
  8671. if (i + 1 < parts.size()) {
  8672. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8673. }
  8674. }
  8675. char buf[512];
  8676. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8677. while (line_reader.getline()) {
  8678. if (resp) { *resp += line_reader.ptr(); }
  8679. }
  8680. return true;
  8681. });
  8682. detail::close_socket(client_sock);
  8683. return ret;
  8684. }
  8685. // Sends a raw request to a server listening at HOST:PORT.
  8686. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8687. std::string *resp = nullptr, int port = PORT) {
  8688. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8689. }
  8690. #ifdef CPPHTTPLIB_SSL_ENABLED
  8691. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  8692. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8693. ASSERT_TRUE(svr.is_valid());
  8694. svr.set_read_timeout(1, 0);
  8695. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8696. auto se = detail::scope_exit([&] {
  8697. svr.stop();
  8698. t.join();
  8699. ASSERT_FALSE(svr.is_running());
  8700. });
  8701. svr.wait_until_ready();
  8702. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  8703. // keeps each wait well within the read timeout. The server gives up a
  8704. // second in, so the bytes sent after that fail.
  8705. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  8706. parts.resize(26, std::string(1, '\0'));
  8707. EXPECT_FALSE(send_request_in_parts(5, parts));
  8708. }
  8709. #endif
  8710. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8711. Server svr;
  8712. std::string header_value;
  8713. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8714. header_value = req.get_header_value("foo");
  8715. res.set_content("ok", "text/plain");
  8716. });
  8717. thread t = thread([&] { svr.listen(HOST, PORT); });
  8718. auto se = detail::scope_exit([&] {
  8719. svr.stop();
  8720. t.join();
  8721. ASSERT_FALSE(svr.is_running());
  8722. });
  8723. svr.wait_until_ready();
  8724. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8725. // like characters are not treated the same - use vertical tab and escape.
  8726. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8727. "foo: \t \v bar \x1B\t \r\n"
  8728. "Connection: close\r\n"
  8729. "\r\n";
  8730. std::string res;
  8731. ASSERT_TRUE(send_request(5, req, &res));
  8732. EXPECT_EQ(header_value, "");
  8733. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8734. }
  8735. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8736. Server svr;
  8737. std::string received;
  8738. svr.Get("/order", [&](const Request &req, Response &res) {
  8739. received = entries_to_string(req.headers);
  8740. res.set_content("ok", "text/plain");
  8741. });
  8742. auto port = svr.bind_to_any_port(HOST);
  8743. thread t = thread([&] { svr.listen_after_bind(); });
  8744. auto se = detail::scope_exit([&] {
  8745. svr.stop();
  8746. t.join();
  8747. ASSERT_FALSE(svr.is_running());
  8748. });
  8749. svr.wait_until_ready();
  8750. const std::string req = "GET /order HTTP/1.1\r\n"
  8751. "X-First: 1\r\n"
  8752. "X-Dup: a\r\n"
  8753. "X-Second: 2\r\n"
  8754. "X-Dup: b\r\n"
  8755. "Connection: close\r\n"
  8756. "\r\n";
  8757. std::string res;
  8758. ASSERT_TRUE(send_request(5, req, &res, port));
  8759. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8760. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8761. }
  8762. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8763. Server svr;
  8764. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8765. res.set_header("Set-Cookie", "first=1");
  8766. res.set_header("X-Between", "y");
  8767. res.set_header("Set-Cookie", "second=2");
  8768. res.set_content("ok", "text/plain");
  8769. });
  8770. auto port = svr.bind_to_any_port(HOST);
  8771. thread t = thread([&] { svr.listen_after_bind(); });
  8772. auto se = detail::scope_exit([&] {
  8773. svr.stop();
  8774. t.join();
  8775. ASSERT_FALSE(svr.is_running());
  8776. });
  8777. svr.wait_until_ready();
  8778. Client cli(HOST, port);
  8779. auto res = cli.Get("/cookies");
  8780. ASSERT_TRUE(res);
  8781. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8782. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8783. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8784. }
  8785. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8786. Server svr;
  8787. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8788. auto i = new int(0);
  8789. res.set_header("Trailer", "X-Safe, X-Reflected");
  8790. res.set_chunked_content_provider(
  8791. "text/plain",
  8792. [i](size_t /*offset*/, DataSink &sink) {
  8793. if (*i == 0) {
  8794. sink.os << "body";
  8795. } else {
  8796. Headers trailer;
  8797. // A valid trailer that must survive.
  8798. trailer.emplace("X-Safe", "safe");
  8799. // Attacker-controlled value carrying CR/LF (response splitting).
  8800. trailer.emplace("X-Reflected",
  8801. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8802. // Attacker-controlled name carrying CR/LF.
  8803. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8804. sink.done_with_trailer(trailer);
  8805. }
  8806. (*i)++;
  8807. return true;
  8808. },
  8809. [i](bool /*success*/) { delete i; });
  8810. });
  8811. thread t = thread([&] { svr.listen(HOST, PORT); });
  8812. auto se = detail::scope_exit([&] {
  8813. svr.stop();
  8814. t.join();
  8815. ASSERT_FALSE(svr.is_running());
  8816. });
  8817. svr.wait_until_ready();
  8818. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8819. "Host: " + HOST +
  8820. "\r\n"
  8821. "Connection: close\r\n"
  8822. "\r\n";
  8823. std::string res;
  8824. ASSERT_TRUE(send_request(5, req, &res));
  8825. // The injected fields must not appear anywhere in the raw response.
  8826. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8827. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8828. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8829. // Invalid trailers are dropped entirely, matching set_header().
  8830. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8831. // The valid trailer still passes through.
  8832. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8833. }
  8834. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8835. Server svr;
  8836. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8837. // res.headers is a public field an application can populate directly,
  8838. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8839. // A valid header that must survive.
  8840. res.headers.emplace("X-Safe", "safe");
  8841. // Attacker-controlled value carrying CR/LF (response splitting).
  8842. res.headers.emplace("X-Reflected",
  8843. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8844. // Attacker-controlled name carrying CR/LF.
  8845. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8846. res.set_content("body", "text/plain");
  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-header 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 headers are dropped entirely, matching set_header().
  8867. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8868. // The valid header still passes through.
  8869. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8870. }
  8871. // Forward declaration: in split builds split.py strips `inline` and moves the
  8872. // definition into httplib.cc, so detail::write_request_line is not visible from
  8873. // the public httplib.h. Re-declaring it here lets the tests link against the
  8874. // symbol in both header-only and split builds.
  8875. namespace httplib {
  8876. namespace detail {
  8877. ssize_t write_request_line(Stream &strm, const std::string &method,
  8878. const std::string &path);
  8879. } // namespace detail
  8880. } // namespace httplib
  8881. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8882. // A well-formed target is written verbatim.
  8883. {
  8884. detail::BufferStream strm;
  8885. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8886. EXPECT_GT(n, 0);
  8887. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8888. }
  8889. // A target carrying CR/LF, SP or other control octets must be rejected
  8890. // before anything reaches the wire, otherwise it splits the request line and
  8891. // injects a header or a whole request.
  8892. const std::string evil_targets[] = {
  8893. "/a\r\nInjected: pwned",
  8894. "/a\rInjected",
  8895. "/a\nInjected",
  8896. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8897. "/a b",
  8898. "/a\tb",
  8899. "/a\x7f",
  8900. };
  8901. for (const auto &evil : evil_targets) {
  8902. detail::BufferStream strm;
  8903. auto n = detail::write_request_line(strm, "GET", evil);
  8904. EXPECT_LT(n, 0);
  8905. EXPECT_TRUE(strm.get_buffer().empty());
  8906. }
  8907. }
  8908. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8909. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8910. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8911. // target reaches write_request. The client must fail cleanly with
  8912. // Error::Write instead of putting a request-line-less, header-injecting
  8913. // request on the wire.
  8914. Server svr;
  8915. svr.Get("/a", [](const Request &, Response &res) {
  8916. res.set_content("ok", "text/plain");
  8917. });
  8918. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8919. auto se = detail::scope_exit([&] {
  8920. svr.stop();
  8921. thread.join();
  8922. ASSERT_FALSE(svr.is_running());
  8923. });
  8924. svr.wait_until_ready();
  8925. {
  8926. Client cli(HOST, PORT);
  8927. cli.set_path_encode(false);
  8928. // The request is rejected before anything is written, so the connection
  8929. // stays silent and the subsequent response read would otherwise block for
  8930. // the full default read timeout. Shorten it -- the assertion is on the
  8931. // error, not the timeout.
  8932. cli.set_read_timeout(1, 0);
  8933. auto res = cli.Get("/a\r\nInjected: pwned");
  8934. EXPECT_FALSE(res);
  8935. EXPECT_EQ(Error::Write, res.error());
  8936. }
  8937. }
  8938. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8939. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8940. // including extension methods.
  8941. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8942. for (const auto &method : good_methods) {
  8943. detail::BufferStream strm;
  8944. auto n = detail::write_request_line(strm, method, "/");
  8945. EXPECT_GT(n, 0);
  8946. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8947. }
  8948. // A method carrying CR/LF would split the request line and smuggle a whole
  8949. // request ahead of the real one. A space or an empty method corrupts the
  8950. // request line. All must be rejected before anything reaches the wire.
  8951. const std::string evil_methods[] = {
  8952. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8953. "GET\r\nInjected: pwned",
  8954. "GET\r",
  8955. "GET\n",
  8956. "GE T",
  8957. "",
  8958. };
  8959. for (const auto &evil : evil_methods) {
  8960. detail::BufferStream strm;
  8961. auto n = detail::write_request_line(strm, evil, "/");
  8962. EXPECT_LT(n, 0);
  8963. EXPECT_TRUE(strm.get_buffer().empty());
  8964. }
  8965. }
  8966. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  8967. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  8968. // through Client::send must fail with Error::Write and no request, neither
  8969. // the smuggled one nor the real one, may reach the server.
  8970. Server svr;
  8971. std::atomic<int> request_count(0);
  8972. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  8973. request_count++;
  8974. res.status = StatusCode::OK_200;
  8975. return Server::HandlerResponse::Handled;
  8976. });
  8977. auto port = svr.bind_to_any_port(HOST);
  8978. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8979. auto se = detail::scope_exit([&] {
  8980. svr.stop();
  8981. thread.join();
  8982. ASSERT_FALSE(svr.is_running());
  8983. });
  8984. svr.wait_until_ready();
  8985. {
  8986. Client cli(HOST, port);
  8987. const std::string evil_methods[] = {
  8988. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8989. "GE T",
  8990. "",
  8991. };
  8992. for (const auto &evil : evil_methods) {
  8993. Request req;
  8994. req.method = evil;
  8995. req.path = "/";
  8996. auto res = cli.send(req);
  8997. EXPECT_FALSE(res);
  8998. EXPECT_EQ(Error::Write, res.error());
  8999. }
  9000. auto handle =
  9001. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9002. EXPECT_FALSE(handle.is_valid());
  9003. EXPECT_EQ(Error::Write, handle.error);
  9004. // A valid request on the same client still goes through.
  9005. auto res = cli.Get("/");
  9006. ASSERT_TRUE(res);
  9007. EXPECT_EQ(StatusCode::OK_200, res->status);
  9008. }
  9009. EXPECT_EQ(1, request_count.load());
  9010. }
  9011. // Sends a raw request and verifies that there isn't a crash or exception.
  9012. static void test_raw_request(const std::string &req,
  9013. std::string *out = nullptr) {
  9014. Server svr;
  9015. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9016. res.set_content("ok", "text/plain");
  9017. });
  9018. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9019. res.set_content("ok", "text/plain");
  9020. });
  9021. svr.Get("/header_field_value_check",
  9022. [&](const Request & /*req*/, Response &res) {
  9023. res.set_content("ok", "text/plain");
  9024. });
  9025. svr.CustomRoute("PROPFIND", "/dav",
  9026. [&](const Request & /*req*/, Response &res) {
  9027. res.status = StatusCode::MultiStatus_207;
  9028. });
  9029. // Server read timeout must be longer than the client read timeout for the
  9030. // bug to reproduce, probably to force the server to process a request
  9031. // without a trailing blank line.
  9032. const time_t client_read_timeout_sec = 1;
  9033. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9034. bool listen_thread_ok = false;
  9035. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9036. auto se = detail::scope_exit([&] {
  9037. svr.stop();
  9038. t.join();
  9039. ASSERT_FALSE(svr.is_running());
  9040. EXPECT_TRUE(listen_thread_ok);
  9041. });
  9042. svr.wait_until_ready();
  9043. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9044. }
  9045. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9046. // A certain header line causes an exception if the header property is parsed
  9047. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9048. test_raw_request(
  9049. "GET /hi HTTP/1.1\r\n"
  9050. " : "
  9051. " "
  9052. " ");
  9053. }
  9054. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9055. // A certain header line causes an exception if the header property *name* is
  9056. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9057. // greedy matcher and requires backtracking when there are a lot of ":"
  9058. // characters.
  9059. // This occurs with libc++ but not libstdc++.
  9060. test_raw_request(
  9061. "GET /hi HTTP/1.1\r\n"
  9062. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9063. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9064. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9065. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9066. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9067. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9068. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9069. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9070. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9071. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9072. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9073. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9074. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9075. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9076. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9077. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9078. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9079. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9080. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9081. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9082. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9083. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9084. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9085. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9086. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9087. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9088. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9089. "&&&%%%");
  9090. }
  9091. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9092. // Make sure this doesn't crash the server.
  9093. // In a previous version of the header line regex, the "\r" rendered the line
  9094. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9095. // a new position where the leading white space ended and the field value
  9096. // began.
  9097. // The crash occurs with libc++ but not libstdc++.
  9098. test_raw_request("GET /hi HTTP/1.1\r\n"
  9099. "a:" +
  9100. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9101. "\r\n"
  9102. "\r\n");
  9103. }
  9104. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9105. std::string out;
  9106. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9107. "Content-Type: text/plain\r\n"
  9108. "Transfer-Encoding: chunked\r\n"
  9109. "\r\n"
  9110. "nothex\r\n",
  9111. &out);
  9112. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9113. }
  9114. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9115. std::string out;
  9116. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9117. "Content-Type: text/plain\r\n"
  9118. "Transfer-Encoding: chunked\r\n"
  9119. "\r\n"
  9120. "3\r\n"
  9121. "xyz\r\n"
  9122. "NaN\r\n",
  9123. &out);
  9124. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9125. }
  9126. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9127. std::string out;
  9128. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9129. "Content-Type: text/plain\r\n"
  9130. "Transfer-Encoding: chunked\r\n"
  9131. "\r\n"
  9132. // Length is too large for 64 bits.
  9133. "1ffffffffffffffff\r\n"
  9134. "xyz\r\n",
  9135. &out);
  9136. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9137. }
  9138. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9139. test_raw_request("GET /hi HTTP/1.1\r\n"
  9140. "Content-Type: text/plain\r\n\r");
  9141. }
  9142. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9143. std::string out;
  9144. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9145. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9146. }
  9147. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9148. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9149. std::string out;
  9150. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9151. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9152. }
  9153. }
  9154. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9155. std::string out;
  9156. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9157. "Connection: close\r\n\r\n",
  9158. &out);
  9159. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9160. }
  9161. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9162. Server svr;
  9163. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9164. EXPECT_TRUE(!req.remote_addr.empty());
  9165. });
  9166. thread t = thread([&] { svr.listen(HOST, PORT); });
  9167. auto se = detail::scope_exit([&] {
  9168. svr.stop();
  9169. t.join();
  9170. ASSERT_FALSE(svr.is_running());
  9171. });
  9172. svr.wait_until_ready();
  9173. // Send an invalid request line to trigger Bad Request
  9174. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9175. std::string out;
  9176. ASSERT_TRUE(send_request(5, bad_req, &out));
  9177. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9178. }
  9179. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9180. // answered right away rather than blocking on a read that waits for EOF.
  9181. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9182. std::string out;
  9183. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9184. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9185. }
  9186. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9187. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9188. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9189. for (const auto *method : methods) {
  9190. Server svr;
  9191. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9192. EXPECT_FALSE(svr.is_valid()) << method;
  9193. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9194. }
  9195. }
  9196. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9197. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9198. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9199. for (const auto *method : methods) {
  9200. Server svr;
  9201. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9202. EXPECT_FALSE(svr.is_valid()) << method;
  9203. }
  9204. }
  9205. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9206. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9207. "COPY", "MOVE", "LOCK",
  9208. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9209. Server svr;
  9210. for (const auto *method : methods) {
  9211. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9212. }
  9213. EXPECT_TRUE(svr.is_valid());
  9214. }
  9215. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9216. Server svr;
  9217. svr.CustomRoute("POST", "/x",
  9218. [](const Request &, Response &, const ContentReader &) {});
  9219. EXPECT_FALSE(svr.is_valid());
  9220. }
  9221. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9222. Server svr;
  9223. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9224. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9225. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9226. EXPECT_FALSE(svr.is_valid());
  9227. }
  9228. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9229. Server svr;
  9230. auto captured = Error::Success;
  9231. svr.set_error_logger(
  9232. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9233. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9234. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9235. }
  9236. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9237. std::string out;
  9238. std::string request(
  9239. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9240. test_raw_request(request, &out);
  9241. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9242. }
  9243. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9244. std::string out;
  9245. std::string request(
  9246. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9247. test_raw_request(request, &out);
  9248. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9249. }
  9250. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9251. std::string out;
  9252. std::string request(
  9253. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9254. test_raw_request(request, &out);
  9255. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9256. }
  9257. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9258. std::string out;
  9259. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9260. "Test: \r\n\r\n",
  9261. &out);
  9262. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9263. }
  9264. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9265. Server svr;
  9266. std::string x_custom;
  9267. std::string cookie;
  9268. std::string xff;
  9269. std::string x_unicode;
  9270. std::string x_iis;
  9271. svr.Get("/check", [&](const Request &req, Response &res) {
  9272. x_custom = req.get_header_value("X-Custom");
  9273. cookie = req.get_header_value("Cookie");
  9274. xff = req.get_header_value("X-Forwarded-For");
  9275. x_unicode = req.get_header_value("X-Unicode");
  9276. x_iis = req.get_header_value("X-IIS");
  9277. res.set_content("ok", "text/plain");
  9278. });
  9279. thread t = thread([&] { svr.listen(HOST, PORT); });
  9280. auto se = detail::scope_exit([&] {
  9281. svr.stop();
  9282. t.join();
  9283. ASSERT_FALSE(svr.is_running());
  9284. });
  9285. svr.wait_until_ready();
  9286. const std::string req = "GET /check HTTP/1.1\r\n"
  9287. "Host: localhost\r\n"
  9288. "X-Custom: a%0D%0AInjected: b\r\n"
  9289. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9290. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9291. "X-Unicode: %E3%81%82\r\n"
  9292. "X-IIS: %u00E9\r\n"
  9293. "Connection: close\r\n"
  9294. "\r\n";
  9295. std::string res;
  9296. ASSERT_TRUE(send_request(5, req, &res));
  9297. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9298. // Every value must be returned verbatim (wire form), with no decoding.
  9299. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9300. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9301. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9302. EXPECT_EQ("%E3%81%82", x_unicode);
  9303. EXPECT_EQ("%u00E9", x_iis);
  9304. }
  9305. // Applications that previously relied on automatic percent-decoding can
  9306. // reproduce the old behavior by explicitly calling decode_path_component()
  9307. // or, for RFC 3986 conformance, decode_uri_component().
  9308. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9309. Server svr;
  9310. std::string decoded;
  9311. svr.Get("/check", [&](const Request &req, Response &res) {
  9312. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9313. res.set_content("ok", "text/plain");
  9314. });
  9315. thread t = thread([&] { svr.listen(HOST, PORT); });
  9316. auto se = detail::scope_exit([&] {
  9317. svr.stop();
  9318. t.join();
  9319. ASSERT_FALSE(svr.is_running());
  9320. });
  9321. svr.wait_until_ready();
  9322. const std::string req = "GET /check HTTP/1.1\r\n"
  9323. "Host: localhost\r\n"
  9324. "X-Custom: hello%20world\r\n"
  9325. "Connection: close\r\n"
  9326. "\r\n";
  9327. std::string res;
  9328. ASSERT_TRUE(send_request(5, req, &res));
  9329. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9330. EXPECT_EQ("hello world", decoded);
  9331. }
  9332. // Regression test for #2033. Browsers send Referer values that include
  9333. // percent-encoded characters such as %0A inside the URL. Decoding the
  9334. // header value would either trip the post-decode CR/LF/NUL guard (the
  9335. // original bug, returning 400) or, after that guard was relaxed, silently
  9336. // store a literal LF — both unacceptable. The wire form must round-trip.
  9337. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9338. Server svr;
  9339. std::string referer;
  9340. svr.Get("/check", [&](const Request &req, Response &res) {
  9341. referer = req.get_header_value("Referer");
  9342. res.set_content("ok", "text/plain");
  9343. });
  9344. thread t = thread([&] { svr.listen(HOST, PORT); });
  9345. auto se = detail::scope_exit([&] {
  9346. svr.stop();
  9347. t.join();
  9348. ASSERT_FALSE(svr.is_running());
  9349. });
  9350. svr.wait_until_ready();
  9351. const std::string req = "GET /check HTTP/1.1\r\n"
  9352. "Host: localhost\r\n"
  9353. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9354. "Connection: close\r\n"
  9355. "\r\n";
  9356. std::string res;
  9357. ASSERT_TRUE(send_request(5, req, &res));
  9358. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9359. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9360. }
  9361. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9362. Server svr;
  9363. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9364. res.set_header("Cache-Control", "no-cache");
  9365. res.set_chunked_content_provider(
  9366. "text/event-stream", [](size_t offset, DataSink &sink) {
  9367. std::string s = "data:";
  9368. s += std::to_string(offset);
  9369. s += "\n\n";
  9370. auto ret = sink.write(s.data(), s.size());
  9371. EXPECT_TRUE(ret);
  9372. std::this_thread::sleep_for(std::chrono::seconds(1));
  9373. return true;
  9374. });
  9375. });
  9376. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9377. svr.wait_until_ready();
  9378. Client client(HOST, PORT);
  9379. const Headers headers = {{"Accept", "text/event-stream"}};
  9380. auto get_thread = std::thread([&client, &headers]() {
  9381. auto res = client.Get(
  9382. "/events", headers,
  9383. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9384. });
  9385. auto se = detail::scope_exit([&] {
  9386. svr.stop();
  9387. get_thread.join();
  9388. listen_thread.join();
  9389. ASSERT_FALSE(svr.is_running());
  9390. });
  9391. // Give GET time to get a few messages.
  9392. std::this_thread::sleep_for(std::chrono::seconds(2));
  9393. }
  9394. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9395. httplib::Server svr;
  9396. svr.Post("/hi",
  9397. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9398. res.status = StatusCode::OK_200;
  9399. });
  9400. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9401. svr.wait_until_ready();
  9402. Client cli(HOST, PORT);
  9403. auto res = cli.Post("/hi", "data", "text/plain");
  9404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9405. EXPECT_EQ(StatusCode::OK_200, res->status);
  9406. svr.stop();
  9407. thread.join();
  9408. ASSERT_FALSE(svr.is_running());
  9409. res = cli.Post("/hi", "data", "text/plain");
  9410. ASSERT_FALSE(res);
  9411. }
  9412. TEST(ServerStopTest, ListenFailure) {
  9413. Server svr;
  9414. auto t = thread([&]() {
  9415. auto ret = svr.listen("????", PORT);
  9416. EXPECT_FALSE(ret);
  9417. });
  9418. svr.wait_until_ready();
  9419. svr.stop();
  9420. t.join();
  9421. }
  9422. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9423. TEST(ServerStopTest, Decommision) {
  9424. Server svr;
  9425. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9426. for (int i = 0; i < 4; i++) {
  9427. auto is_even = !(i % 2);
  9428. std::thread t{[&] {
  9429. try {
  9430. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9431. if (is_even) {
  9432. throw std::runtime_error("Some thing that happens to go wrong.");
  9433. }
  9434. svr.listen(HOST, PORT);
  9435. } catch (...) { svr.decommission(); }
  9436. }};
  9437. svr.wait_until_ready();
  9438. // Server is up
  9439. {
  9440. Client cli(HOST, PORT);
  9441. auto res = cli.Get("/hi");
  9442. if (is_even) {
  9443. EXPECT_FALSE(res);
  9444. } else {
  9445. EXPECT_TRUE(res);
  9446. EXPECT_EQ("hi...", res->body);
  9447. }
  9448. }
  9449. svr.stop();
  9450. t.join();
  9451. // Server is down...
  9452. {
  9453. Client cli(HOST, PORT);
  9454. auto res = cli.Get("/hi");
  9455. EXPECT_FALSE(res);
  9456. }
  9457. }
  9458. }
  9459. #endif
  9460. // Helper function for string body upload progress tests
  9461. template <typename SetupHandler, typename ClientCall>
  9462. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9463. ClientCall &&client_call,
  9464. const string &body) {
  9465. Server svr;
  9466. setup_handler(svr);
  9467. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9468. auto se = detail::scope_exit([&] {
  9469. svr.stop();
  9470. t.join();
  9471. });
  9472. svr.wait_until_ready();
  9473. Client cli(HOST, PORT);
  9474. vector<uint64_t> progress_values;
  9475. bool progress_called = false;
  9476. auto res =
  9477. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9478. progress_values.push_back(current);
  9479. progress_called = true;
  9480. return true;
  9481. });
  9482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9483. EXPECT_EQ(200, res->status);
  9484. EXPECT_TRUE(progress_called);
  9485. }
  9486. TEST(UploadProgressTest, PostStringBodyBasic) {
  9487. TestStringBodyUploadProgress(
  9488. [](Server &svr) {
  9489. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9490. res.set_content("received", "text/plain");
  9491. });
  9492. },
  9493. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9494. return cli.Post("/test", body, "text/plain", progress_callback);
  9495. },
  9496. "test data for upload progress");
  9497. }
  9498. TEST(UploadProgressTest, PutStringBodyBasic) {
  9499. TestStringBodyUploadProgress(
  9500. [](Server &svr) {
  9501. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9502. res.set_content("put received", "text/plain");
  9503. });
  9504. },
  9505. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9506. return cli.Put("/test", body, "text/plain", progress_callback);
  9507. },
  9508. "put test data for upload progress");
  9509. }
  9510. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9511. TestStringBodyUploadProgress(
  9512. [](Server &svr) {
  9513. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9514. res.set_content("patch received", "text/plain");
  9515. });
  9516. },
  9517. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9518. return cli.Patch("/test", body, "text/plain", progress_callback);
  9519. },
  9520. "patch test data for upload progress");
  9521. }
  9522. // Helper function for content provider upload progress tests
  9523. template <typename SetupHandler, typename ClientCall>
  9524. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9525. ClientCall &&client_call) {
  9526. Server svr;
  9527. setup_handler(svr);
  9528. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9529. auto se = detail::scope_exit([&] {
  9530. svr.stop();
  9531. t.join();
  9532. });
  9533. svr.wait_until_ready();
  9534. Client cli(HOST, PORT);
  9535. vector<uint64_t> progress_values;
  9536. auto res =
  9537. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9538. progress_values.push_back(current);
  9539. return true;
  9540. });
  9541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9542. EXPECT_EQ(200, res->status);
  9543. EXPECT_FALSE(progress_values.empty());
  9544. }
  9545. TEST(UploadProgressTest, PostContentProviderProgress) {
  9546. TestContentProviderUploadProgress(
  9547. [](Server &svr) {
  9548. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9549. res.set_content("provider received", "text/plain");
  9550. });
  9551. },
  9552. [](Client &cli, UploadProgress progress_callback) {
  9553. return cli.Post(
  9554. "/test", 10,
  9555. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9556. sink.os << "test data";
  9557. return true;
  9558. },
  9559. "text/plain", progress_callback);
  9560. });
  9561. }
  9562. // Helper function for multipart upload progress tests
  9563. template <typename SetupHandler, typename ClientCall>
  9564. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9565. ClientCall &&client_call,
  9566. const string &endpoint) {
  9567. Server svr;
  9568. setup_handler(svr);
  9569. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9570. auto se = detail::scope_exit([&] {
  9571. svr.stop();
  9572. t.join();
  9573. });
  9574. svr.wait_until_ready();
  9575. Client cli(HOST, PORT);
  9576. vector<uint64_t> progress_values;
  9577. UploadFormDataItems items = {
  9578. {"field1", "value1", "", ""},
  9579. {"field2", "longer value for progress tracking test", "", ""},
  9580. {"file1", "file content data for upload progress", "test.txt",
  9581. "text/plain"}};
  9582. auto res = client_call(cli, endpoint, items,
  9583. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9584. progress_values.push_back(current);
  9585. return true;
  9586. });
  9587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9588. EXPECT_EQ(200, res->status);
  9589. EXPECT_FALSE(progress_values.empty());
  9590. }
  9591. TEST(UploadProgressTest, PostMultipartProgress) {
  9592. TestMultipartUploadProgress(
  9593. [](Server &svr) {
  9594. svr.Post("/multipart", [](const Request &req, Response &res) {
  9595. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9596. res.set_content("multipart received", "text/plain");
  9597. });
  9598. },
  9599. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9600. UploadProgress progress_callback) {
  9601. return cli.Post(endpoint, items, progress_callback);
  9602. },
  9603. "/multipart");
  9604. }
  9605. // Helper function for basic download progress tests
  9606. template <typename SetupHandler, typename ClientCall>
  9607. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9608. ClientCall &&client_call, const string &endpoint,
  9609. size_t expected_content_size) {
  9610. Server svr;
  9611. setup_handler(svr);
  9612. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9613. auto se = detail::scope_exit([&] {
  9614. svr.stop();
  9615. t.join();
  9616. });
  9617. svr.wait_until_ready();
  9618. Client cli(HOST, PORT);
  9619. vector<uint64_t> progress_values;
  9620. auto res = client_call(cli, endpoint,
  9621. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9622. progress_values.push_back(current);
  9623. return true;
  9624. });
  9625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9626. EXPECT_EQ(200, res->status);
  9627. EXPECT_FALSE(progress_values.empty());
  9628. EXPECT_EQ(expected_content_size, res->body.size());
  9629. }
  9630. TEST(DownloadProgressTest, GetBasic) {
  9631. TestBasicDownloadProgress(
  9632. [](Server &svr) {
  9633. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9634. string content(1000, 'D');
  9635. res.set_content(content, "text/plain");
  9636. });
  9637. },
  9638. [](Client &cli, const string &endpoint,
  9639. DownloadProgress progress_callback) {
  9640. return cli.Get(endpoint, progress_callback);
  9641. },
  9642. "/download", 1000u);
  9643. }
  9644. // Helper function for content receiver download progress tests
  9645. template <typename SetupHandler, typename ClientCall>
  9646. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9647. ClientCall &&client_call,
  9648. const string &endpoint,
  9649. size_t expected_content_size) {
  9650. Server svr;
  9651. setup_handler(svr);
  9652. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9653. auto se = detail::scope_exit([&] {
  9654. svr.stop();
  9655. t.join();
  9656. });
  9657. svr.wait_until_ready();
  9658. Client cli(HOST, PORT);
  9659. vector<uint64_t> progress_values;
  9660. string received_body;
  9661. auto res = client_call(
  9662. cli, endpoint,
  9663. [&](const char *data, size_t data_length) -> bool {
  9664. received_body.append(data, data_length);
  9665. return true;
  9666. },
  9667. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9668. progress_values.push_back(current);
  9669. return true;
  9670. });
  9671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9672. EXPECT_EQ(200, res->status);
  9673. EXPECT_FALSE(progress_values.empty());
  9674. EXPECT_EQ(expected_content_size, received_body.size());
  9675. EXPECT_TRUE(res->body.empty());
  9676. }
  9677. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9678. TestContentReceiverDownloadProgress(
  9679. [](Server &svr) {
  9680. svr.Get("/download-receiver",
  9681. [](const Request & /*req*/, Response &res) {
  9682. string content(2000, 'R');
  9683. res.set_content(content, "text/plain");
  9684. });
  9685. },
  9686. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9687. DownloadProgress progress_callback) {
  9688. return cli.Get(endpoint, content_receiver, progress_callback);
  9689. },
  9690. "/download-receiver", 2000u);
  9691. }
  9692. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9693. // A provider reaching a pass with nothing to hand over - an empty buffer
  9694. // popped off a queue, say - must not be taken to mean the body is finished.
  9695. // It used to end the loop with the terminating chunk unwritten while the
  9696. // server still considered the response complete, so the peer waited for an
  9697. // end that never arrived.
  9698. Server svr;
  9699. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9700. auto step = std::make_shared<int>(0);
  9701. res.set_chunked_content_provider("text/plain",
  9702. [step](size_t /*offset*/, DataSink &sink) {
  9703. switch ((*step)++) {
  9704. case 0: sink.write("", 0); break;
  9705. case 1: sink.write("hello", 5); break;
  9706. default: sink.done(); break;
  9707. }
  9708. return true;
  9709. });
  9710. });
  9711. auto port = svr.bind_to_any_port(HOST);
  9712. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9713. auto listen_se = detail::scope_exit([&] {
  9714. svr.stop();
  9715. listen_thread.join();
  9716. ASSERT_FALSE(svr.is_running());
  9717. });
  9718. svr.wait_until_ready();
  9719. Client cli(HOST, port);
  9720. // Without the fix the body is never terminated, so bound the wait rather
  9721. // than letting the test hang on the default read timeout.
  9722. cli.set_read_timeout(5, 0);
  9723. auto res = cli.Get("/stream");
  9724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9725. EXPECT_EQ(StatusCode::OK_200, res->status);
  9726. EXPECT_EQ("hello", res->body);
  9727. }
  9728. TEST(StreamingTest, NoContentLengthStreaming) {
  9729. Server svr;
  9730. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9731. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9732. if (offset < 6) {
  9733. sink.os << (offset < 3 ? "a" : "b");
  9734. } else {
  9735. sink.done();
  9736. }
  9737. return true;
  9738. });
  9739. });
  9740. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9741. auto listen_se = detail::scope_exit([&] {
  9742. svr.stop();
  9743. listen_thread.join();
  9744. ASSERT_FALSE(svr.is_running());
  9745. });
  9746. svr.wait_until_ready();
  9747. Client client(HOST, PORT);
  9748. auto get_thread = std::thread([&client]() {
  9749. std::string s;
  9750. auto res =
  9751. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9752. s += std::string(data, len);
  9753. return true;
  9754. });
  9755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9756. EXPECT_EQ(StatusCode::OK_200, res->status);
  9757. EXPECT_EQ("aaabbb", s);
  9758. });
  9759. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9760. // Give GET time to get a few messages.
  9761. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9762. }
  9763. TEST(MountTest, Unmount) {
  9764. Server svr;
  9765. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9766. auto se = detail::scope_exit([&] {
  9767. svr.stop();
  9768. listen_thread.join();
  9769. ASSERT_FALSE(svr.is_running());
  9770. });
  9771. svr.wait_until_ready();
  9772. Client cli("localhost", PORT);
  9773. svr.set_mount_point("/mount2", "./www2");
  9774. auto res = cli.Get("/");
  9775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9776. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9777. res = cli.Get("/mount2/dir/test.html");
  9778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9779. EXPECT_EQ(StatusCode::OK_200, res->status);
  9780. svr.set_mount_point("/", "./www");
  9781. res = cli.Get("/dir/");
  9782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9783. EXPECT_EQ(StatusCode::OK_200, res->status);
  9784. svr.remove_mount_point("/");
  9785. res = cli.Get("/dir/");
  9786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9787. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9788. svr.remove_mount_point("/mount2");
  9789. res = cli.Get("/mount2/dir/test.html");
  9790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9791. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9792. }
  9793. TEST(MountTest, PathSegmentBoundary) {
  9794. Server svr;
  9795. svr.set_mount_point("/mount2", "./www2");
  9796. svr.set_mount_point("/", "./www");
  9797. auto port = svr.bind_to_any_port(HOST);
  9798. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9799. auto se = detail::scope_exit([&] {
  9800. svr.stop();
  9801. listen_thread.join();
  9802. ASSERT_FALSE(svr.is_running());
  9803. });
  9804. svr.wait_until_ready();
  9805. Client cli(HOST, port);
  9806. auto res = cli.Get("/mount2/dir/test.html");
  9807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9808. EXPECT_EQ(StatusCode::OK_200, res->status);
  9809. // "/mount2" must not match part-way through a path segment.
  9810. res = cli.Get("/mount2dir/test.html");
  9811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9812. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9813. // A mount point ending in '/' keeps matching every path below it.
  9814. res = cli.Get("/dir/test.html");
  9815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9816. EXPECT_EQ(StatusCode::OK_200, res->status);
  9817. }
  9818. TEST(MountTest, Redicect) {
  9819. Server svr;
  9820. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9821. auto se = detail::scope_exit([&] {
  9822. svr.stop();
  9823. listen_thread.join();
  9824. ASSERT_FALSE(svr.is_running());
  9825. });
  9826. svr.set_mount_point("/", "./www");
  9827. svr.wait_until_ready();
  9828. Client cli("localhost", PORT);
  9829. auto res = cli.Get("/dir/");
  9830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9831. EXPECT_EQ(StatusCode::OK_200, res->status);
  9832. res = cli.Get("/dir");
  9833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9834. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9835. res = cli.Get("/file");
  9836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9837. EXPECT_EQ(StatusCode::OK_200, res->status);
  9838. res = cli.Get("/file/");
  9839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9840. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9841. cli.set_follow_location(true);
  9842. res = cli.Get("/dir");
  9843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9844. EXPECT_EQ(StatusCode::OK_200, res->status);
  9845. }
  9846. TEST(MountTest, MultibytesPathName) {
  9847. Server svr;
  9848. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9849. auto se = detail::scope_exit([&] {
  9850. svr.stop();
  9851. listen_thread.join();
  9852. ASSERT_FALSE(svr.is_running());
  9853. });
  9854. svr.set_mount_point("/", "./www");
  9855. svr.wait_until_ready();
  9856. Client cli("localhost", PORT);
  9857. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9859. EXPECT_EQ(StatusCode::OK_200, res->status);
  9860. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9861. }
  9862. #ifdef _WIN32
  9863. // Issue #2435: mmap::open() must succeed even when another handle holds
  9864. // the file open for writing (e.g. an active log file).
  9865. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9866. const char *path = "mmap_concurrent_writer_test.txt";
  9867. const char *content = "hello";
  9868. {
  9869. std::ofstream f(path, std::ios::binary);
  9870. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9871. }
  9872. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9873. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9874. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9875. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9876. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9877. detail::mmap m(path);
  9878. ASSERT_TRUE(m.is_open());
  9879. EXPECT_EQ(strlen(content), m.size());
  9880. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9881. }
  9882. #endif
  9883. #ifndef _WIN32
  9884. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9885. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9886. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9887. TEST(MmapTest, FailedMappingIsNotOpen) {
  9888. const char *path = "./mmap_failed_mapping_test_dir";
  9889. ASSERT_EQ(0, ::mkdir(path, 0755));
  9890. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9891. detail::mmap m(path);
  9892. EXPECT_FALSE(m.is_open());
  9893. EXPECT_EQ(0U, m.size());
  9894. EXPECT_NE(static_cast<const void *>(m.data()),
  9895. static_cast<const void *>(MAP_FAILED));
  9896. }
  9897. #endif
  9898. TEST(KeepAliveTest, ReadTimeout) {
  9899. Server svr;
  9900. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9901. std::this_thread::sleep_for(std::chrono::seconds(2));
  9902. res.set_content("a", "text/plain");
  9903. });
  9904. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9905. res.set_content("b", "text/plain");
  9906. });
  9907. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9908. auto se = detail::scope_exit([&] {
  9909. svr.stop();
  9910. listen_thread.join();
  9911. ASSERT_FALSE(svr.is_running());
  9912. });
  9913. svr.wait_until_ready();
  9914. Client cli("localhost", PORT);
  9915. cli.set_keep_alive(true);
  9916. cli.set_read_timeout(std::chrono::seconds(1));
  9917. auto resa = cli.Get("/a");
  9918. ASSERT_FALSE(resa);
  9919. EXPECT_EQ(Error::Read, resa.error());
  9920. auto resb = cli.Get("/b");
  9921. ASSERT_TRUE(resb);
  9922. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9923. EXPECT_EQ("b", resb->body);
  9924. }
  9925. TEST(KeepAliveTest, MaxCount) {
  9926. size_t keep_alive_max_count = 3;
  9927. Server svr;
  9928. svr.set_keep_alive_max_count(keep_alive_max_count);
  9929. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9930. res.set_content("Hello World!", "text/plain");
  9931. });
  9932. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9933. auto se = detail::scope_exit([&] {
  9934. svr.stop();
  9935. listen_thread.join();
  9936. ASSERT_FALSE(svr.is_running());
  9937. });
  9938. svr.wait_until_ready();
  9939. Client cli(HOST, PORT);
  9940. cli.set_keep_alive(true);
  9941. for (size_t i = 0; i < 5; i++) {
  9942. auto result = cli.Get("/hi");
  9943. ASSERT_TRUE(result);
  9944. EXPECT_EQ(StatusCode::OK_200, result->status);
  9945. if (i == keep_alive_max_count - 1) {
  9946. EXPECT_EQ("close", result->get_header_value("Connection"));
  9947. } else {
  9948. EXPECT_FALSE(result->has_header("Connection"));
  9949. }
  9950. }
  9951. }
  9952. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  9953. // can pull the next one into the server's buffer. The server must serve it
  9954. // without waiting for the socket to become readable again. The keep-alive
  9955. // timeout outlasts the client's read timeout, so a request left waiting for it
  9956. // shows up as a missing response.
  9957. static void serve_pipelining_routes(Server &svr,
  9958. const std::function<void(int)> &client) {
  9959. svr.set_keep_alive_timeout(5);
  9960. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  9961. res.set_content("hi " + req.matches[1].str(), "text/plain");
  9962. });
  9963. svr.Post("/echo", [](const Request &req, Response &res) {
  9964. res.set_content("echo " + req.body, "text/plain");
  9965. });
  9966. auto port = svr.bind_to_any_port(HOST);
  9967. thread t = thread([&] { svr.listen_after_bind(); });
  9968. auto se = detail::scope_exit([&] {
  9969. svr.stop();
  9970. t.join();
  9971. });
  9972. svr.wait_until_ready();
  9973. client(port);
  9974. }
  9975. static std::string
  9976. send_pipelined_requests(const std::vector<std::string> &parts) {
  9977. Server svr;
  9978. std::string res;
  9979. serve_pipelining_routes(svr, [&](int port) {
  9980. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  9981. });
  9982. return res;
  9983. }
  9984. static void expect_in_order(const std::string &res,
  9985. const std::vector<std::string> &bodies) {
  9986. size_t pos = 0;
  9987. for (const auto &body : bodies) {
  9988. pos = res.find(body, pos);
  9989. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  9990. pos += body.size();
  9991. }
  9992. }
  9993. TEST(KeepAliveTest, PipelinedRequests) {
  9994. auto res = send_pipelined_requests(
  9995. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9996. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9997. "Content-Length: 4\r\n\r\nbody"
  9998. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9999. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10000. }
  10001. // The second request starts in the server's buffer and ends on the socket.
  10002. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10003. auto res =
  10004. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10005. "GET /hi/2 HTTP/1.1\r\nHo",
  10006. "st: localhost\r\nConnection: close\r\n\r\n"});
  10007. expect_in_order(res, {"hi 1", "hi 2"});
  10008. }
  10009. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10010. // CRLF after a body does not turn into a 400 for the next request.
  10011. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10012. auto res = send_pipelined_requests(
  10013. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10014. "Content-Length: 4\r\n\r\nbody\r\n"
  10015. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10016. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10017. expect_in_order(res, {"echo body", "hi 2"});
  10018. }
  10019. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10020. // must not be served as the next request.
  10021. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10022. auto res = send_pipelined_requests(
  10023. {"INVALID REQUEST LINE\r\n\r\n"
  10024. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10025. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10026. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10027. }
  10028. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10029. // Over TLS, the next request is held by the TLS library as already decrypted
  10030. // data rather than on the socket.
  10031. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10032. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10033. std::string res;
  10034. serve_pipelining_routes(svr, [&](int port) {
  10035. auto error = Error::Success;
  10036. auto sock = detail::create_client_socket(
  10037. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10038. /*connection_timeout_sec=*/5, 0,
  10039. /*read_timeout_sec=*/2, 0,
  10040. /*write_timeout_sec=*/5, 0, std::string(), error);
  10041. ASSERT_NE(INVALID_SOCKET, sock);
  10042. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  10043. auto ctx = SSL_CTX_new(TLS_client_method());
  10044. auto ssl = SSL_new(ctx);
  10045. auto ssl_se = detail::scope_exit([&] {
  10046. SSL_free(ssl);
  10047. SSL_CTX_free(ctx);
  10048. });
  10049. SSL_set_fd(ssl, static_cast<int>(sock));
  10050. ASSERT_EQ(1, SSL_connect(ssl));
  10051. // One write, so all three requests arrive in one TLS record
  10052. const std::string req =
  10053. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10054. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10055. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  10056. ASSERT_EQ(static_cast<int>(req.size()),
  10057. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  10058. char buf[512];
  10059. int n;
  10060. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10061. res.append(buf, static_cast<size_t>(n));
  10062. }
  10063. });
  10064. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10065. }
  10066. #endif
  10067. TEST(KeepAliveTest, Issue1041) {
  10068. Server svr;
  10069. svr.set_keep_alive_timeout(3);
  10070. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10071. res.set_content("Hello World!", "text/plain");
  10072. });
  10073. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10074. auto se = detail::scope_exit([&] {
  10075. svr.stop();
  10076. listen_thread.join();
  10077. ASSERT_FALSE(svr.is_running());
  10078. });
  10079. svr.wait_until_ready();
  10080. Client cli(HOST, PORT);
  10081. cli.set_keep_alive(true);
  10082. auto result = cli.Get("/hi");
  10083. ASSERT_TRUE(result);
  10084. EXPECT_EQ(StatusCode::OK_200, result->status);
  10085. std::this_thread::sleep_for(std::chrono::seconds(5));
  10086. result = cli.Get("/hi");
  10087. ASSERT_TRUE(result);
  10088. EXPECT_EQ(StatusCode::OK_200, result->status);
  10089. }
  10090. TEST(KeepAliveTest, Issue1959) {
  10091. Server svr;
  10092. svr.set_keep_alive_timeout(5);
  10093. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10094. res.set_content("a", "text/plain");
  10095. });
  10096. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10097. auto se = detail::scope_exit([&] {
  10098. if (!svr.is_running()) return;
  10099. svr.stop();
  10100. listen_thread.join();
  10101. ASSERT_FALSE(svr.is_running());
  10102. });
  10103. svr.wait_until_ready();
  10104. Client cli("localhost", PORT);
  10105. cli.set_keep_alive(true);
  10106. using namespace std::chrono;
  10107. auto start = steady_clock::now();
  10108. cli.Get("/a");
  10109. svr.stop();
  10110. listen_thread.join();
  10111. auto end = steady_clock::now();
  10112. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10113. EXPECT_LT(elapsed, 5000);
  10114. }
  10115. #ifdef CPPHTTPLIB_SSL_ENABLED
  10116. TEST(KeepAliveTest, SSLClientReconnection) {
  10117. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10118. ASSERT_TRUE(svr.is_valid());
  10119. svr.set_keep_alive_timeout(1);
  10120. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10121. res.set_content("Hello World!", "text/plain");
  10122. });
  10123. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10124. auto se = detail::scope_exit([&] {
  10125. svr.stop();
  10126. listen_thread.join();
  10127. ASSERT_FALSE(svr.is_running());
  10128. });
  10129. svr.wait_until_ready();
  10130. SSLClient cli(HOST, PORT);
  10131. cli.enable_server_certificate_verification(false);
  10132. cli.set_keep_alive(true);
  10133. auto result = cli.Get("/hi");
  10134. ASSERT_TRUE(result);
  10135. EXPECT_EQ(StatusCode::OK_200, result->status);
  10136. result = cli.Get("/hi");
  10137. ASSERT_TRUE(result);
  10138. EXPECT_EQ(StatusCode::OK_200, result->status);
  10139. std::this_thread::sleep_for(std::chrono::seconds(2));
  10140. // Recoonect
  10141. result = cli.Get("/hi");
  10142. ASSERT_TRUE(result);
  10143. EXPECT_EQ(StatusCode::OK_200, result->status);
  10144. result = cli.Get("/hi");
  10145. ASSERT_TRUE(result);
  10146. EXPECT_EQ(StatusCode::OK_200, result->status);
  10147. }
  10148. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10149. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10150. ASSERT_TRUE(svr.is_valid());
  10151. svr.set_keep_alive_timeout(1);
  10152. std::string content = "reconnect";
  10153. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10154. res.set_content("Hello World!", "text/plain");
  10155. });
  10156. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10157. auto se = detail::scope_exit([&] {
  10158. svr.stop();
  10159. listen_thread.join();
  10160. ASSERT_FALSE(svr.is_running());
  10161. });
  10162. svr.wait_until_ready();
  10163. SSLClient cli(HOST, PORT);
  10164. cli.enable_server_certificate_verification(false);
  10165. cli.set_keep_alive(true);
  10166. auto result = cli.Post(
  10167. "/hi", content.size(),
  10168. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10169. sink.write(content.c_str(), content.size());
  10170. return true;
  10171. },
  10172. "text/plain");
  10173. ASSERT_TRUE(result);
  10174. EXPECT_EQ(200, result->status);
  10175. std::this_thread::sleep_for(std::chrono::seconds(2));
  10176. // Recoonect
  10177. result = cli.Post(
  10178. "/hi", content.size(),
  10179. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10180. sink.write(content.c_str(), content.size());
  10181. return true;
  10182. },
  10183. "text/plain");
  10184. ASSERT_TRUE(result);
  10185. EXPECT_EQ(200, result->status);
  10186. result = cli.Post(
  10187. "/hi", content.size(),
  10188. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10189. sink.write(content.c_str(), content.size());
  10190. return true;
  10191. },
  10192. "text/plain");
  10193. ASSERT_TRUE(result);
  10194. EXPECT_EQ(200, result->status);
  10195. }
  10196. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10197. using namespace httplib::tls;
  10198. {
  10199. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10200. ASSERT_TRUE(svr.is_valid());
  10201. svr.Get("/sni", [&](const Request &req, Response &res) {
  10202. std::string expected = req.sni();
  10203. EXPECT_EQ(expected, req.get_param_value("expected"));
  10204. res.set_content("ok", "text/plain");
  10205. });
  10206. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10207. auto se = detail::scope_exit([&] {
  10208. svr.stop();
  10209. listen_thread.join();
  10210. ASSERT_FALSE(svr.is_running());
  10211. });
  10212. svr.wait_until_ready();
  10213. {
  10214. SSLClient cli("localhost", PORT);
  10215. cli.enable_server_certificate_verification(false);
  10216. auto res = cli.Get("/sni?expected=localhost");
  10217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10218. }
  10219. {
  10220. SSLClient cli("::1", PORT);
  10221. cli.enable_server_certificate_verification(false);
  10222. auto res = cli.Get("/sni?expected=");
  10223. // NOTE: This may fail if the server is listening on IPv4 only
  10224. // (e.g., when localhost resolves to 127.0.0.1 only)
  10225. if (res) {
  10226. EXPECT_EQ(StatusCode::OK_200, res->status);
  10227. } else {
  10228. EXPECT_EQ(Error::Connection, res.error());
  10229. }
  10230. }
  10231. }
  10232. }
  10233. #endif
  10234. TEST(ClientProblemDetectionTest, ContentProvider) {
  10235. Server svr;
  10236. size_t content_length = 1024 * 1024;
  10237. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10238. res.set_content_provider(
  10239. content_length, "text/plain",
  10240. [&](size_t offset, size_t length, DataSink &sink) {
  10241. auto out_len = std::min(length, static_cast<size_t>(1024));
  10242. std::string out(out_len, '@');
  10243. sink.write(out.data(), out_len);
  10244. return offset < 4096;
  10245. },
  10246. [](bool success) { ASSERT_FALSE(success); });
  10247. });
  10248. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10249. res.set_content_provider(
  10250. 0, "text/plain",
  10251. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10252. EXPECT_TRUE(false);
  10253. return true;
  10254. },
  10255. [](bool success) { ASSERT_FALSE(success); });
  10256. });
  10257. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10258. auto se = detail::scope_exit([&] {
  10259. svr.stop();
  10260. listen_thread.join();
  10261. ASSERT_FALSE(svr.is_running());
  10262. });
  10263. svr.wait_until_ready();
  10264. Client cli("localhost", PORT);
  10265. {
  10266. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10267. size_t /*data_length*/) { return false; });
  10268. ASSERT_FALSE(res);
  10269. }
  10270. {
  10271. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10272. size_t /*data_length*/) { return false; });
  10273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10274. }
  10275. }
  10276. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10277. // A provider that reports success without writing anything and without
  10278. // calling done() used to be handed the same offset and length again on every
  10279. // pass, so it spun for as long as the peer stayed connected.
  10280. Server svr;
  10281. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10282. res.set_content("ok", "text/plain");
  10283. });
  10284. auto port = svr.bind_to_any_port(HOST);
  10285. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10286. auto se = detail::scope_exit([&] {
  10287. svr.stop();
  10288. listen_thread.join();
  10289. ASSERT_FALSE(svr.is_running());
  10290. });
  10291. svr.wait_until_ready();
  10292. std::atomic<int> call_count{0};
  10293. Client cli(HOST, port);
  10294. auto res = cli.Post(
  10295. "/", 1024,
  10296. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10297. // Give up after enough passes to show the spin, so that losing the
  10298. // check below fails this test instead of hanging it.
  10299. return ++call_count < 100;
  10300. },
  10301. "text/plain");
  10302. ASSERT_FALSE(res);
  10303. EXPECT_EQ(Error::Write, res.error());
  10304. EXPECT_EQ(1, call_count.load());
  10305. }
  10306. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10307. // A writer only has to assign `write`. The other three used to be left as
  10308. // empty std::functions, so a provider calling one threw
  10309. // std::bad_function_call out of the thread running it and took the whole
  10310. // process down.
  10311. DataSink sink;
  10312. std::string written;
  10313. sink.write = [&](const char *data, size_t data_len) {
  10314. written.append(data, data_len);
  10315. return true;
  10316. };
  10317. EXPECT_TRUE(sink.is_writable());
  10318. sink.done();
  10319. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10320. EXPECT_TRUE(written.empty());
  10321. }
  10322. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10323. // A sink that cannot carry trailers still has to finish.
  10324. DataSink sink;
  10325. auto done_count = 0;
  10326. sink.done = [&]() { done_count++; };
  10327. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10328. EXPECT_EQ(1, done_count);
  10329. }
  10330. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10331. Server svr;
  10332. const std::string body(4096, 'x');
  10333. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10334. res.set_content_provider(body.size(), "text/plain",
  10335. [&](size_t offset, size_t length, DataSink &sink) {
  10336. sink.write(body.data() + offset, length);
  10337. sink.done();
  10338. return true;
  10339. });
  10340. });
  10341. auto port = svr.bind_to_any_port(HOST);
  10342. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10343. auto se = detail::scope_exit([&] {
  10344. svr.stop();
  10345. listen_thread.join();
  10346. ASSERT_FALSE(svr.is_running());
  10347. });
  10348. svr.wait_until_ready();
  10349. Client cli(HOST, port);
  10350. auto res = cli.Get("/");
  10351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10352. EXPECT_EQ(StatusCode::OK_200, res->status);
  10353. EXPECT_EQ(body, res->body);
  10354. }
  10355. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10356. Server svr;
  10357. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10358. res.set_content_provider(
  10359. 1024, "text/plain",
  10360. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10361. sink.write("hello", 5);
  10362. sink.done(); // short of the 1024 bytes the response promised
  10363. return true;
  10364. });
  10365. });
  10366. auto port = svr.bind_to_any_port(HOST);
  10367. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10368. auto se = detail::scope_exit([&] {
  10369. svr.stop();
  10370. listen_thread.join();
  10371. ASSERT_FALSE(svr.is_running());
  10372. });
  10373. svr.wait_until_ready();
  10374. Client cli(HOST, port);
  10375. cli.set_read_timeout(5, 0);
  10376. // The response is short of its Content-Length, so the client cannot read a
  10377. // complete body. What matters is that this returns at all: a no-op done()
  10378. // would leave the writer looping over a provider that never makes progress.
  10379. auto res = cli.Get("/");
  10380. EXPECT_FALSE(res);
  10381. }
  10382. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10383. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10384. // The compressed path builds the whole body before connecting, so this
  10385. // fails client-side and never reaches a server.
  10386. Client cli(HOST, PORT);
  10387. cli.set_compress(true);
  10388. auto res = cli.Post(
  10389. "/", 1024,
  10390. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10391. sink.write("hello", 5);
  10392. sink.done(); // short of the 1024 bytes the request announced
  10393. return true;
  10394. },
  10395. "text/plain");
  10396. ASSERT_FALSE(res);
  10397. EXPECT_EQ(Error::Write, res.error());
  10398. }
  10399. #endif
  10400. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10401. Server svr;
  10402. svr.set_error_handler([](Request const &, Response &res) -> void {
  10403. res.set_chunked_content_provider(
  10404. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10405. sink.os << "hello";
  10406. sink.os << "world";
  10407. sink.done();
  10408. return true;
  10409. });
  10410. });
  10411. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10412. auto se = detail::scope_exit([&] {
  10413. svr.stop();
  10414. listen_thread.join();
  10415. ASSERT_FALSE(svr.is_running());
  10416. });
  10417. svr.wait_until_ready();
  10418. Client cli("localhost", PORT);
  10419. auto res = cli.Get("/");
  10420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10421. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10422. EXPECT_EQ("helloworld", res->body);
  10423. }
  10424. // A body set after a content provider must replace it, not be sent through it.
  10425. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  10426. Server svr;
  10427. svr.set_mount_point("/", "./www");
  10428. svr.set_file_request_handler([](const Request &req, Response &res) {
  10429. if (req.path == "/dir/test.html") {
  10430. res.status = StatusCode::Forbidden_403;
  10431. res.set_content(std::string(5000, 'D'), "text/plain");
  10432. } else if (req.path == "/file") {
  10433. res.status = StatusCode::Forbidden_403;
  10434. res.body = "Denied";
  10435. }
  10436. });
  10437. auto port = svr.bind_to_any_port(HOST);
  10438. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10439. auto se = detail::scope_exit([&] {
  10440. svr.stop();
  10441. t.join();
  10442. ASSERT_FALSE(svr.is_running());
  10443. });
  10444. svr.wait_until_ready();
  10445. Client cli(HOST, port);
  10446. {
  10447. auto res = cli.Get("/dir/test.html");
  10448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10449. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10450. EXPECT_EQ(std::string(5000, 'D'), res->body);
  10451. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  10452. }
  10453. {
  10454. auto res = cli.Get("/file");
  10455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10456. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10457. EXPECT_EQ("Denied", res->body);
  10458. }
  10459. {
  10460. auto res = cli.Get("/dir/index.html");
  10461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10462. EXPECT_EQ(StatusCode::OK_200, res->status);
  10463. EXPECT_EQ(0U, res->body.find("<html>"));
  10464. }
  10465. }
  10466. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  10467. Server svr;
  10468. std::vector<bool> released;
  10469. std::mutex released_mutex;
  10470. auto releaser = [&](bool success) {
  10471. std::lock_guard<std::mutex> guard(released_mutex);
  10472. released.push_back(success);
  10473. };
  10474. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  10475. return sink.write(&"hello"[offset], length);
  10476. };
  10477. svr.Get("/sized", [&](const Request &, Response &res) {
  10478. res.status = StatusCode::NotFound_404;
  10479. res.set_content_provider(5, "text/plain", provider, releaser);
  10480. });
  10481. svr.Get("/chunked", [&](const Request &, Response &res) {
  10482. res.status = StatusCode::ServiceUnavailable_503;
  10483. res.set_chunked_content_provider(
  10484. "text/plain",
  10485. [](size_t, DataSink &sink) {
  10486. sink.os << "chunk";
  10487. sink.done();
  10488. return true;
  10489. },
  10490. releaser);
  10491. });
  10492. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  10493. res.set_content_provider(5, "text/plain", provider, releaser);
  10494. throw std::runtime_error("after the provider");
  10495. });
  10496. svr.set_error_handler([](const Request &req, Response &res) {
  10497. // Leave the exception handler's content to it.
  10498. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  10499. res.set_content(std::string(1000, 'E'), "text/html");
  10500. return Server::HandlerResponse::Handled;
  10501. });
  10502. svr.set_exception_handler(
  10503. [](const Request &, Response &res, std::exception_ptr) {
  10504. res.status = StatusCode::InternalServerError_500;
  10505. res.set_content(std::string(1000, 'X'), "text/html");
  10506. });
  10507. auto port = svr.bind_to_any_port(HOST);
  10508. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10509. auto se = detail::scope_exit([&] {
  10510. svr.stop();
  10511. t.join();
  10512. ASSERT_FALSE(svr.is_running());
  10513. });
  10514. svr.wait_until_ready();
  10515. Client cli(HOST, port);
  10516. {
  10517. auto res = cli.Get("/sized");
  10518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10519. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10520. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10521. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  10522. }
  10523. {
  10524. auto res = cli.Get("/chunked");
  10525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10526. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  10527. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10528. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  10529. }
  10530. {
  10531. auto res = cli.Get("/throw");
  10532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10533. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  10534. EXPECT_EQ(std::string(1000, 'X'), res->body);
  10535. }
  10536. std::lock_guard<std::mutex> guard(released_mutex);
  10537. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  10538. }
  10539. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  10540. Server svr;
  10541. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  10542. return sink.write(&"abc"[offset], length);
  10543. };
  10544. svr.Get("/file-then-body", [](const Request &, Response &res) {
  10545. res.set_file_content("./www/dir/test.html");
  10546. res.set_content("body", "text/plain");
  10547. });
  10548. svr.Get("/body-then-file", [](const Request &, Response &res) {
  10549. res.set_content(std::string(100, 'B'), "text/plain");
  10550. res.set_file_content("./www/dir/test.html");
  10551. });
  10552. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  10553. res.set_content(std::string(100, 'B'), "text/plain");
  10554. res.set_content_provider(3, "text/plain", abc);
  10555. });
  10556. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  10557. res.set_content_provider(3, "text/plain", abc);
  10558. res.set_content(std::string(100, 'B'), "text/plain");
  10559. });
  10560. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  10561. res.set_content_provider(3, "text/plain", abc);
  10562. res.body = "direct";
  10563. });
  10564. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  10565. res.set_file_content("./www/dir/test.html");
  10566. res.body = "direct";
  10567. });
  10568. auto port = svr.bind_to_any_port(HOST);
  10569. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10570. auto se = detail::scope_exit([&] {
  10571. svr.stop();
  10572. t.join();
  10573. ASSERT_FALSE(svr.is_running());
  10574. });
  10575. svr.wait_until_ready();
  10576. Client cli(HOST, port);
  10577. auto expect_body = [&](const char *path, const std::string &body) {
  10578. // Uncompressed, so Content-Length can be compared with the body.
  10579. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  10580. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  10581. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10582. EXPECT_EQ(body, res->body) << path;
  10583. EXPECT_EQ(std::to_string(body.size()),
  10584. res->get_header_value("Content-Length"))
  10585. << path;
  10586. };
  10587. expect_body("/file-then-body", "body");
  10588. expect_body("/body-then-file", "test.html");
  10589. expect_body("/body-then-provider", "abc");
  10590. expect_body("/provider-then-body", std::string(100, 'B'));
  10591. expect_body("/provider-then-direct-body", "direct");
  10592. expect_body("/file-then-direct-body", "direct");
  10593. // Ranges are checked against the body, not the dropped provider.
  10594. {
  10595. auto res = cli.Get("/provider-then-direct-body",
  10596. Headers{{make_range_header({{1, 2}})}});
  10597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10598. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10599. EXPECT_EQ("ir", res->body);
  10600. }
  10601. {
  10602. auto res = cli.Get("/file-then-direct-body",
  10603. Headers{{make_range_header({{7, 8}})}});
  10604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10605. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  10606. }
  10607. }
  10608. // Forward declaration (see the base64_encode note).
  10609. namespace httplib {
  10610. namespace detail {
  10611. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  10612. const std::string &content_type,
  10613. EncodingType encoding);
  10614. } // namespace detail
  10615. } // namespace httplib
  10616. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  10617. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  10618. ASSERT_TRUE(mm->is_open());
  10619. Response res;
  10620. detail::set_file_content_provider(res, mm, "text/html",
  10621. detail::EncodingType::None);
  10622. std::string out;
  10623. DataSink sink;
  10624. sink.write = [&](const char *d, size_t l) {
  10625. out.append(d, l);
  10626. return true;
  10627. };
  10628. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  10629. EXPECT_EQ("test.html", out);
  10630. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  10631. EXPECT_EQ("test.html", out);
  10632. }
  10633. TEST(LongPollingTest, ClientCloseDetection) {
  10634. Server svr;
  10635. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10636. res.set_chunked_content_provider(
  10637. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10638. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10639. sink.os << "hello";
  10640. auto count = 10;
  10641. while (count > 0 && sink.is_writable()) {
  10642. this_thread::sleep_for(chrono::milliseconds(10));
  10643. count--;
  10644. }
  10645. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10646. return true;
  10647. });
  10648. });
  10649. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10650. auto se = detail::scope_exit([&] {
  10651. svr.stop();
  10652. listen_thread.join();
  10653. ASSERT_FALSE(svr.is_running());
  10654. });
  10655. svr.wait_until_ready();
  10656. Client cli("localhost", PORT);
  10657. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10658. EXPECT_EQ("hello", string(data, data_length));
  10659. return false; // close the socket immediately.
  10660. });
  10661. ASSERT_FALSE(res);
  10662. }
  10663. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10664. Server svr;
  10665. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10666. res.set_chunked_content_provider(
  10667. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10668. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10669. sink.os << "hello";
  10670. EXPECT_TRUE(sink.os.good());
  10671. // Wait for the client to close the connection
  10672. auto count = 10;
  10673. while (count > 0 && sink.is_writable()) {
  10674. this_thread::sleep_for(chrono::milliseconds(10));
  10675. count--;
  10676. }
  10677. // After client disconnect, write repeatedly until the socket
  10678. // write actually fails (small writes may be absorbed by the
  10679. // kernel buffer)
  10680. std::string chunk(1024, 'x');
  10681. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10682. sink.os << chunk;
  10683. }
  10684. EXPECT_TRUE(sink.os.fail());
  10685. return true;
  10686. });
  10687. });
  10688. auto port = svr.bind_to_any_port("localhost");
  10689. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10690. auto se = detail::scope_exit([&] {
  10691. svr.stop();
  10692. listen_thread.join();
  10693. ASSERT_FALSE(svr.is_running());
  10694. });
  10695. svr.wait_until_ready();
  10696. Client cli("localhost", port);
  10697. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10698. EXPECT_EQ("hello", string(data, data_length));
  10699. return false; // close the socket immediately.
  10700. });
  10701. ASSERT_FALSE(res);
  10702. }
  10703. TEST(GetWithParametersTest, GetWithParameters) {
  10704. Server svr;
  10705. svr.Get("/", [&](const Request &req, Response &) {
  10706. EXPECT_EQ("world", req.get_param_value("hello"));
  10707. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10708. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10709. });
  10710. svr.Get("/params", [&](const Request &req, Response &) {
  10711. EXPECT_EQ("world", req.get_param_value("hello"));
  10712. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10713. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10714. });
  10715. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10716. EXPECT_EQ("resource-id", req.matches[1]);
  10717. EXPECT_EQ("foo", req.get_param_value("param1"));
  10718. EXPECT_EQ("bar", req.get_param_value("param2"));
  10719. });
  10720. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10721. EXPECT_EQ("user-id", req.path_params.at("id"));
  10722. EXPECT_EQ("foo", req.get_param_value("param1"));
  10723. EXPECT_EQ("bar", req.get_param_value("param2"));
  10724. });
  10725. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10726. auto se = detail::scope_exit([&] {
  10727. svr.stop();
  10728. listen_thread.join();
  10729. ASSERT_FALSE(svr.is_running());
  10730. });
  10731. svr.wait_until_ready();
  10732. {
  10733. Client cli(HOST, PORT);
  10734. Params params;
  10735. params.emplace("hello", "world");
  10736. params.emplace("hello2", "world2");
  10737. params.emplace("hello3", "world3");
  10738. auto res = cli.Get("/", params, Headers{});
  10739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10740. EXPECT_EQ(StatusCode::OK_200, res->status);
  10741. }
  10742. {
  10743. Client cli(HOST, PORT);
  10744. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10746. EXPECT_EQ(StatusCode::OK_200, res->status);
  10747. }
  10748. {
  10749. Client cli(HOST, PORT);
  10750. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10752. EXPECT_EQ(StatusCode::OK_200, res->status);
  10753. }
  10754. {
  10755. Client cli(HOST, PORT);
  10756. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10758. EXPECT_EQ(StatusCode::OK_200, res->status);
  10759. }
  10760. }
  10761. TEST(GetWithParametersTest, GetWithParameters2) {
  10762. Server svr;
  10763. svr.Get("/", [&](const Request &req, Response &res) {
  10764. auto text = req.get_param_value("hello");
  10765. res.set_content(text, "text/plain");
  10766. });
  10767. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10768. auto se = detail::scope_exit([&] {
  10769. svr.stop();
  10770. listen_thread.join();
  10771. ASSERT_FALSE(svr.is_running());
  10772. });
  10773. svr.wait_until_ready();
  10774. Client cli("localhost", PORT);
  10775. Params params;
  10776. params.emplace("hello", "world");
  10777. std::string body;
  10778. auto res = cli.Get("/", params, Headers{},
  10779. [&](const char *data, size_t data_length) {
  10780. body.append(data, data_length);
  10781. return true;
  10782. });
  10783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10784. EXPECT_EQ(StatusCode::OK_200, res->status);
  10785. EXPECT_EQ("world", body);
  10786. }
  10787. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10788. Server svr;
  10789. svr.Get("/search", [&](const Request &req, Response &res) {
  10790. auto q = req.get_param_value("q");
  10791. res.set_content(q, "text/plain");
  10792. });
  10793. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10794. auto se = detail::scope_exit([&] {
  10795. svr.stop();
  10796. listen_thread.join();
  10797. ASSERT_FALSE(svr.is_running());
  10798. });
  10799. svr.wait_until_ready();
  10800. Client cli("localhost", PORT);
  10801. // Verify that Get(path, params) works without requiring Headers argument
  10802. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10804. EXPECT_EQ(StatusCode::OK_200, res->status);
  10805. EXPECT_EQ("cpp-httplib", res->body);
  10806. }
  10807. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10808. auto host = "httpbingo.org";
  10809. auto path = std::string{"/range/32"};
  10810. #ifdef CPPHTTPLIB_SSL_ENABLED
  10811. SSLClient cli(host);
  10812. #else
  10813. Client cli(host);
  10814. #endif
  10815. cli.set_default_headers({make_range_header({{1, 10}})});
  10816. cli.set_connection_timeout(5);
  10817. {
  10818. auto res = cli.Get(path);
  10819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10820. EXPECT_EQ("bcdefghijk", res->body);
  10821. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10822. }
  10823. {
  10824. auto res = cli.Get(path);
  10825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10826. EXPECT_EQ("bcdefghijk", res->body);
  10827. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10828. }
  10829. }
  10830. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10831. Server svr;
  10832. svr.set_default_headers({{"Hello", "World"}});
  10833. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10834. res.set_content("ok", "text/plain");
  10835. });
  10836. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10837. auto se = detail::scope_exit([&] {
  10838. svr.stop();
  10839. listen_thread.join();
  10840. ASSERT_FALSE(svr.is_running());
  10841. });
  10842. svr.wait_until_ready();
  10843. Client cli("localhost", PORT);
  10844. auto res = cli.Get("/");
  10845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10846. EXPECT_EQ(StatusCode::OK_200, res->status);
  10847. EXPECT_EQ("ok", res->body);
  10848. EXPECT_EQ("World", res->get_header_value("Hello"));
  10849. }
  10850. #ifdef CPPHTTPLIB_SSL_ENABLED
  10851. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10852. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10853. ASSERT_TRUE(svr.is_valid());
  10854. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10855. std::this_thread::sleep_for(std::chrono::seconds(2));
  10856. res.set_content("a", "text/plain");
  10857. });
  10858. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10859. res.set_content("b", "text/plain");
  10860. });
  10861. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10862. auto se = detail::scope_exit([&] {
  10863. svr.stop();
  10864. listen_thread.join();
  10865. ASSERT_FALSE(svr.is_running());
  10866. });
  10867. svr.wait_until_ready();
  10868. SSLClient cli("localhost", PORT);
  10869. cli.enable_server_certificate_verification(false);
  10870. cli.set_keep_alive(true);
  10871. cli.set_read_timeout(std::chrono::seconds(1));
  10872. auto resa = cli.Get("/a");
  10873. ASSERT_TRUE(!resa);
  10874. EXPECT_EQ(Error::Read, resa.error());
  10875. auto resb = cli.Get("/b");
  10876. ASSERT_TRUE(resb);
  10877. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10878. EXPECT_EQ("b", resb->body);
  10879. }
  10880. // Closing an idle keep-alive connection sends close_notify and returns. The
  10881. // server must not wait for the client's close_notify: an idle client never
  10882. // sends one, so the worker would be held until the read timeout expires, and
  10883. // stop() would wait for it.
  10884. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10885. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10886. ASSERT_TRUE(svr.is_valid());
  10887. svr.set_keep_alive_timeout(1);
  10888. svr.set_read_timeout(10, 0);
  10889. svr.Get("/", [](const Request &, Response &res) {
  10890. res.set_content("ok", "text/plain");
  10891. });
  10892. auto port = svr.bind_to_any_port(HOST);
  10893. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10894. auto se = detail::scope_exit([&] {
  10895. if (listen_thread.joinable()) {
  10896. svr.stop();
  10897. listen_thread.join();
  10898. }
  10899. });
  10900. svr.wait_until_ready();
  10901. SSLClient cli(HOST, port);
  10902. cli.enable_server_certificate_verification(false);
  10903. cli.set_keep_alive(true);
  10904. auto res = cli.Get("/");
  10905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10906. EXPECT_EQ(StatusCode::OK_200, res->status);
  10907. // Stay idle past the keep-alive timeout so the server closes the connection.
  10908. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10909. auto start = std::chrono::steady_clock::now();
  10910. svr.stop();
  10911. listen_thread.join();
  10912. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10913. std::chrono::steady_clock::now() - start)
  10914. .count();
  10915. EXPECT_LT(elapsed, 3000);
  10916. }
  10917. #endif
  10918. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10919. protected:
  10920. ServerTestWithAI_PASSIVE()
  10921. : cli_(HOST, PORT)
  10922. #ifdef CPPHTTPLIB_SSL_ENABLED
  10923. ,
  10924. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10925. #endif
  10926. {
  10927. #ifdef CPPHTTPLIB_SSL_ENABLED
  10928. cli_.enable_server_certificate_verification(false);
  10929. #endif
  10930. }
  10931. virtual void SetUp() {
  10932. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10933. res.set_content("Hello World!", "text/plain");
  10934. });
  10935. t_ = thread(
  10936. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10937. svr_.wait_until_ready();
  10938. }
  10939. virtual void TearDown() {
  10940. svr_.stop();
  10941. t_.join();
  10942. }
  10943. #ifdef CPPHTTPLIB_SSL_ENABLED
  10944. SSLClient cli_;
  10945. SSLServer svr_;
  10946. #else
  10947. Client cli_;
  10948. Server svr_;
  10949. #endif
  10950. thread t_;
  10951. };
  10952. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10953. auto res = cli_.Get("/hi");
  10954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10955. EXPECT_EQ(StatusCode::OK_200, res->status);
  10956. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10957. EXPECT_EQ("Hello World!", res->body);
  10958. }
  10959. class ServerUpDownTest : public ::testing::Test {
  10960. protected:
  10961. ServerUpDownTest() : cli_(HOST, PORT) {}
  10962. virtual void SetUp() {
  10963. t_ = thread([&]() {
  10964. svr_.bind_to_any_port(HOST);
  10965. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10966. ASSERT_TRUE(svr_.listen_after_bind());
  10967. });
  10968. svr_.wait_until_ready();
  10969. }
  10970. virtual void TearDown() {
  10971. svr_.stop();
  10972. t_.join();
  10973. }
  10974. Client cli_;
  10975. Server svr_;
  10976. thread t_;
  10977. };
  10978. TEST_F(ServerUpDownTest, QuickStartStop) {
  10979. // Should not crash, especially when run with
  10980. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10981. }
  10982. class PayloadMaxLengthTest : public ::testing::Test {
  10983. protected:
  10984. PayloadMaxLengthTest()
  10985. : cli_(HOST, PORT)
  10986. #ifdef CPPHTTPLIB_SSL_ENABLED
  10987. ,
  10988. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10989. #endif
  10990. {
  10991. #ifdef CPPHTTPLIB_SSL_ENABLED
  10992. cli_.enable_server_certificate_verification(false);
  10993. #endif
  10994. }
  10995. virtual void SetUp() {
  10996. svr_.set_payload_max_length(8);
  10997. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10998. res.set_content("test", "text/plain");
  10999. });
  11000. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11001. svr_.wait_until_ready();
  11002. }
  11003. virtual void TearDown() {
  11004. svr_.stop();
  11005. t_.join();
  11006. }
  11007. #ifdef CPPHTTPLIB_SSL_ENABLED
  11008. SSLClient cli_;
  11009. SSLServer svr_;
  11010. #else
  11011. Client cli_;
  11012. Server svr_;
  11013. #endif
  11014. thread t_;
  11015. };
  11016. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11017. auto res = cli_.Post("/test", "123456789", "text/plain");
  11018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11019. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11020. res = cli_.Post("/test", "12345678", "text/plain");
  11021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11022. EXPECT_EQ(StatusCode::OK_200, res->status);
  11023. }
  11024. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11025. // Test chunked encoding with payload exceeding the 8-byte limit
  11026. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11027. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11029. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11030. }
  11031. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11032. // Test chunked encoding with payload within the 8-byte limit
  11033. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11034. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11036. EXPECT_EQ(StatusCode::OK_200, res->status);
  11037. }
  11038. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11039. // Test using send_request to send chunked data exceeding payload limit
  11040. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11041. "Host: " +
  11042. std::string(HOST) + ":" + std::to_string(PORT) +
  11043. "\r\n"
  11044. "Transfer-Encoding: chunked\r\n"
  11045. "Connection: close\r\n"
  11046. "\r\n"
  11047. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11048. "0123456789\r\n"
  11049. "0\r\n" // End chunk
  11050. "\r\n";
  11051. std::string response;
  11052. bool result = send_request(1, chunked_request, &response);
  11053. if (!result) {
  11054. // If send_request fails, it might be because the server closed the
  11055. // connection due to payload limit enforcement, which is acceptable
  11056. SUCCEED()
  11057. << "Server rejected oversized chunked request (connection closed)";
  11058. } else {
  11059. // If we got a response, check if it's an error response or connection was
  11060. // closed early Short response length indicates connection was closed due to
  11061. // payload limit
  11062. if (response.length() <= 10) {
  11063. SUCCEED() << "Server closed connection for oversized chunked request";
  11064. } else {
  11065. // Check for error status codes
  11066. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11067. response.find("Payload Too Large") != std::string::npos ||
  11068. response.find("400") != std::string::npos);
  11069. }
  11070. }
  11071. }
  11072. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11073. // Test request without Content-Length header exceeding payload limit
  11074. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11075. "Host: " +
  11076. std::string(HOST) + ":" +
  11077. std::to_string(PORT) +
  11078. "\r\n"
  11079. "Connection: close\r\n"
  11080. "\r\n";
  11081. // Add payload exceeding the 8-byte limit
  11082. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11083. request_without_content_length += large_payload;
  11084. std::string response;
  11085. bool result = send_request(1, request_without_content_length, &response);
  11086. if (!result) {
  11087. // If send_request fails, server likely closed connection due to payload
  11088. // limit
  11089. SUCCEED() << "Server rejected oversized request without Content-Length "
  11090. "(connection closed)";
  11091. } else {
  11092. // Check if server responded with error or closed connection early
  11093. if (response.length() <= 10) {
  11094. SUCCEED() << "Server closed connection for oversized request without "
  11095. "Content-Length";
  11096. } else {
  11097. // Check for error status codes
  11098. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11099. response.find("Payload Too Large") != std::string::npos ||
  11100. response.find("400") != std::string::npos);
  11101. }
  11102. }
  11103. }
  11104. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11105. // Test request without Content-Length header within payload limit
  11106. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11107. "Host: " +
  11108. std::string(HOST) + ":" +
  11109. std::to_string(PORT) +
  11110. "\r\n"
  11111. "Connection: close\r\n"
  11112. "\r\n";
  11113. // Add payload within the 8-byte limit
  11114. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11115. request_without_content_length += small_payload;
  11116. std::string response;
  11117. bool result = send_request(1, request_without_content_length, &response);
  11118. // For requests without Content-Length, the server may have different behavior
  11119. // The key is that it should not reject due to payload limit for small
  11120. // payloads
  11121. if (result) {
  11122. // Check for any HTTP response (success or error, but not connection closed)
  11123. if (response.length() > 10) {
  11124. SUCCEED()
  11125. << "Server processed request without Content-Length within limit";
  11126. } else {
  11127. // Short response might indicate connection closed, which is acceptable
  11128. SUCCEED() << "Server closed connection for request without "
  11129. "Content-Length (acceptable behavior)";
  11130. }
  11131. } else {
  11132. // Connection failure might be due to protocol requirements
  11133. SUCCEED() << "Connection issue with request without Content-Length "
  11134. "(environment-specific)";
  11135. }
  11136. }
  11137. class LargePayloadMaxLengthTest : public ::testing::Test {
  11138. protected:
  11139. LargePayloadMaxLengthTest()
  11140. : cli_(HOST, PORT)
  11141. #ifdef CPPHTTPLIB_SSL_ENABLED
  11142. ,
  11143. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11144. #endif
  11145. {
  11146. #ifdef CPPHTTPLIB_SSL_ENABLED
  11147. cli_.enable_server_certificate_verification(false);
  11148. #endif
  11149. }
  11150. virtual void SetUp() {
  11151. // Set 10MB payload limit
  11152. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11153. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11154. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11155. res.set_content("Large payload test", "text/plain");
  11156. });
  11157. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11158. svr_.wait_until_ready();
  11159. }
  11160. virtual void TearDown() {
  11161. svr_.stop();
  11162. t_.join();
  11163. }
  11164. #ifdef CPPHTTPLIB_SSL_ENABLED
  11165. SSLClient cli_;
  11166. SSLServer svr_;
  11167. #else
  11168. Client cli_;
  11169. Server svr_;
  11170. #endif
  11171. thread t_;
  11172. };
  11173. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11174. // Test chunked encoding with payload within 10MB limit
  11175. std::string medium_payload(5 * 1024 * 1024,
  11176. 'A'); // 5MB payload, within 10MB limit
  11177. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11179. EXPECT_EQ(StatusCode::OK_200, res->status);
  11180. }
  11181. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11182. // Test chunked encoding with payload exceeding 10MB limit
  11183. std::string large_payload(12 * 1024 * 1024,
  11184. 'B'); // 12MB payload, exceeds 10MB limit
  11185. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11186. // Server may either return 413 or close the connection
  11187. if (res) {
  11188. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11189. } else {
  11190. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11191. }
  11192. }
  11193. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11194. // Test request without Content-Length header within 10MB limit
  11195. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11196. "Host: " +
  11197. std::string(HOST) + ":" +
  11198. std::to_string(PORT) +
  11199. "\r\n"
  11200. "Connection: close\r\n"
  11201. "\r\n";
  11202. // Add 1MB payload (within 10MB limit)
  11203. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11204. request_without_content_length += medium_payload;
  11205. std::string response;
  11206. bool result = send_request(5, request_without_content_length, &response);
  11207. if (result) {
  11208. // Should get a proper HTTP response for payloads within limit
  11209. if (response.length() > 10) {
  11210. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11211. "10MB limit";
  11212. } else {
  11213. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11214. "Content-Length)";
  11215. }
  11216. } else {
  11217. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11218. }
  11219. }
  11220. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11221. // Test request without Content-Length header exceeding 10MB limit
  11222. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11223. "Host: " +
  11224. std::string(HOST) + ":" +
  11225. std::to_string(PORT) +
  11226. "\r\n"
  11227. "Connection: close\r\n"
  11228. "\r\n";
  11229. // Add 12MB payload (exceeds 10MB limit)
  11230. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11231. request_without_content_length += large_payload;
  11232. std::string response;
  11233. bool result = send_request(10, request_without_content_length, &response);
  11234. if (!result) {
  11235. // Server should close connection due to payload limit
  11236. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11237. "(connection closed)";
  11238. } else {
  11239. // Check for error response
  11240. if (response.length() <= 10) {
  11241. SUCCEED()
  11242. << "Server closed connection for 12MB request exceeding 10MB limit";
  11243. } else {
  11244. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11245. response.find("Payload Too Large") != std::string::npos ||
  11246. response.find("400") != std::string::npos);
  11247. }
  11248. }
  11249. }
  11250. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11251. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11252. // path.
  11253. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11254. Server svr;
  11255. const size_t LIMIT = 64 * 1024; // 64KB
  11256. svr.set_payload_max_length(LIMIT);
  11257. size_t total = 0;
  11258. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11259. const ContentReader &content_reader) {
  11260. content_reader([&](const char * /*data*/, size_t len) {
  11261. total += len;
  11262. return true;
  11263. });
  11264. res.status = 200;
  11265. res.set_content("stream_ok", "text/plain");
  11266. });
  11267. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11268. auto se = detail::scope_exit([&] {
  11269. svr.stop();
  11270. thread.join();
  11271. ASSERT_FALSE(svr.is_running());
  11272. });
  11273. svr.wait_until_ready();
  11274. // Prepare 256KB raw data and gzip-compress it
  11275. std::string raw(256 * 1024, 'A');
  11276. std::string gz;
  11277. {
  11278. z_stream zs{};
  11279. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11280. Z_DEFAULT_STRATEGY);
  11281. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11282. zs.avail_in = static_cast<uInt>(raw.size());
  11283. char outbuf[4096];
  11284. int ret;
  11285. do {
  11286. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11287. zs.avail_out = sizeof(outbuf);
  11288. ret = deflate(&zs, Z_FINISH);
  11289. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11290. } while (ret != Z_STREAM_END);
  11291. deflateEnd(&zs);
  11292. }
  11293. Client cli(HOST, PORT);
  11294. cli.set_connection_timeout(std::chrono::seconds(5));
  11295. Headers headers = {{"Content-Encoding", "gzip"}};
  11296. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11297. "application/octet-stream");
  11298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11299. // Server must reject oversized decompressed payloads with 413.
  11300. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11301. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11302. EXPECT_LE(total, LIMIT);
  11303. }
  11304. #ifndef CPPHTTPLIB_SSL_ENABLED
  11305. // For a request with neither Content-Length nor Transfer-Encoding, the
  11306. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11307. // compressed wire bytes straight to the ContentReader without ever routing
  11308. // them through the decompressor, so payload_max_length_ only bounded the
  11309. // compressed size on the wire, not the decompressed size.
  11310. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11311. Server svr;
  11312. const size_t LIMIT = 64 * 1024; // 64KB
  11313. svr.set_payload_max_length(LIMIT);
  11314. size_t total = 0;
  11315. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11316. const ContentReader &content_reader) {
  11317. content_reader([&](const char * /*data*/, size_t len) {
  11318. total += len;
  11319. return true;
  11320. });
  11321. res.status = 200;
  11322. res.set_content("stream_ok", "text/plain");
  11323. });
  11324. auto port = svr.bind_to_any_port(HOST);
  11325. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  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, same payload as the
  11333. // StreamingGzipDecompression test above.
  11334. std::string raw(256 * 1024, 'A');
  11335. std::string gz;
  11336. {
  11337. httplib::detail::gzip_compressor compressor;
  11338. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11339. [&](const char *chunk, size_t len) {
  11340. gz.append(chunk, len);
  11341. return true;
  11342. });
  11343. ASSERT_TRUE(result);
  11344. }
  11345. // Send the gzip body over raw TCP with neither Content-Length nor
  11346. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11347. // kicks in.
  11348. std::string req = "POST /stream HTTP/1.1\r\n"
  11349. "Host: " +
  11350. std::string(HOST) + ":" + std::to_string(port) +
  11351. "\r\n"
  11352. "Content-Encoding: gzip\r\n"
  11353. "Connection: close\r\n"
  11354. "\r\n" +
  11355. gz;
  11356. std::string response;
  11357. ASSERT_TRUE(send_request(5, req, &response, port));
  11358. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11359. EXPECT_LE(total, LIMIT);
  11360. }
  11361. #endif
  11362. #endif
  11363. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11364. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11365. // the payload must be passed through untouched instead of being rejected.
  11366. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11367. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11368. Server svr;
  11369. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11370. res.set_content(body, "image/jpeg");
  11371. res.set_header("Content-Encoding", "UTF-8");
  11372. });
  11373. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  11374. res.set_content(body, "image/jpeg");
  11375. res.set_header("Content-Encoding", "identity");
  11376. });
  11377. svr.Post("/echo", [](const Request &req, Response &res) {
  11378. res.set_content(req.body, "image/jpeg");
  11379. });
  11380. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11381. auto se = detail::scope_exit([&] {
  11382. svr.stop();
  11383. t.join();
  11384. ASSERT_FALSE(svr.is_running());
  11385. });
  11386. svr.wait_until_ready();
  11387. Client cli(HOST, PORT);
  11388. {
  11389. auto res = cli.Get("/image");
  11390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11391. EXPECT_EQ(StatusCode::OK_200, res->status);
  11392. EXPECT_EQ(body, res->body);
  11393. }
  11394. {
  11395. auto res = cli.Get("/identity");
  11396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11397. EXPECT_EQ(StatusCode::OK_200, res->status);
  11398. EXPECT_EQ(body, res->body);
  11399. }
  11400. {
  11401. // The same applies to a request body reaching the server.
  11402. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11403. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11405. EXPECT_EQ(StatusCode::OK_200, res->status);
  11406. EXPECT_EQ(body, res->body);
  11407. }
  11408. }
  11409. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11410. // gzip-encoded response even when the build has no zlib support.
  11411. static const char GZIPPED_HELLO_WORLD[] = {
  11412. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11413. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11414. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11415. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11416. // A content coding is a whole token, not something the field value merely
  11417. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11418. // as "fibre" look like Brotli, and turned a multi-coding value like
  11419. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11420. // it was never meant to see.
  11421. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11422. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11423. Server svr;
  11424. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11425. res.set_content(body, "image/jpeg");
  11426. res.set_header("Content-Encoding", "fibre");
  11427. });
  11428. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11429. res.set_content(body, "image/jpeg");
  11430. res.set_header("Content-Encoding", "gzip, br");
  11431. });
  11432. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11433. res.set_content(body, "image/jpeg");
  11434. res.set_header("Content-Encoding", "x-zstd-ish");
  11435. });
  11436. auto port = svr.bind_to_any_port(HOST);
  11437. thread t = thread([&]() { svr.listen_after_bind(); });
  11438. auto se = detail::scope_exit([&] {
  11439. svr.stop();
  11440. t.join();
  11441. ASSERT_FALSE(svr.is_running());
  11442. });
  11443. svr.wait_until_ready();
  11444. Client cli(HOST, port);
  11445. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11446. auto res = cli.Get(path);
  11447. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11448. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11449. // Not a coding we recognize, so the payload comes back untouched
  11450. EXPECT_EQ(body, res->body) << path;
  11451. }
  11452. }
  11453. // A content coding cpp-httplib recognizes but was not built with must be
  11454. // reported as such. Handing the still-compressed payload back to the caller
  11455. // would silently corrupt it.
  11456. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11457. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11458. Server svr;
  11459. // "image/jpeg" keeps the server from applying a content coding of its own,
  11460. // so the hand-crafted Content-Encoding below survives.
  11461. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11462. res.set_content(gzipped, "image/jpeg");
  11463. res.set_header("Content-Encoding", "gzip");
  11464. });
  11465. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11466. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11467. res.set_content(gzipped, "image/jpeg");
  11468. res.set_header("Content-Encoding", "GZIP");
  11469. });
  11470. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11471. auto se = detail::scope_exit([&] {
  11472. svr.stop();
  11473. t.join();
  11474. ASSERT_FALSE(svr.is_running());
  11475. });
  11476. svr.wait_until_ready();
  11477. Client cli(HOST, PORT);
  11478. {
  11479. auto res = cli.Get("/gzipped");
  11480. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11482. EXPECT_EQ("Hello World!", res->body);
  11483. #else
  11484. ASSERT_FALSE(res);
  11485. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11486. #endif
  11487. }
  11488. {
  11489. // open_stream() must behave the same way.
  11490. auto handle = cli.open_stream("GET", "/gzipped");
  11491. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11492. ASSERT_TRUE(handle.is_valid());
  11493. std::string received;
  11494. char buf[256];
  11495. ssize_t n;
  11496. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11497. received.append(buf, static_cast<size_t>(n));
  11498. }
  11499. EXPECT_EQ("Hello World!", received);
  11500. #else
  11501. EXPECT_FALSE(handle.is_valid());
  11502. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11503. #endif
  11504. }
  11505. {
  11506. // A differently-cased coding must not be mistaken for an unknown one, or
  11507. // the body would be handed back still compressed.
  11508. auto res = cli.Get("/gzipped-uppercase");
  11509. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11511. EXPECT_EQ("Hello World!", res->body);
  11512. #else
  11513. ASSERT_FALSE(res);
  11514. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11515. #endif
  11516. }
  11517. }
  11518. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11519. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11520. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11521. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11522. // body a second time and appending a second Content-Encoding field line, so
  11523. // clients that decode one coding per listed value handed back raw gzip bytes.
  11524. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11525. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11526. Server svr;
  11527. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11528. // keeps the server from applying a coding of its own.
  11529. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11530. res.set_content(gzipped, "text/plain");
  11531. res.set_header("Content-Encoding", "gzip");
  11532. });
  11533. auto port = svr.bind_to_any_port(HOST);
  11534. thread t = thread([&]() { svr.listen_after_bind(); });
  11535. auto se = detail::scope_exit([&] {
  11536. svr.stop();
  11537. t.join();
  11538. ASSERT_FALSE(svr.is_running());
  11539. });
  11540. svr.wait_until_ready();
  11541. Client cli(HOST, port);
  11542. Headers headers = {{"Accept-Encoding", "gzip"}};
  11543. auto res = cli.Get("/pre-gzipped", headers);
  11544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11545. EXPECT_EQ(StatusCode::OK_200, res->status);
  11546. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11547. EXPECT_EQ("Hello World!", res->body);
  11548. }
  11549. // A chunked provider settles its coding where the headers are written and
  11550. // reuses it at write time. Both ends of that have to hold: a handler's own
  11551. // Content-Encoding suppresses the coding, and a response without one is still
  11552. // compressed as it always was.
  11553. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11554. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11555. const std::string plain = "Hello World! Hello World! Hello World!";
  11556. Server svr;
  11557. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11558. res.set_header("Content-Encoding", "gzip");
  11559. res.set_chunked_content_provider(
  11560. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11561. sink.write(gzipped.data(), gzipped.size());
  11562. sink.done();
  11563. return true;
  11564. });
  11565. });
  11566. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11567. res.set_chunked_content_provider(
  11568. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11569. sink.write(plain.data(), plain.size());
  11570. sink.done();
  11571. return true;
  11572. });
  11573. });
  11574. auto port = svr.bind_to_any_port(HOST);
  11575. thread t = thread([&]() { svr.listen_after_bind(); });
  11576. auto se = detail::scope_exit([&] {
  11577. svr.stop();
  11578. t.join();
  11579. ASSERT_FALSE(svr.is_running());
  11580. });
  11581. svr.wait_until_ready();
  11582. Client cli(HOST, port);
  11583. Headers headers = {{"Accept-Encoding", "gzip"}};
  11584. {
  11585. auto res = cli.Get("/pre-gzipped", headers);
  11586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11587. EXPECT_EQ(StatusCode::OK_200, res->status);
  11588. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11589. EXPECT_EQ("Hello World!", res->body);
  11590. }
  11591. {
  11592. auto res = cli.Get("/negotiated", headers);
  11593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11594. EXPECT_EQ(StatusCode::OK_200, res->status);
  11595. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11596. EXPECT_EQ(plain, res->body);
  11597. }
  11598. }
  11599. #endif
  11600. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11601. // the same message as the comma-joined one, so both have to be read the same
  11602. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11603. // single gzip coding, and a body the sender says was encoded twice was handed
  11604. // back after one pass, still compressed but presented as decoded.
  11605. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11606. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11607. Server svr;
  11608. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11609. res.set_content(body, "image/jpeg");
  11610. res.headers.emplace("Content-Encoding", "gzip");
  11611. res.headers.emplace("Content-Encoding", "gzip");
  11612. });
  11613. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11614. res.set_content(body, "image/jpeg");
  11615. res.set_header("Content-Encoding", "gzip, gzip");
  11616. });
  11617. auto port = svr.bind_to_any_port(HOST);
  11618. thread t = thread([&]() { svr.listen_after_bind(); });
  11619. auto se = detail::scope_exit([&] {
  11620. svr.stop();
  11621. t.join();
  11622. ASSERT_FALSE(svr.is_running());
  11623. });
  11624. svr.wait_until_ready();
  11625. Client cli(HOST, port);
  11626. // Two codings is not something cpp-httplib decodes, so both representations
  11627. // take the pass-through path rather than one of them being gunzipped once.
  11628. for (const char *path : {"/split", "/joined"}) {
  11629. auto res = cli.Get(path);
  11630. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11631. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11632. EXPECT_EQ(body, res->body) << path;
  11633. }
  11634. }
  11635. // Regression test for DoS vulnerability: a malicious server sending a response
  11636. // without Content-Length header must not cause unbounded memory consumption on
  11637. // the client side. The client should stop reading after a reasonable limit,
  11638. // similar to the server-side set_payload_max_length protection.
  11639. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11640. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11641. #ifndef _WIN32
  11642. signal(SIGPIPE, SIG_IGN);
  11643. #endif
  11644. auto server_thread = std::thread([] {
  11645. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11646. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11647. default_socket_options(srv);
  11648. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11649. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11650. sockaddr_in addr{};
  11651. addr.sin_family = AF_INET;
  11652. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11653. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11654. int opt = 1;
  11655. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11656. #ifdef _WIN32
  11657. reinterpret_cast<const char *>(&opt),
  11658. #else
  11659. &opt,
  11660. #endif
  11661. sizeof(opt));
  11662. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11663. ::listen(srv, 1);
  11664. sockaddr_in cli_addr{};
  11665. socklen_t cli_len = sizeof(cli_addr);
  11666. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11667. if (cli != INVALID_SOCKET) {
  11668. char buf[4096];
  11669. ::recv(cli, buf, sizeof(buf), 0);
  11670. // Malicious response: no Content-Length, no chunked encoding
  11671. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11672. "Connection: close\r\n"
  11673. "\r\n";
  11674. ::send(cli,
  11675. #ifdef _WIN32
  11676. static_cast<const char *>(response_header.c_str()),
  11677. static_cast<int>(response_header.size()),
  11678. #else
  11679. response_header.c_str(), response_header.size(),
  11680. #endif
  11681. 0);
  11682. // Send 10MB of data
  11683. std::string chunk(64 * 1024, 'A');
  11684. size_t total_sent = 0;
  11685. while (total_sent < MALICIOUS_DATA_SIZE) {
  11686. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11687. auto sent = ::send(cli,
  11688. #ifdef _WIN32
  11689. static_cast<const char *>(chunk.c_str()),
  11690. static_cast<int>(to_send),
  11691. #else
  11692. chunk.c_str(), to_send,
  11693. #endif
  11694. 0);
  11695. if (sent <= 0) break;
  11696. total_sent += static_cast<size_t>(sent);
  11697. }
  11698. detail::close_socket(cli);
  11699. }
  11700. detail::close_socket(srv);
  11701. });
  11702. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11703. size_t total_read = 0;
  11704. {
  11705. Client cli("127.0.0.1", PORT + 2);
  11706. cli.set_read_timeout(5, 0);
  11707. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11708. auto stream = cli.open_stream("GET", "/malicious");
  11709. ASSERT_TRUE(stream.is_valid());
  11710. char buffer[64 * 1024];
  11711. ssize_t n;
  11712. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11713. total_read += static_cast<size_t>(n);
  11714. }
  11715. } // StreamHandle and Client destroyed here, closing the socket
  11716. server_thread.join();
  11717. // With set_payload_max_length, the client must stop reading before consuming
  11718. // all 10MB. The read loop should be cut off at or near the configured limit.
  11719. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11720. << "Client read " << total_read << " bytes, exceeding the configured "
  11721. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11722. }
  11723. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11724. // the entire response body without truncation.
  11725. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11726. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11727. #ifndef _WIN32
  11728. signal(SIGPIPE, SIG_IGN);
  11729. #endif
  11730. auto server_thread = std::thread([] {
  11731. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11732. default_socket_options(srv);
  11733. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11734. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11735. sockaddr_in addr{};
  11736. addr.sin_family = AF_INET;
  11737. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11738. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11739. int opt = 1;
  11740. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11741. #ifdef _WIN32
  11742. reinterpret_cast<const char *>(&opt),
  11743. #else
  11744. &opt,
  11745. #endif
  11746. sizeof(opt));
  11747. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11748. ::listen(srv, 1);
  11749. sockaddr_in cli_addr{};
  11750. socklen_t cli_len = sizeof(cli_addr);
  11751. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11752. if (cli != INVALID_SOCKET) {
  11753. char buf[4096];
  11754. ::recv(cli, buf, sizeof(buf), 0);
  11755. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11756. "Connection: close\r\n"
  11757. "\r\n";
  11758. ::send(cli,
  11759. #ifdef _WIN32
  11760. static_cast<const char *>(response_header.c_str()),
  11761. static_cast<int>(response_header.size()),
  11762. #else
  11763. response_header.c_str(), response_header.size(),
  11764. #endif
  11765. 0);
  11766. std::string chunk(64 * 1024, 'A');
  11767. size_t total_sent = 0;
  11768. while (total_sent < DATA_SIZE) {
  11769. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11770. auto sent = ::send(cli,
  11771. #ifdef _WIN32
  11772. static_cast<const char *>(chunk.c_str()),
  11773. static_cast<int>(to_send),
  11774. #else
  11775. chunk.c_str(), to_send,
  11776. #endif
  11777. 0);
  11778. if (sent <= 0) break;
  11779. total_sent += static_cast<size_t>(sent);
  11780. }
  11781. #ifdef _WIN32
  11782. ::shutdown(cli, SD_SEND);
  11783. #else
  11784. ::shutdown(cli, SHUT_WR);
  11785. #endif
  11786. // Drain until the client closes its end, ensuring all data is delivered
  11787. char drain[1024];
  11788. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11789. detail::close_socket(cli);
  11790. }
  11791. detail::close_socket(srv);
  11792. });
  11793. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11794. size_t total_read = 0;
  11795. {
  11796. Client cli("127.0.0.1", PORT + 2);
  11797. cli.set_read_timeout(5, 0);
  11798. cli.set_payload_max_length(0); // 0 means no limit
  11799. auto stream = cli.open_stream("GET", "/data");
  11800. ASSERT_TRUE(stream.is_valid());
  11801. char buffer[64 * 1024];
  11802. ssize_t n;
  11803. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11804. total_read += static_cast<size_t>(n);
  11805. }
  11806. }
  11807. server_thread.join();
  11808. EXPECT_EQ(total_read, DATA_SIZE)
  11809. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11810. << " bytes without truncation, but only read " << total_read << " bytes.";
  11811. }
  11812. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11813. // enormous Content-Length must not cause the client to pre-allocate a huge
  11814. // response body buffer. The reservation is capped at payload_max_length_, and
  11815. // the read itself fails when the body exceeds the limit.
  11816. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11817. #ifndef _WIN32
  11818. signal(SIGPIPE, SIG_IGN);
  11819. #endif
  11820. auto server_thread = std::thread([] {
  11821. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11822. default_socket_options(srv);
  11823. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11824. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11825. sockaddr_in addr{};
  11826. addr.sin_family = AF_INET;
  11827. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11828. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11829. int opt = 1;
  11830. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11831. #ifdef _WIN32
  11832. reinterpret_cast<const char *>(&opt),
  11833. #else
  11834. &opt,
  11835. #endif
  11836. sizeof(opt));
  11837. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11838. ::listen(srv, 1);
  11839. sockaddr_in cli_addr{};
  11840. socklen_t cli_len = sizeof(cli_addr);
  11841. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11842. if (cli != INVALID_SOCKET) {
  11843. char buf[4096];
  11844. ::recv(cli, buf, sizeof(buf), 0);
  11845. // Malicious response: claim a 20GB body but send only a tiny payload.
  11846. std::string response = "HTTP/1.1 200 OK\r\n"
  11847. "Content-Length: 20000000000\r\n"
  11848. "\r\n"
  11849. "abc";
  11850. ::send(cli,
  11851. #ifdef _WIN32
  11852. static_cast<const char *>(response.c_str()),
  11853. static_cast<int>(response.size()),
  11854. #else
  11855. response.c_str(), response.size(),
  11856. #endif
  11857. 0);
  11858. detail::close_socket(cli);
  11859. }
  11860. detail::close_socket(srv);
  11861. });
  11862. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11863. {
  11864. Client cli("127.0.0.1", PORT + 2);
  11865. cli.set_read_timeout(5, 0);
  11866. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11867. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11868. // (server claims more bytes than payload_max_length permits), but it must
  11869. // not exhaust memory before getting there.
  11870. auto res = cli.Get("/malicious");
  11871. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11872. }
  11873. server_thread.join();
  11874. }
  11875. // Verify that content_receiver bypasses the default payload_max_length,
  11876. // allowing streaming downloads larger than 100MB without requiring an explicit
  11877. // set_payload_max_length call.
  11878. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11879. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11880. #ifndef _WIN32
  11881. signal(SIGPIPE, SIG_IGN);
  11882. #endif
  11883. auto server_thread = std::thread([] {
  11884. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11885. default_socket_options(srv);
  11886. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11887. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11888. sockaddr_in addr{};
  11889. addr.sin_family = AF_INET;
  11890. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11891. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11892. int opt = 1;
  11893. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11894. #ifdef _WIN32
  11895. reinterpret_cast<const char *>(&opt),
  11896. #else
  11897. &opt,
  11898. #endif
  11899. sizeof(opt));
  11900. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11901. ::listen(srv, 1);
  11902. sockaddr_in cli_addr{};
  11903. socklen_t cli_len = sizeof(cli_addr);
  11904. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11905. if (cli != INVALID_SOCKET) {
  11906. char buf[4096];
  11907. ::recv(cli, buf, sizeof(buf), 0);
  11908. // Response with Content-Length larger than default 100MB limit
  11909. auto content_length = std::to_string(DATA_SIZE);
  11910. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11911. "Content-Length: " +
  11912. content_length +
  11913. "\r\n"
  11914. "Connection: close\r\n"
  11915. "\r\n";
  11916. ::send(cli,
  11917. #ifdef _WIN32
  11918. static_cast<const char *>(response_header.c_str()),
  11919. static_cast<int>(response_header.size()),
  11920. #else
  11921. response_header.c_str(), response_header.size(),
  11922. #endif
  11923. 0);
  11924. std::string chunk(64 * 1024, 'A');
  11925. size_t total_sent = 0;
  11926. while (total_sent < DATA_SIZE) {
  11927. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11928. auto sent = ::send(cli,
  11929. #ifdef _WIN32
  11930. static_cast<const char *>(chunk.c_str()),
  11931. static_cast<int>(to_send),
  11932. #else
  11933. chunk.c_str(), to_send,
  11934. #endif
  11935. 0);
  11936. if (sent <= 0) break;
  11937. total_sent += static_cast<size_t>(sent);
  11938. }
  11939. detail::close_socket(cli);
  11940. }
  11941. detail::close_socket(srv);
  11942. });
  11943. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11944. size_t total_received = 0;
  11945. {
  11946. Client cli("127.0.0.1", PORT + 2);
  11947. cli.set_read_timeout(10, 0);
  11948. // Do NOT call set_payload_max_length — use the default 100MB limit
  11949. auto res =
  11950. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11951. total_received += data_length;
  11952. return true;
  11953. });
  11954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11955. EXPECT_EQ(StatusCode::OK_200, res->status);
  11956. }
  11957. server_thread.join();
  11958. EXPECT_EQ(total_received, DATA_SIZE)
  11959. << "With content_receiver, the client should read all " << DATA_SIZE
  11960. << " bytes despite the default 100MB payload_max_length, but only read "
  11961. << total_received << " bytes.";
  11962. }
  11963. // Verify that an explicit set_payload_max_length smaller than the response is
  11964. // enforced even when a content_receiver is used.
  11965. TEST(ClientVulnerabilityTest,
  11966. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11967. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11968. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11969. #ifndef _WIN32
  11970. signal(SIGPIPE, SIG_IGN);
  11971. #endif
  11972. auto server_thread = std::thread([] {
  11973. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11974. default_socket_options(srv);
  11975. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11976. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11977. sockaddr_in addr{};
  11978. addr.sin_family = AF_INET;
  11979. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11980. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11981. int opt = 1;
  11982. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11983. #ifdef _WIN32
  11984. reinterpret_cast<const char *>(&opt),
  11985. #else
  11986. &opt,
  11987. #endif
  11988. sizeof(opt));
  11989. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11990. ::listen(srv, 1);
  11991. sockaddr_in cli_addr{};
  11992. socklen_t cli_len = sizeof(cli_addr);
  11993. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11994. if (cli != INVALID_SOCKET) {
  11995. char buf[4096];
  11996. ::recv(cli, buf, sizeof(buf), 0);
  11997. auto content_length = std::to_string(DATA_SIZE);
  11998. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11999. "Content-Length: " +
  12000. content_length +
  12001. "\r\n"
  12002. "Connection: close\r\n"
  12003. "\r\n";
  12004. ::send(cli,
  12005. #ifdef _WIN32
  12006. static_cast<const char *>(response_header.c_str()),
  12007. static_cast<int>(response_header.size()),
  12008. #else
  12009. response_header.c_str(), response_header.size(),
  12010. #endif
  12011. 0);
  12012. std::string chunk(64 * 1024, 'A');
  12013. size_t total_sent = 0;
  12014. while (total_sent < DATA_SIZE) {
  12015. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12016. auto sent = ::send(cli,
  12017. #ifdef _WIN32
  12018. static_cast<const char *>(chunk.c_str()),
  12019. static_cast<int>(to_send),
  12020. #else
  12021. chunk.c_str(), to_send,
  12022. #endif
  12023. 0);
  12024. if (sent <= 0) break;
  12025. total_sent += static_cast<size_t>(sent);
  12026. }
  12027. detail::close_socket(cli);
  12028. }
  12029. detail::close_socket(srv);
  12030. });
  12031. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12032. size_t total_received = 0;
  12033. {
  12034. Client cli("127.0.0.1", PORT + 2);
  12035. cli.set_read_timeout(10, 0);
  12036. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12037. auto res =
  12038. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12039. total_received += data_length;
  12040. return true;
  12041. });
  12042. // Should fail because 200MB exceeds the explicit 150MB limit
  12043. EXPECT_FALSE(res);
  12044. }
  12045. server_thread.join();
  12046. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12047. << "Client with content_receiver should respect the explicit "
  12048. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12049. << total_received << " bytes.";
  12050. }
  12051. // Verify that an explicit set_payload_max_length larger than the response
  12052. // allows the content_receiver to read all data successfully.
  12053. TEST(ClientVulnerabilityTest,
  12054. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12055. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12056. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12057. #ifndef _WIN32
  12058. signal(SIGPIPE, SIG_IGN);
  12059. #endif
  12060. auto server_thread = std::thread([] {
  12061. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12062. default_socket_options(srv);
  12063. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12064. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12065. sockaddr_in addr{};
  12066. addr.sin_family = AF_INET;
  12067. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12068. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12069. int opt = 1;
  12070. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12071. #ifdef _WIN32
  12072. reinterpret_cast<const char *>(&opt),
  12073. #else
  12074. &opt,
  12075. #endif
  12076. sizeof(opt));
  12077. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12078. ::listen(srv, 1);
  12079. sockaddr_in cli_addr{};
  12080. socklen_t cli_len = sizeof(cli_addr);
  12081. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12082. if (cli != INVALID_SOCKET) {
  12083. char buf[4096];
  12084. ::recv(cli, buf, sizeof(buf), 0);
  12085. auto content_length = std::to_string(DATA_SIZE);
  12086. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12087. "Content-Length: " +
  12088. content_length +
  12089. "\r\n"
  12090. "Connection: close\r\n"
  12091. "\r\n";
  12092. ::send(cli,
  12093. #ifdef _WIN32
  12094. static_cast<const char *>(response_header.c_str()),
  12095. static_cast<int>(response_header.size()),
  12096. #else
  12097. response_header.c_str(), response_header.size(),
  12098. #endif
  12099. 0);
  12100. std::string chunk(64 * 1024, 'A');
  12101. size_t total_sent = 0;
  12102. while (total_sent < DATA_SIZE) {
  12103. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12104. auto sent = ::send(cli,
  12105. #ifdef _WIN32
  12106. static_cast<const char *>(chunk.c_str()),
  12107. static_cast<int>(to_send),
  12108. #else
  12109. chunk.c_str(), to_send,
  12110. #endif
  12111. 0);
  12112. if (sent <= 0) break;
  12113. total_sent += static_cast<size_t>(sent);
  12114. }
  12115. #ifdef _WIN32
  12116. ::shutdown(cli, SD_SEND);
  12117. #else
  12118. ::shutdown(cli, SHUT_WR);
  12119. #endif
  12120. char drain[1024];
  12121. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12122. detail::close_socket(cli);
  12123. }
  12124. detail::close_socket(srv);
  12125. });
  12126. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12127. size_t total_received = 0;
  12128. {
  12129. Client cli("127.0.0.1", PORT + 2);
  12130. cli.set_read_timeout(10, 0);
  12131. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12132. auto res =
  12133. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12134. total_received += data_length;
  12135. return true;
  12136. });
  12137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12138. EXPECT_EQ(StatusCode::OK_200, res->status);
  12139. }
  12140. server_thread.join();
  12141. EXPECT_EQ(total_received, DATA_SIZE)
  12142. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12143. << " bytes (larger than " << DATA_SIZE
  12144. << " bytes response), content_receiver should read all data, but only "
  12145. "read "
  12146. << total_received << " bytes.";
  12147. }
  12148. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12149. // Regression test for "zip bomb" attack on the client side: a malicious server
  12150. // sends a small gzip-compressed response that decompresses to a huge payload.
  12151. // The client must enforce payload_max_length on the decompressed size.
  12152. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12153. constexpr size_t DECOMPRESSED_SIZE =
  12154. 10 * 1024 * 1024; // 10MB after decompression
  12155. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12156. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12157. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12158. std::string compressed;
  12159. {
  12160. httplib::detail::gzip_compressor compressor;
  12161. bool ok =
  12162. compressor.compress(uncompressed.data(), uncompressed.size(),
  12163. /*last=*/true, [&](const char *buf, size_t len) {
  12164. compressed.append(buf, len);
  12165. return true;
  12166. });
  12167. ASSERT_TRUE(ok);
  12168. }
  12169. // Sanity: compressed data should be much smaller than the decompressed size
  12170. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12171. #ifndef _WIN32
  12172. signal(SIGPIPE, SIG_IGN);
  12173. #endif
  12174. // Set up the listening socket in the main thread so the server is guaranteed
  12175. // to be ready before the client connects (eliminates race condition).
  12176. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12177. default_socket_options(srv);
  12178. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12179. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12180. sockaddr_in addr{};
  12181. addr.sin_family = AF_INET;
  12182. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12183. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12184. int opt = 1;
  12185. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12186. #ifdef _WIN32
  12187. reinterpret_cast<const char *>(&opt),
  12188. #else
  12189. &opt,
  12190. #endif
  12191. sizeof(opt));
  12192. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12193. ASSERT_EQ(0, ::listen(srv, 1));
  12194. auto server_thread = std::thread([&compressed, srv] {
  12195. sockaddr_in cli_addr{};
  12196. socklen_t cli_len = sizeof(cli_addr);
  12197. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12198. if (cli != INVALID_SOCKET) {
  12199. // Read the full HTTP request (until \r\n\r\n)
  12200. char buf[4096];
  12201. size_t total = 0;
  12202. while (total < sizeof(buf)) {
  12203. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12204. if (n <= 0) break;
  12205. total += static_cast<size_t>(n);
  12206. // Check for end of headers
  12207. if (total >= 4) {
  12208. std::string req(buf, total);
  12209. if (req.find("\r\n\r\n") != std::string::npos) break;
  12210. }
  12211. }
  12212. // Malicious response: gzip-compressed body, no Content-Length
  12213. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12214. "Content-Encoding: gzip\r\n"
  12215. "Connection: close\r\n"
  12216. "\r\n";
  12217. ::send(cli,
  12218. #ifdef _WIN32
  12219. static_cast<const char *>(response_header.c_str()),
  12220. static_cast<int>(response_header.size()),
  12221. #else
  12222. response_header.c_str(), response_header.size(),
  12223. #endif
  12224. 0);
  12225. // Send the compressed payload (small on the wire, huge when decompressed)
  12226. size_t total_sent = 0;
  12227. while (total_sent < compressed.size()) {
  12228. auto to_send = std::min(compressed.size() - total_sent,
  12229. static_cast<size_t>(64 * 1024));
  12230. auto sent =
  12231. ::send(cli,
  12232. #ifdef _WIN32
  12233. static_cast<const char *>(compressed.c_str() + total_sent),
  12234. static_cast<int>(to_send),
  12235. #else
  12236. compressed.c_str() + total_sent, to_send,
  12237. #endif
  12238. 0);
  12239. if (sent <= 0) break;
  12240. total_sent += static_cast<size_t>(sent);
  12241. }
  12242. detail::close_socket(cli);
  12243. }
  12244. });
  12245. auto se = detail::scope_exit([&] {
  12246. detail::close_socket(srv);
  12247. server_thread.join();
  12248. });
  12249. size_t total_decompressed = 0;
  12250. {
  12251. Client cli("127.0.0.1", PORT + 3);
  12252. cli.set_read_timeout(5, 0);
  12253. cli.set_decompress(true);
  12254. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12255. auto stream = cli.open_stream("GET", "/zipbomb");
  12256. ASSERT_TRUE(stream.is_valid());
  12257. char buffer[64 * 1024];
  12258. ssize_t n;
  12259. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12260. total_decompressed += static_cast<size_t>(n);
  12261. }
  12262. }
  12263. // The decompressed size must be capped by payload_max_length. Without
  12264. // protection, the client would decompress the full 10MB from a tiny
  12265. // compressed payload, enabling a zip bomb DoS attack.
  12266. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12267. << "Client decompressed " << total_decompressed
  12268. << " bytes from a gzip response. The decompressed size should be "
  12269. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12270. }
  12271. #endif
  12272. TEST(HostAndPortPropertiesTest, NoSSL) {
  12273. httplib::Client cli("www.google.com", 1234);
  12274. ASSERT_EQ("www.google.com", cli.host());
  12275. ASSERT_EQ(1234, cli.port());
  12276. }
  12277. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12278. httplib::Client cli("www.google.com:1234");
  12279. ASSERT_EQ("www.google.com", cli.host());
  12280. ASSERT_EQ(1234, cli.port());
  12281. }
  12282. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12283. // Port number that overflows int — should not crash, client becomes invalid
  12284. httplib::Client cli("http://www.google.com:99999999999999999999");
  12285. ASSERT_FALSE(cli.is_valid());
  12286. }
  12287. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12288. // Port 99999 exceeds valid range (1-65535) — should not crash
  12289. httplib::Client cli("http://www.google.com:99999");
  12290. ASSERT_FALSE(cli.is_valid());
  12291. }
  12292. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12293. httplib::Client cli("http://www.google.com:80abc");
  12294. ASSERT_FALSE(cli.is_valid());
  12295. }
  12296. #ifdef CPPHTTPLIB_SSL_ENABLED
  12297. TEST(HostAndPortPropertiesTest, SSL) {
  12298. httplib::SSLClient cli("www.google.com");
  12299. ASSERT_EQ("www.google.com", cli.host());
  12300. ASSERT_EQ(443, cli.port());
  12301. }
  12302. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12303. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12304. std::string cert;
  12305. read_file(CA_CERT_FILE, cert);
  12306. httplib::SSLClient httplib_client("www.google.com");
  12307. // Load CA store first time
  12308. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12309. // Load CA store second time (update)
  12310. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12311. // Verify client is still valid and can make connections
  12312. httplib_client.enable_server_certificate_verification(true);
  12313. auto res = httplib_client.Get("/");
  12314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12315. // Google may return 200 or 301 depending on various factors
  12316. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12317. res->status == StatusCode::MovedPermanently_301);
  12318. }
  12319. TEST(SSLClientTest, ServerNameIndication_Online) {
  12320. auto host = "httpbingo.org";
  12321. auto path = std::string{"/get"};
  12322. SSLClient cli(host, 443);
  12323. auto res = cli.Get(path);
  12324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12325. ASSERT_EQ(StatusCode::OK_200, res->status);
  12326. }
  12327. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12328. // Use a site that will cause SSL verification failure due to self-signed cert
  12329. SSLClient cli("self-signed.badssl.com", 443);
  12330. cli.enable_server_certificate_verification(true);
  12331. auto res = cli.Get("/");
  12332. ASSERT_TRUE(!res);
  12333. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12334. // Verify backend error is captured for SSLServerVerification
  12335. // This occurs when certificate verification fails
  12336. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12337. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12338. EXPECT_NE(0UL, res.ssl_backend_error());
  12339. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12340. // For OpenSSL, ssl_error is 0 for verification errors
  12341. EXPECT_EQ(0, res.ssl_error());
  12342. #if !defined(_WIN32) || \
  12343. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12344. // On non-Windows or when Windows Schannel is disabled, the error comes
  12345. // from OpenSSL's verification
  12346. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12347. res.ssl_backend_error());
  12348. #endif
  12349. #endif
  12350. }
  12351. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12352. // Use a site where hostname doesn't match the certificate
  12353. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12354. SSLClient cli("wrong.host.badssl.com", 443);
  12355. cli.enable_server_certificate_verification(true);
  12356. cli.enable_server_hostname_verification(true);
  12357. auto res = cli.Get("/");
  12358. ASSERT_TRUE(!res);
  12359. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12360. // Verify backend error is captured for hostname verification failure
  12361. EXPECT_NE(0UL, res.ssl_backend_error());
  12362. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12363. // For OpenSSL, ssl_error is 0 for verification errors
  12364. EXPECT_EQ(0, res.ssl_error());
  12365. #if !defined(_WIN32) || \
  12366. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12367. // On non-Windows or when Windows Schannel is disabled, the error comes
  12368. // from OpenSSL's hostname verification
  12369. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12370. res.ssl_backend_error());
  12371. #endif
  12372. #endif
  12373. }
  12374. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12375. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12376. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12377. SSLClient cli("www.google.com", 443);
  12378. cli.enable_server_certificate_verification(true);
  12379. auto res = cli.Get("/");
  12380. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12381. }
  12382. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12383. SSLClient cli("www.google.com", 443);
  12384. cli.enable_server_certificate_verification(true);
  12385. cli.enable_windows_certificate_verification(false);
  12386. auto res = cli.Get("/");
  12387. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12388. }
  12389. // The server sends an intermediate cross-signed by a root Windows trusts,
  12390. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12391. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12392. SSLClient cli("accounts.spotify.com", 443);
  12393. auto res = cli.Get("/");
  12394. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12395. << " ssl_backend_error=" << res.ssl_backend_error();
  12396. }
  12397. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12398. // policy status, which no backend reports for a self-signed certificate.
  12399. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12400. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12401. ASSERT_TRUE(svr.is_valid());
  12402. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12403. auto se = detail::scope_exit([&] {
  12404. svr.stop();
  12405. t.join();
  12406. ASSERT_FALSE(svr.is_running());
  12407. });
  12408. svr.wait_until_ready();
  12409. SSLClient cli("127.0.0.1", PORT);
  12410. cli.set_connection_timeout(30);
  12411. auto res = cli.Get("/");
  12412. ASSERT_FALSE(res);
  12413. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12414. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12415. }
  12416. #endif
  12417. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12418. Client cli("https://google.com");
  12419. auto res = cli.Get("/");
  12420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12421. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12422. }
  12423. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12424. SSLClient cli("google.com");
  12425. cli.set_ca_cert_path(CA_CERT_FILE);
  12426. auto res = cli.Get("/");
  12427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12428. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12429. }
  12430. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12431. SSLClient cli("google.com");
  12432. cli.enable_server_certificate_verification(true);
  12433. cli.set_ca_cert_path("hello");
  12434. auto res = cli.Get("/");
  12435. ASSERT_TRUE(!res);
  12436. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12437. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12438. // should be set
  12439. EXPECT_EQ(0, res.ssl_error());
  12440. // Verify backend error is captured for SSLLoadingCerts
  12441. // This error occurs when loading CA certificates fails
  12442. EXPECT_NE(0UL, res.ssl_backend_error());
  12443. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12444. // OpenSSL specific error codes:
  12445. // > openssl errstr 0x80000002
  12446. // error:80000002:system library::No such file or directory
  12447. // > openssl errstr 0xA000126
  12448. // error:0A000126:SSL routines::unexpected eof while reading
  12449. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12450. res.ssl_backend_error() == 0xA000126);
  12451. #endif
  12452. }
  12453. TEST(SSLClientTest, ServerCertificateVerification4) {
  12454. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12455. ASSERT_TRUE(svr.is_valid());
  12456. svr.Get("/test", [&](const Request &, Response &res) {
  12457. res.set_content("test", "text/plain");
  12458. svr.stop();
  12459. ASSERT_TRUE(true);
  12460. });
  12461. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12462. auto se = detail::scope_exit([&] {
  12463. t.join();
  12464. ASSERT_FALSE(svr.is_running());
  12465. });
  12466. svr.wait_until_ready();
  12467. SSLClient cli("127.0.0.1", PORT);
  12468. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12469. cli.enable_server_certificate_verification(true);
  12470. cli.set_connection_timeout(30);
  12471. auto res = cli.Get("/test");
  12472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12473. ASSERT_EQ(StatusCode::OK_200, res->status);
  12474. }
  12475. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12476. std::string cert;
  12477. read_file(CA_CERT_FILE, cert);
  12478. SSLClient cli("google.com");
  12479. cli.load_ca_cert_store(cert.data(), cert.size());
  12480. const 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, ServerCertificateVerification6_Online) {
  12485. // clang-format off
  12486. static constexpr char cert[] =
  12487. "GlobalSign Root CA\n"
  12488. "==================\n"
  12489. "-----BEGIN CERTIFICATE-----\n"
  12490. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12491. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12492. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12493. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12494. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12495. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12496. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12497. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12498. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12499. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12500. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12501. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12502. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12503. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12504. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12505. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12506. "-----END CERTIFICATE-----\n";
  12507. // clang-format on
  12508. SSLClient cli("google.com");
  12509. cli.load_ca_cert_store(cert, sizeof(cert));
  12510. const auto res = cli.Get("/");
  12511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12512. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12513. }
  12514. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12515. SSLClient cli("www.youtube.com");
  12516. cli.set_ca_cert_path(CA_CERT_FILE);
  12517. cli.enable_server_certificate_verification(true);
  12518. cli.set_follow_location(true);
  12519. auto res = cli.Get("/");
  12520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12521. ASSERT_EQ(StatusCode::OK_200, res->status);
  12522. }
  12523. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12524. SSLClient cli("wWw.YouTube.Com");
  12525. cli.set_ca_cert_path(CA_CERT_FILE);
  12526. cli.enable_server_certificate_verification(true);
  12527. cli.enable_server_hostname_verification(true);
  12528. cli.set_follow_location(true);
  12529. auto res = cli.Get("/");
  12530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12531. ASSERT_EQ(StatusCode::OK_200, res->status);
  12532. }
  12533. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12534. SSLClient cli("gOoGlE.COm");
  12535. cli.enable_server_certificate_verification(true);
  12536. cli.enable_server_hostname_verification(true);
  12537. cli.set_follow_location(true);
  12538. auto res = cli.Get("/");
  12539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12540. ASSERT_EQ(StatusCode::OK_200, res->status);
  12541. }
  12542. TEST(SSLClientTest, Issue2004_Online) {
  12543. Client client("https://google.com");
  12544. client.set_follow_location(true);
  12545. auto res = client.Get("/");
  12546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12547. ASSERT_EQ(StatusCode::OK_200, res->status);
  12548. auto body = res->body;
  12549. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12550. }
  12551. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12552. // Create SSLClient with invalid cert/key to make is_valid() return false
  12553. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12554. "nonexistent_key.pem");
  12555. // is_valid() should be false due to cert loading failure
  12556. ASSERT_FALSE(cli.is_valid());
  12557. auto res = cli.Get("/");
  12558. ASSERT_FALSE(res);
  12559. EXPECT_EQ(Error::SSLConnection, res.error());
  12560. }
  12561. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12562. // Test for Issue #2251: SSL error not properly reported when client cert
  12563. // and key paths are swapped or mismatched
  12564. // This simulates the scenario where user accidentally swaps the cert and key
  12565. // files
  12566. // Using client cert file as private key and vice versa (completely wrong)
  12567. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12568. // Should fail validation due to cert/key mismatch
  12569. ASSERT_FALSE(cli.is_valid());
  12570. // Attempt to make a request should fail with proper error
  12571. auto res = cli.Get("/");
  12572. ASSERT_FALSE(res);
  12573. EXPECT_EQ(Error::SSLConnection, res.error());
  12574. // SSL error should be recorded in the Result object (this is the key fix for
  12575. // Issue #2251)
  12576. auto backend_error = res.ssl_backend_error();
  12577. EXPECT_NE(0u, backend_error);
  12578. }
  12579. // Tests cert/key mismatch detection at the TLS context level
  12580. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12581. // Test that using mismatched cert/key causes connection failure.
  12582. // We verify this at the SSLClient level rather than through internal
  12583. // TLS API functions.
  12584. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12585. cli.enable_server_certificate_verification(false);
  12586. cli.set_connection_timeout(2);
  12587. // The mismatch should cause a connection or handshake error
  12588. auto res = cli.Get("/test");
  12589. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12590. // Either way, the request should fail
  12591. EXPECT_FALSE(res);
  12592. }
  12593. #endif
  12594. #if 0
  12595. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12596. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12597. ASSERT_TRUE(cli != nullptr);
  12598. cli->set_address_family(AF_INET6);
  12599. cli->set_interface("en0");
  12600. auto res = cli->Get("/get");
  12601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12602. ASSERT_EQ(StatusCode::OK_200, res->status);
  12603. }
  12604. #endif
  12605. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12606. #ifdef CPPHTTPLIB_SSL_ENABLED
  12607. void ClientCertPresent(
  12608. const std::string &client_cert_file,
  12609. const std::string &client_private_key_file,
  12610. const std::string &client_encrypted_private_key_pass = std::string()) {
  12611. using namespace httplib::tls;
  12612. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12613. CLIENT_CA_CERT_DIR);
  12614. ASSERT_TRUE(svr.is_valid());
  12615. svr.Get("/test", [&](const Request &req, Response &res) {
  12616. res.set_content("test", "text/plain");
  12617. auto cert = req.peer_cert();
  12618. ASSERT_TRUE(static_cast<bool>(cert));
  12619. std::string common_name = cert.subject_cn();
  12620. EXPECT_EQ("Common Name", common_name);
  12621. });
  12622. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12623. auto se = detail::scope_exit([&] {
  12624. svr.stop();
  12625. t.join();
  12626. ASSERT_FALSE(svr.is_running());
  12627. });
  12628. svr.wait_until_ready();
  12629. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12630. client_encrypted_private_key_pass);
  12631. cli.enable_server_certificate_verification(false);
  12632. cli.set_connection_timeout(30);
  12633. auto res = cli.Get("/test");
  12634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12635. ASSERT_EQ(StatusCode::OK_200, res->status);
  12636. }
  12637. TEST(SSLClientServerTest, ClientCertPresent) {
  12638. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12639. }
  12640. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12641. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12642. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12643. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12644. }
  12645. // PEM memory-based constructor tests (works with all TLS backends)
  12646. void PemMemoryClientCertPresent(
  12647. const std::string &client_cert_file,
  12648. const std::string &client_private_key_file,
  12649. const std::string &client_encrypted_private_key_pass = std::string()) {
  12650. // Read PEM files into memory
  12651. std::string server_cert_pem, server_key_pem;
  12652. std::string client_ca_pem;
  12653. std::string client_cert_pem, client_key_pem;
  12654. read_file(SERVER_CERT_FILE, server_cert_pem);
  12655. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12656. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12657. read_file(client_cert_file, client_cert_pem);
  12658. read_file(client_private_key_file, client_key_pem);
  12659. // Create server with PEM memory
  12660. SSLServer::PemMemory server_pem = {
  12661. server_cert_pem.c_str(),
  12662. server_cert_pem.size(),
  12663. server_key_pem.c_str(),
  12664. server_key_pem.size(),
  12665. client_ca_pem.c_str(),
  12666. client_ca_pem.size(),
  12667. nullptr // no password for server key
  12668. };
  12669. SSLServer svr(server_pem);
  12670. ASSERT_TRUE(svr.is_valid());
  12671. svr.Get("/test", [&](const Request &, Response &res) {
  12672. res.set_content("test", "text/plain");
  12673. });
  12674. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12675. auto se = detail::scope_exit([&] {
  12676. svr.stop();
  12677. t.join();
  12678. ASSERT_FALSE(svr.is_running());
  12679. });
  12680. svr.wait_until_ready();
  12681. // Create client with PEM memory
  12682. const char *password = client_encrypted_private_key_pass.empty()
  12683. ? nullptr
  12684. : client_encrypted_private_key_pass.c_str();
  12685. SSLClient::PemMemory client_pem = {
  12686. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12687. client_key_pem.size(), password};
  12688. SSLClient cli(HOST, PORT, client_pem);
  12689. cli.enable_server_certificate_verification(false);
  12690. cli.set_connection_timeout(30);
  12691. auto res = cli.Get("/test");
  12692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12693. ASSERT_EQ(StatusCode::OK_200, res->status);
  12694. }
  12695. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12696. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12697. }
  12698. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12699. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12700. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12701. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12702. }
  12703. TEST(SSLClientServerTest, ClientCertMissing) {
  12704. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12705. CLIENT_CA_CERT_DIR);
  12706. ASSERT_TRUE(svr.is_valid());
  12707. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12708. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12709. auto se = detail::scope_exit([&] {
  12710. svr.stop();
  12711. t.join();
  12712. ASSERT_FALSE(svr.is_running());
  12713. });
  12714. svr.wait_until_ready();
  12715. SSLClient cli(HOST, PORT);
  12716. cli.set_connection_timeout(30);
  12717. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12718. // the chain check on Windows, so the result does not depend on the order.
  12719. cli.enable_server_hostname_verification(false);
  12720. auto res = cli.Get("/test");
  12721. ASSERT_TRUE(!res);
  12722. // When client cert is missing and server requires it, connection fails
  12723. // Error type depends on backend implementation
  12724. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12725. res.error() == Error::SSLConnection);
  12726. // Verify backend error is captured
  12727. // Note: This test may have different error codes depending on the exact
  12728. // verification failure
  12729. EXPECT_NE(0UL, res.ssl_backend_error());
  12730. }
  12731. TEST(SSLClientServerTest, TrustDirOptional) {
  12732. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12733. ASSERT_TRUE(svr.is_valid());
  12734. svr.Get("/test", [&](const Request &, Response &res) {
  12735. res.set_content("test", "text/plain");
  12736. });
  12737. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12738. auto se = detail::scope_exit([&] {
  12739. svr.stop();
  12740. t.join();
  12741. ASSERT_FALSE(svr.is_running());
  12742. });
  12743. svr.wait_until_ready();
  12744. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12745. cli.enable_server_certificate_verification(false);
  12746. cli.set_connection_timeout(30);
  12747. auto res = cli.Get("/test");
  12748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12749. ASSERT_EQ(StatusCode::OK_200, res->status);
  12750. }
  12751. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12752. class NoListenSSLServer : public SSLServer {
  12753. public:
  12754. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12755. const char *client_ca_cert_file_path,
  12756. const char *client_ca_cert_dir_path = nullptr)
  12757. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12758. client_ca_cert_dir_path),
  12759. stop_(false) {}
  12760. std::atomic_bool stop_;
  12761. private:
  12762. bool process_and_close_socket(socket_t /*sock*/) override {
  12763. // Don't create SSL context
  12764. while (!stop_.load()) {
  12765. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12766. }
  12767. return true;
  12768. }
  12769. };
  12770. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12771. CLIENT_CA_CERT_FILE);
  12772. ASSERT_TRUE(svr.is_valid());
  12773. svr.Get("/test", [&](const Request &, Response &res) {
  12774. res.set_content("test", "text/plain");
  12775. });
  12776. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12777. auto se = detail::scope_exit([&] {
  12778. svr.stop_ = true;
  12779. svr.stop();
  12780. t.join();
  12781. ASSERT_FALSE(svr.is_running());
  12782. });
  12783. svr.wait_until_ready();
  12784. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12785. cli.enable_server_certificate_verification(false);
  12786. cli.set_connection_timeout(1);
  12787. auto res = cli.Get("/test");
  12788. ASSERT_TRUE(!res);
  12789. EXPECT_EQ(Error::SSLConnection, res.error());
  12790. // Timeout results in WantRead error code (maps to backend-specific value)
  12791. EXPECT_NE(0, res.ssl_error());
  12792. }
  12793. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12794. // Test SSLServer with client certificate verification using the standard
  12795. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12796. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12797. CLIENT_CA_CERT_DIR);
  12798. ASSERT_TRUE(svr.is_valid());
  12799. svr.Get("/test", [&](const Request &req, Response &res) {
  12800. res.set_content("test", "text/plain");
  12801. auto cert = req.peer_cert();
  12802. ASSERT_TRUE(static_cast<bool>(cert));
  12803. auto common_name = cert.subject_cn();
  12804. EXPECT_EQ("Common Name", common_name);
  12805. });
  12806. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12807. auto se = detail::scope_exit([&] {
  12808. svr.stop();
  12809. t.join();
  12810. ASSERT_FALSE(svr.is_running());
  12811. });
  12812. svr.wait_until_ready();
  12813. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12814. cli.enable_server_certificate_verification(false);
  12815. cli.set_connection_timeout(30);
  12816. auto res = cli.Get("/test");
  12817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12818. ASSERT_EQ(StatusCode::OK_200, res->status);
  12819. }
  12820. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12821. // Verifies that wildcard matching and exact matching work consistently
  12822. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12823. using namespace httplib::tls;
  12824. // We need a running server to test against
  12825. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12826. ASSERT_TRUE(svr.is_valid());
  12827. svr.Get("/test", [](const Request &, Response &res) {
  12828. res.set_content("ok", "text/plain");
  12829. });
  12830. thread t([&]() { svr.listen(HOST, PORT); });
  12831. auto se = detail::scope_exit([&] {
  12832. svr.stop();
  12833. t.join();
  12834. });
  12835. svr.wait_until_ready();
  12836. bool verify_callback_called = false;
  12837. bool verify_result_wrong = false;
  12838. SSLClient cli(HOST, PORT);
  12839. cli.enable_server_certificate_verification(true);
  12840. cli.set_ca_cert_path(CA_CERT_FILE);
  12841. cli.set_connection_timeout(5);
  12842. // Note: Test certificate has CN="Common Name", not "localhost"
  12843. bool verify_result_cn = false;
  12844. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12845. verify_callback_called = true;
  12846. if (!ctx.cert) return false;
  12847. // Test 1: "Common Name" should match (our test server cert CN)
  12848. verify_result_cn = ctx.check_hostname("Common Name");
  12849. // Test 2: wrong hostname should not match
  12850. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12851. return true; // Accept for the purpose of this test
  12852. });
  12853. auto res = cli.Get("/test");
  12854. // The request may succeed or fail depending on cert configuration
  12855. // but the callback should have been called
  12856. ASSERT_TRUE(verify_callback_called)
  12857. << "Verify callback should have been called";
  12858. // CN="Common Name" should match our test certificate
  12859. //
  12860. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12861. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12862. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12863. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12864. // <openssl/base.h>, which is included transitively when
  12865. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12866. #if defined(OPENSSL_IS_BORINGSSL)
  12867. EXPECT_FALSE(verify_result_cn)
  12868. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12869. #else
  12870. EXPECT_TRUE(verify_result_cn)
  12871. << "verify_hostname should match 'Common Name' (certificate CN)";
  12872. #endif
  12873. // Wrong hostname should not match
  12874. EXPECT_FALSE(verify_result_wrong)
  12875. << "verify_hostname should not match 'wronghost.example.com'";
  12876. }
  12877. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12878. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12879. // X509_check_ip behavior and must hold for every backend.
  12880. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12881. using namespace httplib::tls;
  12882. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12883. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12884. ASSERT_TRUE(svr.is_valid());
  12885. svr.Get("/test", [](const Request &, Response &res) {
  12886. res.set_content("ok", "text/plain");
  12887. });
  12888. thread t([&]() { svr.listen(HOST, PORT); });
  12889. auto se = detail::scope_exit([&] {
  12890. svr.stop();
  12891. t.join();
  12892. });
  12893. svr.wait_until_ready();
  12894. bool verify_callback_called = false;
  12895. bool ip_matched_via_cn = true;
  12896. SSLClient cli(HOST, PORT);
  12897. cli.enable_server_certificate_verification(true);
  12898. cli.set_ca_cert_path(CA_CERT_FILE);
  12899. cli.set_connection_timeout(5);
  12900. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12901. verify_callback_called = true;
  12902. if (!ctx.cert) return false;
  12903. // The IP appears only in the CN, so it must NOT be accepted.
  12904. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12905. return true; // Accept for the purpose of this test
  12906. });
  12907. cli.Get("/test");
  12908. ASSERT_TRUE(verify_callback_called)
  12909. << "Verify callback should have been called";
  12910. EXPECT_FALSE(ip_matched_via_cn)
  12911. << "An IP host must not be authenticated via the certificate CN";
  12912. }
  12913. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12914. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12915. using namespace httplib::tls;
  12916. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12917. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12918. ASSERT_TRUE(svr.is_valid());
  12919. svr.Get("/test", [](const Request &, Response &res) {
  12920. res.set_content("ok", "text/plain");
  12921. });
  12922. thread t([&]() { svr.listen(HOST, PORT); });
  12923. auto se = detail::scope_exit([&] {
  12924. svr.stop();
  12925. t.join();
  12926. });
  12927. svr.wait_until_ready();
  12928. bool verify_callback_called = false;
  12929. bool san_matched = false;
  12930. bool wrong_ipv6_matched = true;
  12931. bool cn_ipv6_matched = true;
  12932. SSLClient cli(HOST, PORT);
  12933. cli.enable_server_certificate_verification(true);
  12934. cli.set_ca_cert_path(CA_CERT_FILE);
  12935. cli.set_connection_timeout(5);
  12936. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12937. verify_callback_called = true;
  12938. if (!ctx.cert) return false;
  12939. // Matches the IPv6 iPAddress SAN.
  12940. san_matched = ctx.check_hostname("2001:db8::1");
  12941. // A different IPv6 address must not match.
  12942. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12943. // "::1" lives only in the CN, so it must not be accepted.
  12944. cn_ipv6_matched = ctx.check_hostname("::1");
  12945. return true; // Accept for the purpose of this test
  12946. });
  12947. cli.Get("/test");
  12948. ASSERT_TRUE(verify_callback_called)
  12949. << "Verify callback should have been called";
  12950. EXPECT_TRUE(san_matched)
  12951. << "verify_hostname should match an IPv6 iPAddress SAN";
  12952. EXPECT_FALSE(wrong_ipv6_matched)
  12953. << "verify_hostname should not match a non-matching IPv6 address";
  12954. EXPECT_FALSE(cn_ipv6_matched)
  12955. << "An IPv6 host must not be authenticated via the certificate CN";
  12956. }
  12957. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  12958. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  12959. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  12960. using namespace httplib::tls;
  12961. // SANs: DNS:a.zz, IP:42.46.122.122
  12962. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12963. ASSERT_TRUE(svr.is_valid());
  12964. svr.Get("/test", [](const Request &, Response &res) {
  12965. res.set_content("ok", "text/plain");
  12966. });
  12967. auto port = svr.bind_to_any_port(HOST);
  12968. thread t([&]() { svr.listen_after_bind(); });
  12969. auto se = detail::scope_exit([&] {
  12970. svr.stop();
  12971. t.join();
  12972. });
  12973. svr.wait_until_ready();
  12974. bool verify_callback_called = false;
  12975. bool dns_san_matched = false;
  12976. bool ip_san_matched = false;
  12977. bool ip_matched_via_dns_san = true;
  12978. bool dns_matched_via_ip_san = true;
  12979. SSLClient cli(HOST, port);
  12980. cli.enable_server_certificate_verification(true);
  12981. cli.set_ca_cert_path(CA_CERT_FILE);
  12982. cli.set_connection_timeout(5);
  12983. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12984. verify_callback_called = true;
  12985. if (!ctx.cert) return false;
  12986. dns_san_matched = ctx.check_hostname("a.zz");
  12987. ip_san_matched = ctx.check_hostname("42.46.122.122");
  12988. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  12989. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  12990. return true; // Accept for the purpose of this test
  12991. });
  12992. cli.Get("/test");
  12993. ASSERT_TRUE(verify_callback_called)
  12994. << "Verify callback should have been called";
  12995. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  12996. EXPECT_TRUE(ip_san_matched)
  12997. << "verify_hostname should match an iPAddress SAN";
  12998. EXPECT_FALSE(ip_matched_via_dns_san)
  12999. << "An IP host must not be authenticated via a dNSName SAN";
  13000. EXPECT_FALSE(dns_matched_via_ip_san)
  13001. << "A DNS host must not be authenticated via an iPAddress SAN";
  13002. }
  13003. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13004. // "www.*.example.test" names one host and not every host under example.test.
  13005. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13006. using namespace httplib::tls;
  13007. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13008. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13009. ASSERT_TRUE(svr.is_valid());
  13010. svr.Get("/test", [](const Request &, Response &res) {
  13011. res.set_content("ok", "text/plain");
  13012. });
  13013. auto port = svr.bind_to_any_port(HOST);
  13014. thread t([&]() { svr.listen_after_bind(); });
  13015. auto se = detail::scope_exit([&] {
  13016. svr.stop();
  13017. t.join();
  13018. });
  13019. svr.wait_until_ready();
  13020. bool verify_callback_called = false;
  13021. bool leftmost_wildcard_matched = false;
  13022. bool wildcard_spanned_labels = true;
  13023. bool inner_wildcard_matched = true;
  13024. SSLClient cli(HOST, port);
  13025. cli.enable_server_certificate_verification(true);
  13026. cli.set_ca_cert_path(CA_CERT_FILE);
  13027. cli.set_connection_timeout(5);
  13028. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13029. verify_callback_called = true;
  13030. if (!ctx.cert) return false;
  13031. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13032. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13033. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13034. return true; // Accept for the purpose of this test
  13035. });
  13036. cli.Get("/test");
  13037. ASSERT_TRUE(verify_callback_called)
  13038. << "Verify callback should have been called";
  13039. EXPECT_TRUE(leftmost_wildcard_matched)
  13040. << "A leftmost wildcard should match a single label";
  13041. EXPECT_FALSE(wildcard_spanned_labels)
  13042. << "A wildcard label must not match more than one label";
  13043. EXPECT_FALSE(inner_wildcard_matched)
  13044. << "A wildcard outside the leftmost label must not be honoured";
  13045. }
  13046. // sans() must report each SAN entry under its own type.
  13047. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13048. using namespace httplib::tls;
  13049. // SANs: DNS:a.zz, IP:42.46.122.122
  13050. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13051. ASSERT_TRUE(svr.is_valid());
  13052. svr.Get("/test", [](const Request &, Response &res) {
  13053. res.set_content("ok", "text/plain");
  13054. });
  13055. auto port = svr.bind_to_any_port(HOST);
  13056. thread t([&]() { svr.listen_after_bind(); });
  13057. auto se = detail::scope_exit([&] {
  13058. svr.stop();
  13059. t.join();
  13060. });
  13061. svr.wait_until_ready();
  13062. bool verify_callback_called = false;
  13063. std::vector<SanEntry> sans;
  13064. SSLClient cli(HOST, port);
  13065. cli.enable_server_certificate_verification(true);
  13066. cli.set_ca_cert_path(CA_CERT_FILE);
  13067. cli.set_connection_timeout(5);
  13068. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13069. verify_callback_called = true;
  13070. if (!ctx.cert) return false;
  13071. sans = ctx.sans();
  13072. return true; // Accept for the purpose of this test
  13073. });
  13074. cli.Get("/test");
  13075. ASSERT_TRUE(verify_callback_called)
  13076. << "Verify callback should have been called";
  13077. auto has_san = [&](SanType type, const std::string &value) {
  13078. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13079. return san.type == type && san.value == value;
  13080. });
  13081. };
  13082. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13083. << "sans() should report the dNSName SAN";
  13084. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13085. << "sans() should report the iPAddress SAN";
  13086. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13087. << "sans() must not report the dNSName SAN as an address";
  13088. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13089. << "sans() must not report the iPAddress SAN as a DNS name";
  13090. }
  13091. #endif
  13092. // mbedTLS-specific callback constructor test
  13093. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13094. #ifdef CPPHTTPLIB_SSL_ENABLED
  13095. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13096. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13097. ASSERT_TRUE(svr.is_valid());
  13098. // Set up a handler to verify client certificate is present
  13099. bool client_cert_verified = false;
  13100. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13101. // Verify that client certificate was provided
  13102. client_cert_verified = true;
  13103. res.set_content("success", "text/plain");
  13104. });
  13105. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13106. auto se = detail::scope_exit([&] {
  13107. svr.stop();
  13108. t.join();
  13109. ASSERT_FALSE(svr.is_running());
  13110. });
  13111. svr.wait_until_ready();
  13112. // Client with certificate
  13113. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13114. cli.enable_server_certificate_verification(false);
  13115. cli.set_connection_timeout(30);
  13116. auto res = cli.Get("/test");
  13117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13118. ASSERT_EQ(StatusCode::OK_200, res->status);
  13119. ASSERT_TRUE(client_cert_verified);
  13120. EXPECT_EQ("success", res->body);
  13121. }
  13122. #endif
  13123. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13124. // backends
  13125. #ifdef CPPHTTPLIB_SSL_ENABLED
  13126. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13127. using namespace httplib::tls;
  13128. // Test that when client CA cert file is provided,
  13129. // the server properly requests and validates client certificates
  13130. // Create a server with client authentication
  13131. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13132. ASSERT_TRUE(svr.is_valid());
  13133. bool handler_called = false;
  13134. svr.Get("/test", [&](const Request &req, Response &res) {
  13135. handler_called = true;
  13136. // Verify that a client certificate was provided
  13137. auto cert = req.peer_cert();
  13138. ASSERT_TRUE(static_cast<bool>(cert));
  13139. // Get the issuer name
  13140. std::string issuer_str = cert.issuer_name();
  13141. ASSERT_FALSE(issuer_str.empty());
  13142. // The client certificate should be issued by our test CA
  13143. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13144. res.set_content("authenticated", "text/plain");
  13145. });
  13146. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13147. auto se = detail::scope_exit([&] {
  13148. svr.stop();
  13149. t.join();
  13150. ASSERT_FALSE(svr.is_running());
  13151. });
  13152. svr.wait_until_ready();
  13153. // Connect with a client certificate issued by the CA
  13154. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13155. cli.enable_server_certificate_verification(false);
  13156. cli.set_connection_timeout(30);
  13157. auto res = cli.Get("/test");
  13158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13159. ASSERT_EQ(StatusCode::OK_200, res->status);
  13160. ASSERT_TRUE(handler_called);
  13161. EXPECT_EQ("authenticated", res->body);
  13162. }
  13163. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13164. using namespace httplib::tls;
  13165. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13166. ASSERT_TRUE(svr.is_valid());
  13167. svr.Get("/test", [](const Request &, Response &res) {
  13168. res.set_content("ok", "text/plain");
  13169. });
  13170. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13171. auto se = detail::scope_exit([&] {
  13172. svr.stop();
  13173. t.join();
  13174. });
  13175. svr.wait_until_ready();
  13176. SSLClient cli(HOST, PORT);
  13177. cli.enable_server_certificate_verification(false);
  13178. cli.set_connection_timeout(30);
  13179. bool cert_checked = false;
  13180. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13181. if (ctx.cert) {
  13182. auto sans = ctx.sans();
  13183. // Test certificate may or may not have SANs - just verify the API
  13184. // works If SANs exist, verify the types are valid
  13185. for (const auto &san : sans) {
  13186. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13187. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13188. san.type == SanType::OTHER);
  13189. EXPECT_FALSE(san.value.empty());
  13190. }
  13191. cert_checked = true;
  13192. }
  13193. return true;
  13194. });
  13195. auto res = cli.Get("/test");
  13196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13197. EXPECT_TRUE(cert_checked);
  13198. }
  13199. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13200. using namespace httplib::tls;
  13201. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13202. ASSERT_TRUE(svr.is_valid());
  13203. svr.Get("/test", [](const Request &, Response &res) {
  13204. res.set_content("ok", "text/plain");
  13205. });
  13206. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13207. auto se = detail::scope_exit([&] {
  13208. svr.stop();
  13209. t.join();
  13210. });
  13211. svr.wait_until_ready();
  13212. SSLClient cli(HOST, PORT);
  13213. cli.enable_server_certificate_verification(false);
  13214. cli.set_connection_timeout(30);
  13215. bool validity_checked = false;
  13216. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13217. if (ctx.cert) {
  13218. time_t not_before = 0, not_after = 0;
  13219. bool result = ctx.validity(not_before, not_after);
  13220. EXPECT_TRUE(result);
  13221. // Verify that not_before < now < not_after for a valid cert
  13222. time_t now = time(nullptr);
  13223. EXPECT_LT(not_before, now);
  13224. EXPECT_GT(not_after, now);
  13225. validity_checked = true;
  13226. }
  13227. return true;
  13228. });
  13229. auto res = cli.Get("/test");
  13230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13231. EXPECT_TRUE(validity_checked);
  13232. }
  13233. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13234. using namespace httplib::tls;
  13235. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13236. ASSERT_TRUE(svr.is_valid());
  13237. svr.Get("/test", [](const Request &, Response &res) {
  13238. res.set_content("ok", "text/plain");
  13239. });
  13240. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13241. auto se = detail::scope_exit([&] {
  13242. svr.stop();
  13243. t.join();
  13244. });
  13245. svr.wait_until_ready();
  13246. SSLClient cli(HOST, PORT);
  13247. cli.enable_server_certificate_verification(false);
  13248. cli.set_connection_timeout(30);
  13249. bool serial_checked = false;
  13250. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13251. if (ctx.cert) {
  13252. std::string serial = ctx.serial();
  13253. EXPECT_FALSE(serial.empty());
  13254. // Serial should be a hex string
  13255. for (char c : serial) {
  13256. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13257. (c >= 'a' && c <= 'f'));
  13258. }
  13259. serial_checked = true;
  13260. }
  13261. return true;
  13262. });
  13263. auto res = cli.Get("/test");
  13264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13265. EXPECT_TRUE(serial_checked);
  13266. }
  13267. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13268. // Test 1: Valid CA file - no error should be recorded
  13269. {
  13270. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13271. CLIENT_CA_CERT_FILE);
  13272. ASSERT_TRUE(svr.is_valid());
  13273. // With valid setup, last_ssl_error should be 0
  13274. EXPECT_EQ(0, svr.ssl_last_error());
  13275. }
  13276. // Test 2: Invalid CA file content
  13277. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13278. {
  13279. // Create a temporary file with completely invalid content
  13280. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13281. {
  13282. std::ofstream ofs(temp_invalid_ca);
  13283. ofs << "This is not a certificate file at all\n";
  13284. ofs << "Just plain text content\n";
  13285. }
  13286. // Create server with invalid CA file
  13287. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13288. // Clean up temporary file
  13289. std::remove(temp_invalid_ca);
  13290. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13291. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13292. // Note: SSL_CTX_load_verify_locations typically fails first,
  13293. // but our error handling code path is still exercised
  13294. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13295. }
  13296. }
  13297. TEST(VerifyCallbackTest, VerifyContextFields) {
  13298. using namespace httplib::tls;
  13299. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13300. ASSERT_TRUE(svr.is_valid());
  13301. svr.Get("/test", [](const Request &, Response &res) {
  13302. res.set_content("ok", "text/plain");
  13303. });
  13304. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13305. auto se = detail::scope_exit([&] {
  13306. svr.stop();
  13307. t.join();
  13308. });
  13309. svr.wait_until_ready();
  13310. SSLClient cli(HOST, PORT);
  13311. cli.enable_server_certificate_verification(false);
  13312. cli.set_connection_timeout(30);
  13313. int callback_count = 0;
  13314. bool saw_leaf_cert = false;
  13315. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13316. if (ctx.cert) {
  13317. callback_count++;
  13318. // We should see at least one certificate (the leaf)
  13319. std::string cn = ctx.subject_cn();
  13320. if (!cn.empty()) { saw_leaf_cert = true; }
  13321. // Verify context fields are populated
  13322. EXPECT_NE(ctx.session, nullptr);
  13323. EXPECT_GE(ctx.depth, 0);
  13324. }
  13325. return true;
  13326. });
  13327. auto res = cli.Get("/test");
  13328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13329. EXPECT_GT(callback_count, 0);
  13330. EXPECT_TRUE(saw_leaf_cert);
  13331. }
  13332. // A verifier belongs to the client that set it, not to the thread that set it.
  13333. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13334. using namespace httplib::tls;
  13335. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13336. ASSERT_TRUE(svr.is_valid());
  13337. svr.Get("/test", [](const Request &, Response &res) {
  13338. res.set_content("ok", "text/plain");
  13339. });
  13340. auto port = svr.bind_to_any_port(HOST);
  13341. thread t([&]() { svr.listen_after_bind(); });
  13342. auto se = detail::scope_exit([&] {
  13343. svr.stop();
  13344. t.join();
  13345. });
  13346. svr.wait_until_ready();
  13347. auto rejecting_calls = 0;
  13348. SSLClient rejecting(HOST, port);
  13349. rejecting.enable_server_certificate_verification(false);
  13350. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13351. rejecting_calls++;
  13352. return false;
  13353. });
  13354. auto accepting_calls = 0;
  13355. SSLClient accepting(HOST, port);
  13356. accepting.enable_server_certificate_verification(false);
  13357. // Set on another thread than the requests below.
  13358. thread([&]() {
  13359. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13360. accepting_calls++;
  13361. return true;
  13362. });
  13363. }).join();
  13364. // Requested on another thread than the verifier was set on.
  13365. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13366. EXPECT_GT(rejecting_calls, 0);
  13367. auto res = accepting.Get("/test");
  13368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13369. EXPECT_GT(accepting_calls, 0);
  13370. }
  13371. // VerifyContext::session is the same handle the other tls:: functions take.
  13372. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13373. using namespace httplib::tls;
  13374. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13375. ASSERT_TRUE(svr.is_valid());
  13376. svr.Get("/test", [](const Request &, Response &res) {
  13377. res.set_content("ok", "text/plain");
  13378. });
  13379. auto port = svr.bind_to_any_port(HOST);
  13380. thread t([&]() { svr.listen_after_bind(); });
  13381. auto se = detail::scope_exit([&] {
  13382. svr.stop();
  13383. t.join();
  13384. });
  13385. svr.wait_until_ready();
  13386. SSLClient cli(HOST, port);
  13387. cli.enable_server_certificate_verification(false);
  13388. session_t verifier_session = nullptr;
  13389. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  13390. verifier_session = ctx.session;
  13391. return true;
  13392. });
  13393. session_t session_verifier_session = nullptr;
  13394. cli.set_session_verifier([&](session_t session) {
  13395. session_verifier_session = session;
  13396. return SSLVerifierResponse::NoDecisionMade;
  13397. });
  13398. auto res = cli.Get("/test");
  13399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13400. EXPECT_NE(nullptr, verifier_session);
  13401. EXPECT_EQ(session_verifier_session, verifier_session);
  13402. }
  13403. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13404. using httplib::tls::TlsError;
  13405. // Test that verify_error_to_string returns empty for success
  13406. std::string success_str = TlsError::verify_error_to_string(0);
  13407. EXPECT_TRUE(success_str.empty());
  13408. // Test that verify_error_to_string returns non-empty for error codes
  13409. // Using a common error code (certificate expired)
  13410. std::string error_str =
  13411. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13412. EXPECT_FALSE(error_str.empty());
  13413. }
  13414. TEST(SessionVerifierTest, CertificateAccepted) {
  13415. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13416. ASSERT_TRUE(svr.is_valid());
  13417. svr.Get("/test", [](const Request &, Response &res) {
  13418. res.set_content("ok", "text/plain");
  13419. });
  13420. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13421. auto se = detail::scope_exit([&] {
  13422. svr.stop();
  13423. t.join();
  13424. });
  13425. svr.wait_until_ready();
  13426. SSLClient cli(HOST, PORT);
  13427. cli.enable_server_certificate_verification(false);
  13428. cli.set_connection_timeout(30);
  13429. bool callback_called = false;
  13430. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13431. EXPECT_NE(session, nullptr);
  13432. callback_called = true;
  13433. return SSLVerifierResponse::CertificateAccepted;
  13434. });
  13435. auto res = cli.Get("/test");
  13436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13437. EXPECT_EQ(200, res->status);
  13438. EXPECT_TRUE(callback_called);
  13439. }
  13440. TEST(SessionVerifierTest, CertificateRejected) {
  13441. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13442. ASSERT_TRUE(svr.is_valid());
  13443. svr.Get("/test", [](const Request &, Response &res) {
  13444. res.set_content("ok", "text/plain");
  13445. });
  13446. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13447. auto se = detail::scope_exit([&] {
  13448. svr.stop();
  13449. t.join();
  13450. });
  13451. svr.wait_until_ready();
  13452. SSLClient cli(HOST, PORT);
  13453. cli.enable_server_certificate_verification(false);
  13454. cli.set_connection_timeout(30);
  13455. bool callback_called = false;
  13456. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13457. EXPECT_NE(session, nullptr);
  13458. callback_called = true;
  13459. return SSLVerifierResponse::CertificateRejected;
  13460. });
  13461. auto res = cli.Get("/test");
  13462. EXPECT_FALSE(res);
  13463. EXPECT_TRUE(callback_called);
  13464. }
  13465. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13466. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13467. ASSERT_TRUE(svr.is_valid());
  13468. svr.Get("/test", [](const Request &, Response &res) {
  13469. res.set_content("ok", "text/plain");
  13470. });
  13471. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13472. auto se = detail::scope_exit([&] {
  13473. svr.stop();
  13474. t.join();
  13475. });
  13476. svr.wait_until_ready();
  13477. // NoDecisionMade with verification disabled should succeed (no default check)
  13478. SSLClient cli(HOST, PORT);
  13479. cli.enable_server_certificate_verification(false);
  13480. cli.set_connection_timeout(30);
  13481. bool callback_called = false;
  13482. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13483. EXPECT_NE(session, nullptr);
  13484. callback_called = true;
  13485. return SSLVerifierResponse::NoDecisionMade;
  13486. });
  13487. auto res = cli.Get("/test");
  13488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13489. EXPECT_EQ(200, res->status);
  13490. EXPECT_TRUE(callback_called);
  13491. }
  13492. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  13493. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13494. ASSERT_TRUE(svr.is_valid());
  13495. svr.Get("/test", [](const Request &, Response &res) {
  13496. res.set_content("ok", "text/plain");
  13497. });
  13498. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13499. auto se = detail::scope_exit([&] {
  13500. svr.stop();
  13501. t.join();
  13502. });
  13503. svr.wait_until_ready();
  13504. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13505. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13506. // so we only check that the request fails, not whether the callback was
  13507. // called.
  13508. SSLClient cli(HOST, PORT);
  13509. cli.enable_server_certificate_verification(true);
  13510. cli.set_connection_timeout(30);
  13511. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13512. EXPECT_NE(session, nullptr);
  13513. return SSLVerifierResponse::NoDecisionMade;
  13514. });
  13515. auto res = cli.Get("/test");
  13516. EXPECT_FALSE(res);
  13517. }
  13518. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13519. // Test SSL server using PemMemory constructor with client CA certificates
  13520. // Read PEM files
  13521. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13522. read_file(SERVER_CERT_FILE, server_cert_pem);
  13523. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13524. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13525. // Create SSLServer with PemMemory constructor including client CA
  13526. SSLServer::PemMemory server_pem = {
  13527. server_cert_pem.c_str(),
  13528. server_cert_pem.size(),
  13529. server_key_pem.c_str(),
  13530. server_key_pem.size(),
  13531. client_ca_pem.c_str(),
  13532. client_ca_pem.size(),
  13533. nullptr // no password for server key
  13534. };
  13535. SSLServer svr(server_pem);
  13536. ASSERT_TRUE(svr.is_valid());
  13537. // No SSL error should be recorded for valid setup
  13538. EXPECT_EQ(0, svr.ssl_last_error());
  13539. // Set up server endpoints
  13540. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13541. res.set_content("ok", "text/plain");
  13542. });
  13543. // Start server in a thread
  13544. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13545. svr.wait_until_ready();
  13546. // Connect with client certificate (using constructor with paths)
  13547. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13548. cli.enable_server_certificate_verification(false);
  13549. auto res = cli.Get("/test-pem-ca");
  13550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13551. EXPECT_EQ(200, res->status);
  13552. EXPECT_EQ("ok", res->body);
  13553. svr.stop();
  13554. server_thread.join();
  13555. }
  13556. #endif
  13557. #ifdef _WIN32
  13558. TEST(CleanupTest, WSACleanup) {
  13559. int ret = WSACleanup();
  13560. ASSERT_EQ(0, ret);
  13561. }
  13562. #endif
  13563. #ifndef CPPHTTPLIB_SSL_ENABLED
  13564. TEST(NoSSLSupport, SimpleInterface) {
  13565. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13566. }
  13567. #endif
  13568. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13569. TEST(InvalidScheme, SimpleInterface) {
  13570. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13571. }
  13572. #endif
  13573. TEST(NoScheme, SimpleInterface) {
  13574. Client cli("yahoo.com:80");
  13575. ASSERT_TRUE(cli.is_valid());
  13576. }
  13577. TEST(SendAPI, SimpleInterface_Online) {
  13578. Client cli("http://yahoo.com");
  13579. Request req;
  13580. req.method = "GET";
  13581. req.path = "/";
  13582. auto res = cli.send(req);
  13583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13584. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13585. }
  13586. TEST(SendAPI, WithParamsInRequest) {
  13587. Server svr;
  13588. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13589. EXPECT_TRUE(req.has_param("test"));
  13590. EXPECT_EQ("test_value", req.get_param_value("test"));
  13591. });
  13592. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13593. auto se = detail::scope_exit([&] {
  13594. svr.stop();
  13595. t.join();
  13596. ASSERT_FALSE(svr.is_running());
  13597. });
  13598. svr.wait_until_ready();
  13599. Client cli(HOST, PORT);
  13600. {
  13601. Request req;
  13602. req.method = "GET";
  13603. req.path = "/";
  13604. req.params.emplace("test", "test_value");
  13605. auto res = cli.send(req);
  13606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13607. }
  13608. {
  13609. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13611. }
  13612. }
  13613. TEST(ClientImplMethods, GetSocketTest) {
  13614. httplib::Server svr;
  13615. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13616. res.status = StatusCode::OK_200;
  13617. });
  13618. auto port = svr.bind_to_any_port("127.0.0.1");
  13619. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13620. auto se = detail::scope_exit([&] {
  13621. svr.stop();
  13622. thread.join();
  13623. ASSERT_FALSE(svr.is_running());
  13624. });
  13625. svr.wait_until_ready();
  13626. {
  13627. httplib::Client cli("127.0.0.1", port);
  13628. cli.set_keep_alive(true);
  13629. // Use the behavior of cpp-httplib of opening the connection
  13630. // only when the first request happens. If that changes,
  13631. // this test would be obsolete.
  13632. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13633. // This also implicitly tests the server. But other tests would fail much
  13634. // earlier than this one to be considered.
  13635. auto res = cli.Get("/");
  13636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13637. EXPECT_EQ(StatusCode::OK_200, res->status);
  13638. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13639. }
  13640. }
  13641. #ifdef CPPHTTPLIB_SSL_ENABLED
  13642. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13643. Client cli("http://yahoo.com");
  13644. auto res = cli.Get("/");
  13645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13646. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13647. cli.set_follow_location(true);
  13648. res = cli.Get("/");
  13649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13650. EXPECT_EQ(StatusCode::OK_200, res->status);
  13651. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13652. }
  13653. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13654. Client cli("https://yahoo.com");
  13655. auto res = cli.Get("/");
  13656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13657. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13658. cli.set_follow_location(true);
  13659. res = cli.Get("/");
  13660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13661. EXPECT_EQ(StatusCode::OK_200, res->status);
  13662. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13663. }
  13664. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13665. Client cli("https://yahoo.com");
  13666. auto res = cli.Get("/");
  13667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13668. ASSERT_FALSE(!res);
  13669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13670. ASSERT_FALSE(res == nullptr);
  13671. ASSERT_TRUE(res != nullptr);
  13672. EXPECT_EQ(Error::Success, res.error());
  13673. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13674. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13675. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13676. cli.set_follow_location(true);
  13677. res = cli.Get("/");
  13678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13679. EXPECT_EQ(Error::Success, res.error());
  13680. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13681. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13682. EXPECT_EQ(StatusCode::OK_200, res->status);
  13683. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13684. }
  13685. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13686. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13687. Client cli("https://cdnjs.cloudflare.com");
  13688. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13689. Headers{{"Accept-Encoding", "br"}});
  13690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13691. EXPECT_EQ(StatusCode::OK_200, res->status);
  13692. EXPECT_EQ(287630U, res->body.size());
  13693. EXPECT_EQ("application/javascript; charset=utf-8",
  13694. res->get_header_value("Content-Type"));
  13695. }
  13696. #endif
  13697. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13698. #undef REDIR_HOST // Silence compiler warning
  13699. #define REDIR_HOST "https://httpbingo.org"
  13700. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13701. Client cli(REDIR_HOST);
  13702. cli.set_follow_location(true);
  13703. auto res =
  13704. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13706. EXPECT_EQ(StatusCode::OK_200, res->status);
  13707. }
  13708. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13709. Client cli(REDIR_HOST);
  13710. cli.set_follow_location(true);
  13711. Params params;
  13712. params.emplace("url", "http://example.com");
  13713. params.emplace("status_code", "302");
  13714. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13716. EXPECT_EQ(StatusCode::OK_200, res->status);
  13717. }
  13718. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13719. Client cli(REDIR_HOST);
  13720. cli.set_follow_location(true);
  13721. Params params;
  13722. params.emplace("url", "http://example.com");
  13723. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13725. EXPECT_EQ(StatusCode::OK_200, res->status);
  13726. }
  13727. TEST(HttpToHttpsRedirectTest, CertFile) {
  13728. auto ssl_port = PORT + 1;
  13729. Server svr;
  13730. ASSERT_TRUE(svr.is_valid());
  13731. svr.Get("/index", [&](const Request &, Response &res) {
  13732. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13733. "/index");
  13734. svr.stop();
  13735. });
  13736. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13737. ASSERT_TRUE(ssl_svr.is_valid());
  13738. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13739. res.set_content("test", "text/plain");
  13740. ssl_svr.stop();
  13741. });
  13742. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13743. thread t2 =
  13744. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13745. auto se = detail::scope_exit([&] {
  13746. t2.join();
  13747. t.join();
  13748. ASSERT_FALSE(svr.is_running());
  13749. });
  13750. svr.wait_until_ready();
  13751. ssl_svr.wait_until_ready();
  13752. Client cli("127.0.0.1", PORT);
  13753. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13754. cli.enable_server_certificate_verification(true);
  13755. cli.set_follow_location(true);
  13756. cli.set_connection_timeout(30);
  13757. auto res = cli.Get("/index");
  13758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13759. ASSERT_EQ(StatusCode::OK_200, res->status);
  13760. }
  13761. TEST(SSLClientRedirectTest, CertFile) {
  13762. auto ssl_port = PORT + 1;
  13763. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13764. ASSERT_TRUE(ssl_svr1.is_valid());
  13765. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13766. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13767. "/index");
  13768. ssl_svr1.stop();
  13769. });
  13770. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13771. ASSERT_TRUE(ssl_svr2.is_valid());
  13772. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13773. res.set_content("test", "text/plain");
  13774. ssl_svr2.stop();
  13775. });
  13776. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13777. thread t2 =
  13778. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13779. auto se = detail::scope_exit([&] {
  13780. t2.join();
  13781. t.join();
  13782. ASSERT_FALSE(ssl_svr1.is_running());
  13783. });
  13784. ssl_svr1.wait_until_ready();
  13785. ssl_svr2.wait_until_ready();
  13786. SSLClient cli("127.0.0.1", PORT);
  13787. std::string cert;
  13788. read_file(SERVER_CERT2_FILE, cert);
  13789. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13790. cli.enable_server_certificate_verification(true);
  13791. cli.set_follow_location(true);
  13792. cli.set_connection_timeout(30);
  13793. auto res = cli.Get("/index");
  13794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13795. ASSERT_EQ(StatusCode::OK_200, res->status);
  13796. }
  13797. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  13798. // another port, so the client follows it with a new client.
  13799. static Result GetThroughTlsRedirectToDifferentPort(
  13800. const std::function<void(SSLClient &)> &setup,
  13801. const char *target_cert = SERVER_CERT2_FILE) {
  13802. auto ssl_port = PORT + 1;
  13803. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13804. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13805. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13806. "/index");
  13807. });
  13808. SSLServer ssl_svr2(target_cert, SERVER_PRIVATE_KEY_FILE);
  13809. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13810. res.set_content("test", "text/plain");
  13811. });
  13812. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  13813. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  13814. auto se = detail::scope_exit([&] {
  13815. ssl_svr2.stop();
  13816. ssl_svr1.stop();
  13817. t2.join();
  13818. t.join();
  13819. });
  13820. ssl_svr1.wait_until_ready();
  13821. ssl_svr2.wait_until_ready();
  13822. SSLClient cli("127.0.0.1", PORT);
  13823. cli.set_follow_location(true);
  13824. cli.set_connection_timeout(30);
  13825. setup(cli);
  13826. return cli.Get("/index");
  13827. }
  13828. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  13829. auto calls = 0;
  13830. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  13831. cli.enable_server_certificate_verification(false);
  13832. // Accept the first server only.
  13833. cli.set_session_verifier([&](tls::session_t) {
  13834. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  13835. : SSLVerifierResponse::CertificateRejected;
  13836. });
  13837. });
  13838. EXPECT_FALSE(res);
  13839. EXPECT_EQ(2, calls);
  13840. }
  13841. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  13842. std::string pinned;
  13843. auto res = GetThroughTlsRedirectToDifferentPort(
  13844. [&](SSLClient &cli) {
  13845. cli.enable_server_certificate_verification(false);
  13846. // Pin the first certificate seen.
  13847. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  13848. if (pinned.empty()) { pinned = ctx.serial(); }
  13849. return ctx.serial() == pinned;
  13850. });
  13851. },
  13852. // A certificate other than the first server's.
  13853. SERVER_CERT_FILE);
  13854. EXPECT_FALSE(res);
  13855. EXPECT_FALSE(pinned.empty());
  13856. }
  13857. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  13858. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  13859. std::string cert;
  13860. read_file(SERVER_CERT2_FILE, cert);
  13861. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13862. });
  13863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13864. EXPECT_EQ(StatusCode::OK_200, res->status);
  13865. }
  13866. #endif
  13867. #ifdef CPPHTTPLIB_SSL_ENABLED
  13868. // Test that set_ca_cert_store() skips system certs (consistent with
  13869. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13870. // should be trusted - system certs should NOT be loaded.
  13871. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  13872. // Load a specific cert that is NOT a system CA cert
  13873. std::string cert;
  13874. read_file(SERVER_CERT2_FILE, cert);
  13875. SSLClient cli("google.com");
  13876. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13877. cli.enable_server_certificate_verification(true);
  13878. // This should FAIL because:
  13879. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  13880. // 2. System certs should NOT be loaded when custom store is set
  13881. // If system certs WERE loaded, this would succeed
  13882. auto res = cli.Get("/");
  13883. ASSERT_FALSE(res);
  13884. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13885. }
  13886. // Same as above, but through the native store handle path. Regression test:
  13887. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  13888. // merged system certs into the user-provided store.
  13889. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  13890. std::string cert;
  13891. read_file(SERVER_CERT2_FILE, cert);
  13892. SSLClient cli("google.com");
  13893. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13894. cli.enable_server_certificate_verification(true);
  13895. auto res = cli.Get("/");
  13896. ASSERT_FALSE(res);
  13897. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13898. }
  13899. // A custom store set via the native handle must still verify a server whose
  13900. // cert it does contain.
  13901. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  13902. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13903. ASSERT_TRUE(svr.is_valid());
  13904. svr.Get("/test", [&](const Request &, Response &res) {
  13905. res.set_content("test", "text/plain");
  13906. });
  13907. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13908. auto se = detail::scope_exit([&] {
  13909. svr.stop();
  13910. t.join();
  13911. ASSERT_FALSE(svr.is_running());
  13912. });
  13913. svr.wait_until_ready();
  13914. SSLClient cli("127.0.0.1", PORT);
  13915. std::string cert;
  13916. read_file(SERVER_CERT2_FILE, cert);
  13917. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13918. cli.enable_server_certificate_verification(true);
  13919. cli.set_connection_timeout(30);
  13920. auto res = cli.Get("/test");
  13921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13922. ASSERT_EQ(StatusCode::OK_200, res->status);
  13923. }
  13924. // CA certs loaded through the universal Client must be transferred to the
  13925. // client created internally for following an HTTPS redirect. Regression test:
  13926. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  13927. // the CA data for redirect transfer.
  13928. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  13929. auto ssl_port = PORT + 1;
  13930. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13931. ASSERT_TRUE(ssl_svr1.is_valid());
  13932. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13933. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13934. "/index");
  13935. });
  13936. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13937. ASSERT_TRUE(ssl_svr2.is_valid());
  13938. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13939. res.set_content("test", "text/plain");
  13940. });
  13941. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13942. thread t2 =
  13943. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13944. auto se = detail::scope_exit([&] {
  13945. ssl_svr2.stop();
  13946. ssl_svr1.stop();
  13947. t2.join();
  13948. t.join();
  13949. ASSERT_FALSE(ssl_svr1.is_running());
  13950. });
  13951. ssl_svr1.wait_until_ready();
  13952. ssl_svr2.wait_until_ready();
  13953. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13954. std::string cert;
  13955. read_file(SERVER_CERT2_FILE, cert);
  13956. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13957. cli.enable_server_certificate_verification(true);
  13958. cli.set_follow_location(true);
  13959. cli.set_connection_timeout(30);
  13960. auto res = cli.Get("/index");
  13961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13962. ASSERT_EQ(StatusCode::OK_200, res->status);
  13963. }
  13964. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  13965. // so a host signed by a system CA verifies even though a custom CA is set
  13966. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  13967. std::string cert;
  13968. read_file(SERVER_CERT2_FILE, cert);
  13969. SSLClient cli("google.com");
  13970. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13971. cli.enable_system_ca(true);
  13972. cli.enable_server_certificate_verification(true);
  13973. auto res = cli.Get("/");
  13974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13975. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13976. }
  13977. // The custom CA remains effective when combined with the system CA
  13978. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  13979. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13980. ASSERT_TRUE(svr.is_valid());
  13981. svr.Get("/test", [&](const Request &, Response &res) {
  13982. res.set_content("test", "text/plain");
  13983. });
  13984. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13985. auto se = detail::scope_exit([&] {
  13986. svr.stop();
  13987. t.join();
  13988. ASSERT_FALSE(svr.is_running());
  13989. });
  13990. svr.wait_until_ready();
  13991. SSLClient cli("127.0.0.1", PORT);
  13992. std::string cert;
  13993. read_file(SERVER_CERT2_FILE, cert);
  13994. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13995. cli.enable_system_ca(true);
  13996. cli.enable_server_certificate_verification(true);
  13997. cli.set_connection_timeout(30);
  13998. auto res = cli.Get("/test");
  13999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14000. ASSERT_EQ(StatusCode::OK_200, res->status);
  14001. }
  14002. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14003. // skip chain verification entirely (only the certificate identity was
  14004. // checked), so a server presenting an untrusted certificate with a matching
  14005. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14006. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14007. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14008. ASSERT_TRUE(svr.is_valid());
  14009. svr.Get("/test", [&](const Request &, Response &res) {
  14010. res.set_content("test", "text/plain");
  14011. });
  14012. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14013. auto se = detail::scope_exit([&] {
  14014. svr.stop();
  14015. t.join();
  14016. ASSERT_FALSE(svr.is_running());
  14017. });
  14018. svr.wait_until_ready();
  14019. SSLClient cli("127.0.0.1", PORT);
  14020. std::string cert;
  14021. // A trusted CA that did not sign the server certificate. The server cert
  14022. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14023. // this connection.
  14024. read_file(CLIENT_CA_CERT_FILE, cert);
  14025. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14026. cli.enable_server_certificate_verification(true);
  14027. cli.set_connection_timeout(30);
  14028. auto res = cli.Get("/test");
  14029. ASSERT_FALSE(res);
  14030. }
  14031. // enable_system_ca(false) prevents system CA loading entirely
  14032. TEST(SSLClientTest, DisableSystemCa_Online) {
  14033. SSLClient cli("google.com");
  14034. cli.enable_system_ca(false);
  14035. cli.enable_server_certificate_verification(true);
  14036. auto res = cli.Get("/");
  14037. ASSERT_FALSE(res);
  14038. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14039. // itself when the CA chain is empty
  14040. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14041. res.error() == Error::SSLConnection);
  14042. }
  14043. // The universal Client forwards enable_system_ca()
  14044. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14045. std::string cert;
  14046. read_file(SERVER_CERT2_FILE, cert);
  14047. Client cli("https://google.com");
  14048. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14049. cli.enable_system_ca(true);
  14050. cli.enable_server_certificate_verification(true);
  14051. auto res = cli.Get("/");
  14052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14053. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14054. }
  14055. // The system CA policy must carry over to the client created internally for
  14056. // following a cross-host HTTPS redirect
  14057. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14058. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14059. ASSERT_TRUE(svr.is_valid());
  14060. svr.Get("/index", [&](const Request &, Response &res) {
  14061. res.set_redirect("https://www.google.com/");
  14062. });
  14063. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14064. auto se = detail::scope_exit([&] {
  14065. svr.stop();
  14066. t.join();
  14067. ASSERT_FALSE(svr.is_running());
  14068. });
  14069. svr.wait_until_ready();
  14070. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14071. std::string cert;
  14072. read_file(SERVER_CERT2_FILE, cert);
  14073. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14074. cli.enable_system_ca(true);
  14075. cli.enable_server_certificate_verification(true);
  14076. cli.set_follow_location(true);
  14077. cli.set_connection_timeout(30);
  14078. // Receiving any response proves the redirect client completed the TLS
  14079. // handshake with a system-CA-signed host
  14080. auto res = cli.Get("/index");
  14081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14082. }
  14083. TEST(MultipartFormDataTest, LargeData) {
  14084. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14085. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14086. const ContentReader &content_reader) {
  14087. if (req.is_multipart_form_data()) {
  14088. std::vector<FormData> items;
  14089. content_reader(
  14090. [&](const FormData &file) {
  14091. items.push_back(file);
  14092. return true;
  14093. },
  14094. [&](const char *data, size_t data_length) {
  14095. items.back().content.append(data, data_length);
  14096. return true;
  14097. });
  14098. EXPECT_TRUE(std::string(items[0].name) == "document");
  14099. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14100. EXPECT_TRUE(items[0].filename == "2MB_data");
  14101. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14102. EXPECT_TRUE(items[1].name == "hello");
  14103. EXPECT_TRUE(items[1].content == "world");
  14104. EXPECT_TRUE(items[1].filename == "");
  14105. EXPECT_TRUE(items[1].content_type == "");
  14106. } else {
  14107. std::string body;
  14108. content_reader([&](const char *data, size_t data_length) {
  14109. body.append(data, data_length);
  14110. return true;
  14111. });
  14112. }
  14113. });
  14114. auto port = svr.bind_to_any_port(HOST);
  14115. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14116. auto se = detail::scope_exit([&] {
  14117. svr.stop();
  14118. t.join();
  14119. ASSERT_FALSE(svr.is_running());
  14120. });
  14121. svr.wait_until_ready();
  14122. {
  14123. std::string data(1024 * 1024 * 2, '.');
  14124. std::stringstream buffer;
  14125. buffer << data;
  14126. SSLClient cli(HOST, port);
  14127. cli.enable_server_certificate_verification(false);
  14128. UploadFormDataItems items{
  14129. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14130. {"hello", "world", "", ""},
  14131. };
  14132. auto res = cli.Post("/post", items);
  14133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14134. ASSERT_EQ(StatusCode::OK_200, res->status);
  14135. }
  14136. }
  14137. TEST(MultipartFormDataTest, DataProviderItems) {
  14138. std::random_device seed_gen;
  14139. std::mt19937 random(seed_gen());
  14140. std::string rand1;
  14141. rand1.resize(1000);
  14142. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14143. std::string rand2;
  14144. rand2.resize(3000);
  14145. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14146. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14147. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14148. const ContentReader &content_reader) {
  14149. ASSERT_FALSE(req.is_multipart_form_data());
  14150. std::string body;
  14151. content_reader([&](const char *data, size_t data_length) {
  14152. body.append(data, data_length);
  14153. return true;
  14154. });
  14155. EXPECT_EQ(body, "");
  14156. });
  14157. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14158. const ContentReader &content_reader) {
  14159. ASSERT_TRUE(req.is_multipart_form_data());
  14160. std::vector<FormData> items;
  14161. content_reader(
  14162. [&](const FormData &file) {
  14163. items.push_back(file);
  14164. return true;
  14165. },
  14166. [&](const char *data, size_t data_length) {
  14167. items.back().content.append(data, data_length);
  14168. return true;
  14169. });
  14170. ASSERT_TRUE(items.size() == 2);
  14171. EXPECT_EQ(std::string(items[0].name), "name1");
  14172. EXPECT_EQ(items[0].content, "Testing123");
  14173. EXPECT_EQ(items[0].filename, "filename1");
  14174. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14175. EXPECT_EQ(items[1].name, "name2");
  14176. EXPECT_EQ(items[1].content, "Testing456");
  14177. EXPECT_EQ(items[1].filename, "");
  14178. EXPECT_EQ(items[1].content_type, "");
  14179. });
  14180. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14181. const ContentReader &content_reader) {
  14182. ASSERT_TRUE(req.is_multipart_form_data());
  14183. std::vector<FormData> items;
  14184. content_reader(
  14185. [&](const FormData &file) {
  14186. items.push_back(file);
  14187. return true;
  14188. },
  14189. [&](const char *data, size_t data_length) {
  14190. items.back().content.append(data, data_length);
  14191. return true;
  14192. });
  14193. ASSERT_TRUE(items.size() == 2);
  14194. EXPECT_EQ(items[0].name, "name3");
  14195. EXPECT_EQ(items[0].content, rand1);
  14196. EXPECT_EQ(items[0].filename, "filename3");
  14197. EXPECT_EQ(items[0].content_type, "");
  14198. EXPECT_EQ(items[1].name, "name4");
  14199. EXPECT_EQ(items[1].content, rand2);
  14200. EXPECT_EQ(items[1].filename, "filename4");
  14201. EXPECT_EQ(items[1].content_type, "");
  14202. });
  14203. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14204. const ContentReader &content_reader) {
  14205. ASSERT_TRUE(req.is_multipart_form_data());
  14206. std::vector<FormData> items;
  14207. content_reader(
  14208. [&](const FormData &file) {
  14209. items.push_back(file);
  14210. return true;
  14211. },
  14212. [&](const char *data, size_t data_length) {
  14213. items.back().content.append(data, data_length);
  14214. return true;
  14215. });
  14216. ASSERT_TRUE(items.size() == 4);
  14217. EXPECT_EQ(std::string(items[0].name), "name1");
  14218. EXPECT_EQ(items[0].content, "Testing123");
  14219. EXPECT_EQ(items[0].filename, "filename1");
  14220. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14221. EXPECT_EQ(items[1].name, "name2");
  14222. EXPECT_EQ(items[1].content, "Testing456");
  14223. EXPECT_EQ(items[1].filename, "");
  14224. EXPECT_EQ(items[1].content_type, "");
  14225. EXPECT_EQ(items[2].name, "name3");
  14226. EXPECT_EQ(items[2].content, rand1);
  14227. EXPECT_EQ(items[2].filename, "filename3");
  14228. EXPECT_EQ(items[2].content_type, "");
  14229. EXPECT_EQ(items[3].name, "name4");
  14230. EXPECT_EQ(items[3].content, rand2);
  14231. EXPECT_EQ(items[3].filename, "filename4");
  14232. EXPECT_EQ(items[3].content_type, "");
  14233. });
  14234. auto port = svr.bind_to_any_port("localhost");
  14235. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14236. auto se = detail::scope_exit([&] {
  14237. svr.stop();
  14238. t.join();
  14239. ASSERT_FALSE(svr.is_running());
  14240. });
  14241. svr.wait_until_ready();
  14242. {
  14243. SSLClient cli("localhost", port);
  14244. cli.enable_server_certificate_verification(false);
  14245. UploadFormDataItems items{
  14246. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14247. {"name2", "Testing456", "", ""}, // not a file
  14248. };
  14249. {
  14250. auto res = cli.Post("/post-none", {}, {}, {});
  14251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14252. ASSERT_EQ(StatusCode::OK_200, res->status);
  14253. }
  14254. FormDataProviderItems providers;
  14255. {
  14256. auto res =
  14257. cli.Post("/post-items", {}, items, providers); // empty providers
  14258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14259. ASSERT_EQ(StatusCode::OK_200, res->status);
  14260. }
  14261. providers.push_back({"name3",
  14262. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14263. // test the offset is given correctly at each step
  14264. if (!offset)
  14265. sink.os.write(rand1.data(), 30);
  14266. else if (offset == 30)
  14267. sink.os.write(rand1.data() + 30, 300);
  14268. else if (offset == 330)
  14269. sink.os.write(rand1.data() + 330, 670);
  14270. else if (offset == rand1.size())
  14271. sink.done();
  14272. return true;
  14273. },
  14274. "filename3",
  14275. {}});
  14276. providers.push_back({"name4",
  14277. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14278. // test the offset is given correctly at each step
  14279. if (!offset)
  14280. sink.os.write(rand2.data(), 2000);
  14281. else if (offset == 2000)
  14282. sink.os.write(rand2.data() + 2000, 1);
  14283. else if (offset == 2001)
  14284. sink.os.write(rand2.data() + 2001, 999);
  14285. else if (offset == rand2.size())
  14286. sink.done();
  14287. return true;
  14288. },
  14289. "filename4",
  14290. {}});
  14291. {
  14292. auto res = cli.Post("/post-providers", {}, {}, providers);
  14293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14294. ASSERT_EQ(StatusCode::OK_200, res->status);
  14295. }
  14296. {
  14297. auto res = cli.Post("/post-both", {}, items, providers);
  14298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14299. ASSERT_EQ(StatusCode::OK_200, res->status);
  14300. }
  14301. }
  14302. }
  14303. TEST(MultipartFormDataTest, BadHeader) {
  14304. Server svr;
  14305. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14306. res.set_content("ok", "text/plain");
  14307. });
  14308. thread t = thread([&] { svr.listen(HOST, PORT); });
  14309. auto se = detail::scope_exit([&] {
  14310. svr.stop();
  14311. t.join();
  14312. ASSERT_FALSE(svr.is_running());
  14313. });
  14314. svr.wait_until_ready();
  14315. const std::string body =
  14316. "This is the preamble. It is to be ignored, though it\r\n"
  14317. "is a handy place for composition agents to include an\r\n"
  14318. "explanatory note to non-MIME conformant readers.\r\n"
  14319. "\r\n"
  14320. "\r\n"
  14321. "--simple boundary\r\n"
  14322. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14323. ": BAD...\r\n"
  14324. "\r\n"
  14325. "value1\r\n"
  14326. "--simple boundary\r\n"
  14327. "Content-Disposition: form-data; name=\"field2\"; "
  14328. "filename=\"example.txt\"\r\n"
  14329. "\r\n"
  14330. "value2\r\n"
  14331. "--simple boundary--\r\n"
  14332. "This is the epilogue. It is also to be ignored.\r\n";
  14333. std::string content_type =
  14334. R"(multipart/form-data; boundary="simple boundary")";
  14335. Client cli(HOST, PORT);
  14336. auto res = cli.Post("/post", body, content_type.c_str());
  14337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14338. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14339. }
  14340. TEST(MultipartFormDataTest, WithPreamble) {
  14341. Server svr;
  14342. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14343. res.set_content("ok", "text/plain");
  14344. });
  14345. thread t = thread([&] { svr.listen(HOST, PORT); });
  14346. auto se = detail::scope_exit([&] {
  14347. svr.stop();
  14348. t.join();
  14349. ASSERT_FALSE(svr.is_running());
  14350. });
  14351. svr.wait_until_ready();
  14352. const std::string body =
  14353. "This is the preamble. It is to be ignored, though it\r\n"
  14354. "is a handy place for composition agents to include an\r\n"
  14355. "explanatory note to non-MIME conformant readers.\r\n"
  14356. "\r\n"
  14357. "\r\n"
  14358. "--simple boundary\r\n"
  14359. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14360. "\r\n"
  14361. "value1\r\n"
  14362. "--simple boundary\r\n"
  14363. "Content-Disposition: form-data; name=\"field2\"; "
  14364. "filename=\"example.txt\"\r\n"
  14365. "\r\n"
  14366. "value2\r\n"
  14367. "--simple boundary--\r\n"
  14368. "This is the epilogue. It is also to be ignored.\r\n";
  14369. std::string content_type =
  14370. R"(multipart/form-data; boundary="simple boundary")";
  14371. Client cli(HOST, PORT);
  14372. auto res = cli.Post("/post", body, content_type.c_str());
  14373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14374. EXPECT_EQ(StatusCode::OK_200, res->status);
  14375. }
  14376. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14377. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14378. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14379. const ContentReader &content_reader) {
  14380. if (req.is_multipart_form_data()) {
  14381. std::vector<FormData> items;
  14382. content_reader(
  14383. [&](const FormData &file) {
  14384. items.push_back(file);
  14385. return true;
  14386. },
  14387. [&](const char *data, size_t data_length) {
  14388. items.back().content.append(data, data_length);
  14389. return true;
  14390. });
  14391. EXPECT_TRUE(std::string(items[0].name) == "document");
  14392. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14393. EXPECT_TRUE(items[0].filename == "2MB_data");
  14394. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14395. EXPECT_TRUE(items[1].name == "hello");
  14396. EXPECT_TRUE(items[1].content == "world");
  14397. EXPECT_TRUE(items[1].filename == "");
  14398. EXPECT_TRUE(items[1].content_type == "");
  14399. } else {
  14400. std::string body;
  14401. content_reader([&](const char *data, size_t data_length) {
  14402. body.append(data, data_length);
  14403. return true;
  14404. });
  14405. }
  14406. });
  14407. auto port = svr.bind_to_any_port("localhost");
  14408. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14409. auto se = detail::scope_exit([&] {
  14410. svr.stop();
  14411. t.join();
  14412. ASSERT_FALSE(svr.is_running());
  14413. });
  14414. svr.wait_until_ready();
  14415. {
  14416. std::string data(1024 * 1024 * 2, '.');
  14417. std::stringstream buffer;
  14418. buffer << data;
  14419. SSLClient cli("localhost", port);
  14420. cli.enable_server_certificate_verification(false);
  14421. UploadFormDataItems items{
  14422. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14423. {"hello", "world", "", ""},
  14424. };
  14425. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14427. ASSERT_EQ(StatusCode::OK_200, res->status);
  14428. }
  14429. }
  14430. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14431. std::string data(1024 * 1024 * 2, '&');
  14432. std::stringstream buffer;
  14433. buffer << data;
  14434. Client cli("https://localhost:8080");
  14435. UploadFormDataItems items{
  14436. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14437. {"hello", "world", "", ""},
  14438. };
  14439. for (const char &c : " \t\r\n") {
  14440. auto res =
  14441. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14442. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14443. ASSERT_FALSE(res);
  14444. }
  14445. }
  14446. TEST(MultipartFormDataTest, PutFormData) {
  14447. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14448. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14449. const ContentReader &content_reader) {
  14450. if (req.is_multipart_form_data()) {
  14451. std::vector<FormData> items;
  14452. content_reader(
  14453. [&](const FormData &file) {
  14454. items.push_back(file);
  14455. return true;
  14456. },
  14457. [&](const char *data, size_t data_length) {
  14458. items.back().content.append(data, data_length);
  14459. return true;
  14460. });
  14461. EXPECT_TRUE(std::string(items[0].name) == "document");
  14462. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14463. EXPECT_TRUE(items[0].filename == "2MB_data");
  14464. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14465. EXPECT_TRUE(items[1].name == "hello");
  14466. EXPECT_TRUE(items[1].content == "world");
  14467. EXPECT_TRUE(items[1].filename == "");
  14468. EXPECT_TRUE(items[1].content_type == "");
  14469. } else {
  14470. std::string body;
  14471. content_reader([&](const char *data, size_t data_length) {
  14472. body.append(data, data_length);
  14473. return true;
  14474. });
  14475. }
  14476. });
  14477. auto port = svr.bind_to_any_port("localhost");
  14478. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14479. auto se = detail::scope_exit([&] {
  14480. svr.stop();
  14481. t.join();
  14482. ASSERT_FALSE(svr.is_running());
  14483. });
  14484. svr.wait_until_ready();
  14485. {
  14486. std::string data(1024 * 1024 * 2, '&');
  14487. std::stringstream buffer;
  14488. buffer << data;
  14489. SSLClient cli("localhost", port);
  14490. cli.enable_server_certificate_verification(false);
  14491. UploadFormDataItems items{
  14492. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14493. {"hello", "world", "", ""},
  14494. };
  14495. auto res = cli.Put("/put", items);
  14496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14497. ASSERT_EQ(StatusCode::OK_200, res->status);
  14498. }
  14499. }
  14500. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14501. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14502. svr.Put("/put_customboundary",
  14503. [&](const Request &req, const Response & /*res*/,
  14504. const ContentReader &content_reader) {
  14505. if (req.is_multipart_form_data()) {
  14506. std::vector<FormData> items;
  14507. content_reader(
  14508. [&](const FormData &file) {
  14509. items.push_back(file);
  14510. return true;
  14511. },
  14512. [&](const char *data, size_t data_length) {
  14513. items.back().content.append(data, data_length);
  14514. return true;
  14515. });
  14516. EXPECT_TRUE(std::string(items[0].name) == "document");
  14517. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14518. EXPECT_TRUE(items[0].filename == "2MB_data");
  14519. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14520. EXPECT_TRUE(items[1].name == "hello");
  14521. EXPECT_TRUE(items[1].content == "world");
  14522. EXPECT_TRUE(items[1].filename == "");
  14523. EXPECT_TRUE(items[1].content_type == "");
  14524. } else {
  14525. std::string body;
  14526. content_reader([&](const char *data, size_t data_length) {
  14527. body.append(data, data_length);
  14528. return true;
  14529. });
  14530. }
  14531. });
  14532. auto port = svr.bind_to_any_port("localhost");
  14533. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14534. auto se = detail::scope_exit([&] {
  14535. svr.stop();
  14536. t.join();
  14537. ASSERT_FALSE(svr.is_running());
  14538. });
  14539. svr.wait_until_ready();
  14540. {
  14541. std::string data(1024 * 1024 * 2, '&');
  14542. std::stringstream buffer;
  14543. buffer << data;
  14544. SSLClient cli("localhost", port);
  14545. cli.enable_server_certificate_verification(false);
  14546. UploadFormDataItems items{
  14547. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14548. {"hello", "world", "", ""},
  14549. };
  14550. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14552. ASSERT_EQ(StatusCode::OK_200, res->status);
  14553. }
  14554. }
  14555. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14556. std::string data(1024 * 1024 * 2, '&');
  14557. std::stringstream buffer;
  14558. buffer << data;
  14559. Client cli("https://localhost:8080");
  14560. cli.enable_server_certificate_verification(false);
  14561. UploadFormDataItems items{
  14562. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14563. {"hello", "world", "", ""},
  14564. };
  14565. for (const char &c : " \t\r\n") {
  14566. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14567. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14568. ASSERT_FALSE(res);
  14569. }
  14570. }
  14571. TEST(MultipartFormDataTest, AlternateFilename) {
  14572. auto handled = false;
  14573. Server svr;
  14574. svr.Post("/test", [&](const Request &req, Response &res) {
  14575. ASSERT_EQ(2u, req.form.files.size());
  14576. ASSERT_EQ(1u, req.form.fields.size());
  14577. // Test files
  14578. const auto &file1 = req.form.get_file("file1");
  14579. ASSERT_EQ("file1", file1.name);
  14580. ASSERT_EQ("A.txt", file1.filename);
  14581. ASSERT_EQ("text/plain", file1.content_type);
  14582. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14583. const auto &file2 = req.form.get_file("file2");
  14584. ASSERT_EQ("file2", file2.name);
  14585. ASSERT_EQ("a.html", file2.filename);
  14586. ASSERT_EQ("text/html", file2.content_type);
  14587. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14588. file2.content);
  14589. // Test text field
  14590. const auto &text = req.form.get_field("text");
  14591. ASSERT_EQ("text default", text);
  14592. res.set_content("ok", "text/plain");
  14593. handled = true;
  14594. });
  14595. thread t = thread([&] { svr.listen(HOST, PORT); });
  14596. auto se = detail::scope_exit([&] {
  14597. svr.stop();
  14598. t.join();
  14599. ASSERT_FALSE(svr.is_running());
  14600. ASSERT_TRUE(handled);
  14601. });
  14602. svr.wait_until_ready();
  14603. auto req = "POST /test HTTP/1.1\r\n"
  14604. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14605. "Content-Length: 399\r\n"
  14606. "\r\n"
  14607. "----------\r\n"
  14608. "Content-Disposition: form-data; name=\"text\"\r\n"
  14609. "\r\n"
  14610. "text default\r\n"
  14611. "----------\r\n"
  14612. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14613. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14614. "Content-Type: text/plain\r\n"
  14615. "\r\n"
  14616. "Content of a.txt.\r\n"
  14617. "\r\n"
  14618. "----------\r\n"
  14619. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14620. "\"a.html\"\r\n"
  14621. "Content-Type: text/html\r\n"
  14622. "\r\n"
  14623. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14624. "\r\n"
  14625. "------------\r\n";
  14626. ASSERT_TRUE(send_request(1, req));
  14627. }
  14628. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14629. auto handled = false;
  14630. Server svr;
  14631. svr.Post("/test", [&](const Request &req, Response &res) {
  14632. // Case-insensitive "utf-8''" prefix with a long value
  14633. const auto &file = req.form.get_file("file1");
  14634. ASSERT_EQ("file1", file.name);
  14635. // 8000 chars exercises both the Content-Disposition parser and the
  14636. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  14637. // Prior to the fix, std::regex_match on this header would cause O(N)
  14638. // stack recursion in libstdc++, leading to SIGSEGV.
  14639. std::string expected_filename(8000, 'A');
  14640. ASSERT_EQ(expected_filename, file.filename);
  14641. res.set_content("ok", "text/plain");
  14642. handled = true;
  14643. });
  14644. thread t = thread([&] { svr.listen(HOST, PORT); });
  14645. auto se = detail::scope_exit([&] {
  14646. svr.stop();
  14647. t.join();
  14648. ASSERT_FALSE(svr.is_running());
  14649. ASSERT_TRUE(handled);
  14650. });
  14651. svr.wait_until_ready();
  14652. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14653. // Regression test for GHSA-qq6v-r583-3h69
  14654. std::string long_filename(8000, 'A');
  14655. std::string body = "----------\r\n"
  14656. "Content-Disposition: form-data; name=\"file1\"; "
  14657. "filename*=\"Utf-8''" +
  14658. long_filename +
  14659. "\"\r\n"
  14660. "\r\n"
  14661. "hello\r\n"
  14662. "------------\r\n";
  14663. auto req = "POST /test HTTP/1.1\r\n"
  14664. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14665. "Content-Length: " +
  14666. std::to_string(body.size()) + "\r\n\r\n" + body;
  14667. ASSERT_TRUE(send_request(1, req));
  14668. }
  14669. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14670. auto handled = false;
  14671. Server svr;
  14672. svr.Post("/test", [&](const Request &req, Response &) {
  14673. ASSERT_EQ(2u, req.form.fields.size());
  14674. const auto &text1 = req.form.get_field("text1");
  14675. ASSERT_EQ("text1", text1);
  14676. const auto &text2 = req.form.get_field("text2");
  14677. ASSERT_EQ("text2", text2);
  14678. handled = true;
  14679. });
  14680. thread t = thread([&] { svr.listen(HOST, PORT); });
  14681. auto se = detail::scope_exit([&] {
  14682. svr.stop();
  14683. t.join();
  14684. ASSERT_FALSE(svr.is_running());
  14685. ASSERT_TRUE(handled);
  14686. });
  14687. svr.wait_until_ready();
  14688. auto req = "POST /test HTTP/1.1\r\n"
  14689. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14690. "Content-Length: 146\r\n"
  14691. "\r\n----------\r\n"
  14692. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14693. "\r\n"
  14694. "text1"
  14695. "\r\n----------\r\n"
  14696. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14697. "\r\n"
  14698. "text2"
  14699. "\r\n------------";
  14700. std::string response;
  14701. ASSERT_TRUE(send_request(1, req, &response));
  14702. ASSERT_EQ("200", response.substr(9, 3));
  14703. }
  14704. TEST(MultipartFormDataTest, ContentLength) {
  14705. auto handled = false;
  14706. Server svr;
  14707. svr.Post("/test", [&](const Request &req, Response &) {
  14708. ASSERT_EQ(2u, req.form.fields.size());
  14709. const auto &text1 = req.form.get_field("text1");
  14710. ASSERT_EQ("text1", text1);
  14711. const auto &text2 = req.form.get_field("text2");
  14712. ASSERT_EQ("text2", text2);
  14713. handled = true;
  14714. });
  14715. thread t = thread([&] { svr.listen(HOST, PORT); });
  14716. auto se = detail::scope_exit([&] {
  14717. svr.stop();
  14718. t.join();
  14719. ASSERT_FALSE(svr.is_running());
  14720. ASSERT_TRUE(handled);
  14721. });
  14722. svr.wait_until_ready();
  14723. auto req = "POST /test HTTP/1.1\r\n"
  14724. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14725. "Content-Length: 167\r\n"
  14726. "\r\n----------\r\n"
  14727. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14728. "Content-Length: 5\r\n"
  14729. "\r\n"
  14730. "text1"
  14731. "\r\n----------\r\n"
  14732. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14733. "\r\n"
  14734. "text2"
  14735. "\r\n------------\r\n";
  14736. std::string response;
  14737. ASSERT_TRUE(send_request(1, req, &response));
  14738. ASSERT_EQ("200", response.substr(9, 3));
  14739. }
  14740. TEST(MultipartFormDataTest, AccessPartHeaders) {
  14741. auto handled = false;
  14742. Server svr;
  14743. svr.Post("/test", [&](const Request &req, Response &) {
  14744. ASSERT_EQ(2u, req.form.fields.size());
  14745. const auto &text1 = req.form.get_field("text1");
  14746. ASSERT_EQ("text1", text1);
  14747. // TODO: Add header access for text fields if needed
  14748. const auto &text2 = req.form.get_field("text2");
  14749. ASSERT_EQ("text2", text2);
  14750. // TODO: Header access for text fields needs to be implemented
  14751. // auto &headers = it->second.headers;
  14752. // ASSERT_EQ(3U, headers.size());
  14753. // auto custom_header = headers.find("x-whatever");
  14754. // ASSERT_TRUE(custom_header != headers.end());
  14755. // ASSERT_NE("customvalue", custom_header->second);
  14756. // ASSERT_EQ("CustomValue", custom_header->second);
  14757. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14758. handled = true;
  14759. });
  14760. thread t = thread([&] { svr.listen(HOST, PORT); });
  14761. auto se = detail::scope_exit([&] {
  14762. svr.stop();
  14763. t.join();
  14764. ASSERT_FALSE(svr.is_running());
  14765. ASSERT_TRUE(handled);
  14766. });
  14767. svr.wait_until_ready();
  14768. auto req = "POST /test HTTP/1.1\r\n"
  14769. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14770. "Content-Length: 232\r\n"
  14771. "\r\n----------\r\n"
  14772. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14773. "Content-Length: 5\r\n"
  14774. "X-Test: 1\r\n"
  14775. "\r\n"
  14776. "text1"
  14777. "\r\n----------\r\n"
  14778. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14779. "Content-Type: text/plain\r\n"
  14780. "X-Whatever: CustomValue\r\n"
  14781. "\r\n"
  14782. "text2"
  14783. "\r\n------------\r\n"
  14784. "That should be disregarded. Not even read";
  14785. std::string response;
  14786. ASSERT_TRUE(send_request(1, req, &response));
  14787. ASSERT_EQ("200", response.substr(9, 3));
  14788. }
  14789. TEST(MultipartFormDataTest, LargeHeader) {
  14790. auto handled = false;
  14791. Server svr;
  14792. svr.Post("/test", [&](const Request &req, Response &) {
  14793. ASSERT_EQ(1u, req.form.fields.size());
  14794. const auto &text = req.form.get_field("name1");
  14795. ASSERT_EQ("text1", text);
  14796. handled = true;
  14797. });
  14798. thread t = thread([&] { svr.listen(HOST, PORT); });
  14799. auto se = detail::scope_exit([&] {
  14800. svr.stop();
  14801. t.join();
  14802. ASSERT_FALSE(svr.is_running());
  14803. ASSERT_TRUE(handled);
  14804. });
  14805. svr.wait_until_ready();
  14806. auto boundary = std::string("cpp-httplib-multipart-data");
  14807. std::string content = "--" + boundary +
  14808. "\r\n"
  14809. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14810. "\r\n"
  14811. "text1\r\n"
  14812. "--" +
  14813. boundary + "--\r\n";
  14814. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14815. "Content-Type: multipart/form-data;boundary=" +
  14816. boundary +
  14817. "\r\n"
  14818. "Content-Length: " +
  14819. std::to_string(content.size()) +
  14820. "\r\n"
  14821. "Dummy-Header: ";
  14822. std::string header_suffix = "\r\n"
  14823. "\r\n";
  14824. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14825. size_t header_dummy_size =
  14826. read_buff_size -
  14827. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14828. auto header_dummy = std::string(header_dummy_size, '@');
  14829. auto req = header_prefix + header_dummy + header_suffix + content;
  14830. std::string response;
  14831. ASSERT_TRUE(send_request(1, req, &response));
  14832. ASSERT_EQ("200", response.substr(9, 3));
  14833. }
  14834. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14835. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14836. // (not chunked Transfer-Encoding) after the streaming refactor.
  14837. auto handled = false;
  14838. Server svr;
  14839. svr.Post("/upload", [&](const Request &req, Response &res) {
  14840. auto cl_it = req.headers.find("Content-Length");
  14841. EXPECT_TRUE(cl_it != req.headers.end());
  14842. auto te_it = req.headers.find("Transfer-Encoding");
  14843. EXPECT_TRUE(te_it == req.headers.end());
  14844. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  14845. res.set_content("ok", "text/plain");
  14846. handled = true;
  14847. });
  14848. auto port = svr.bind_to_any_port(HOST);
  14849. auto t = thread([&] { svr.listen_after_bind(); });
  14850. auto se = detail::scope_exit([&] {
  14851. svr.stop();
  14852. t.join();
  14853. ASSERT_FALSE(svr.is_running());
  14854. ASSERT_TRUE(handled);
  14855. });
  14856. svr.wait_until_ready();
  14857. UploadFormDataItems items = {
  14858. {"field1", "hello", "", "text/plain"},
  14859. {"file1", "world", "test.txt", "application/octet-stream"},
  14860. };
  14861. Client cli(HOST, port);
  14862. auto res = cli.Post("/upload", {}, items);
  14863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14864. EXPECT_EQ(StatusCode::OK_200, res->status);
  14865. }
  14866. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14867. // Verify that make_multipart_content_provider coalesces many small segments
  14868. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14869. constexpr size_t kItemCount = 1000;
  14870. UploadFormDataItems items;
  14871. items.reserve(kItemCount);
  14872. for (size_t i = 0; i < kItemCount; i++) {
  14873. items.push_back(
  14874. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14875. }
  14876. const std::string boundary = "----test-boundary";
  14877. auto content_length = detail::get_multipart_content_length(items, boundary);
  14878. auto provider = detail::make_multipart_content_provider(items, boundary);
  14879. // Drive the provider the same way write_content_with_progress does
  14880. size_t write_count = 0;
  14881. size_t total_bytes = 0;
  14882. DataSink sink;
  14883. size_t offset = 0;
  14884. sink.write = [&](const char *d, size_t l) -> bool {
  14885. (void)d;
  14886. write_count++;
  14887. total_bytes += l;
  14888. offset += l;
  14889. return true;
  14890. };
  14891. sink.is_writable = []() -> bool { return true; };
  14892. while (offset < content_length) {
  14893. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  14894. }
  14895. EXPECT_EQ(content_length, total_bytes);
  14896. // The total number of segments is 3 * kItemCount + 1 = 3001.
  14897. // With buffering into 64KB blocks, write_count should be much smaller.
  14898. auto segment_count = 3 * kItemCount + 1;
  14899. EXPECT_LT(write_count, segment_count / 10);
  14900. }
  14901. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  14902. // Integration test: send many UploadFormDataItems and verify the server
  14903. // receives all of them correctly (#2410).
  14904. constexpr size_t kItemCount = 500;
  14905. auto handled = false;
  14906. Server svr;
  14907. svr.Post("/upload", [&](const Request &req, Response &res) {
  14908. EXPECT_EQ(kItemCount, req.form.fields.size());
  14909. for (size_t i = 0; i < kItemCount; i++) {
  14910. auto key = "field" + std::to_string(i);
  14911. auto val = "value" + std::to_string(i);
  14912. auto it = req.form.fields.find(key);
  14913. if (it != req.form.fields.end()) {
  14914. EXPECT_EQ(val, it->second.content);
  14915. } else {
  14916. ADD_FAILURE() << "Missing field: " << key;
  14917. }
  14918. }
  14919. res.set_content("ok", "text/plain");
  14920. handled = true;
  14921. });
  14922. auto port = svr.bind_to_any_port(HOST);
  14923. auto t = thread([&] { svr.listen_after_bind(); });
  14924. auto se = detail::scope_exit([&] {
  14925. svr.stop();
  14926. t.join();
  14927. ASSERT_FALSE(svr.is_running());
  14928. ASSERT_TRUE(handled);
  14929. });
  14930. svr.wait_until_ready();
  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. Client cli(HOST, port);
  14938. auto res = cli.Post("/upload", items);
  14939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14940. EXPECT_EQ(StatusCode::OK_200, res->status);
  14941. }
  14942. TEST(MultipartFormDataTest, MakeFileProvider) {
  14943. // Verify make_file_provider sends a file's contents correctly.
  14944. const std::string file_content(4096, 'Z');
  14945. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  14946. {
  14947. std::ofstream ofs(tmp_path, std::ios::binary);
  14948. ofs.write(file_content.data(),
  14949. static_cast<std::streamsize>(file_content.size()));
  14950. }
  14951. auto handled = false;
  14952. Server svr;
  14953. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  14954. const ContentReader &content_reader) {
  14955. ASSERT_TRUE(req.is_multipart_form_data());
  14956. std::vector<FormData> items;
  14957. content_reader(
  14958. [&](const FormData &file) {
  14959. items.push_back(file);
  14960. return true;
  14961. },
  14962. [&](const char *data, size_t data_length) {
  14963. items.back().content.append(data, data_length);
  14964. return true;
  14965. });
  14966. ASSERT_EQ(1u, items.size());
  14967. EXPECT_EQ("myfile", items[0].name);
  14968. EXPECT_EQ("data.bin", items[0].filename);
  14969. EXPECT_EQ("application/octet-stream", items[0].content_type);
  14970. EXPECT_EQ(file_content, items[0].content);
  14971. handled = true;
  14972. });
  14973. auto port = svr.bind_to_any_port(HOST);
  14974. auto t = thread([&] { svr.listen_after_bind(); });
  14975. auto se = detail::scope_exit([&] {
  14976. svr.stop();
  14977. t.join();
  14978. ASSERT_FALSE(svr.is_running());
  14979. ASSERT_TRUE(handled);
  14980. std::remove(tmp_path.c_str());
  14981. });
  14982. svr.wait_until_ready();
  14983. FormDataProviderItems providers;
  14984. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  14985. "application/octet-stream"));
  14986. Client cli(HOST, port);
  14987. auto res = cli.Post("/upload", {}, {}, providers);
  14988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14989. EXPECT_EQ(StatusCode::OK_200, res->status);
  14990. }
  14991. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  14992. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  14993. // (100) headers is rejected with a 400 Bad Request response.
  14994. Server svr;
  14995. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14996. res.set_content("ok", "text/plain");
  14997. });
  14998. thread t = thread([&] { svr.listen(HOST, PORT); });
  14999. auto se = detail::scope_exit([&] {
  15000. svr.stop();
  15001. t.join();
  15002. ASSERT_FALSE(svr.is_running());
  15003. });
  15004. svr.wait_until_ready();
  15005. // Build a multipart part with 101 custom headers (exceeding
  15006. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15007. std::stringstream body;
  15008. body << "--simpleboundary\r\n"
  15009. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15010. for (int i = 0; i < 101; i++) {
  15011. body << "X-Custom-Header-" << i << ": value\r\n";
  15012. }
  15013. body << "\r\n"
  15014. << "value1\r\n"
  15015. << "--simpleboundary--\r\n";
  15016. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15017. Client cli(HOST, PORT);
  15018. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15020. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15021. }
  15022. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15023. // A body that never contains the declared boundary must not be accumulated
  15024. // while the parser waits for it. Buffering it would also make every read
  15025. // rescan everything seen so far, which is quadratic in the body size.
  15026. Server svr;
  15027. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15028. res.set_content("ok", "text/plain");
  15029. });
  15030. auto port = svr.bind_to_any_port(HOST);
  15031. thread t = thread([&] { svr.listen_after_bind(); });
  15032. auto se = detail::scope_exit([&] {
  15033. svr.stop();
  15034. t.join();
  15035. ASSERT_FALSE(svr.is_running());
  15036. });
  15037. svr.wait_until_ready();
  15038. Client cli(HOST, port);
  15039. cli.set_read_timeout(60, 0);
  15040. cli.set_write_timeout(60, 0);
  15041. // '-' is the worst case: it matches the first character of the boundary, so
  15042. // every position has to be checked against it.
  15043. auto post_dashes = [&](size_t size) {
  15044. const std::string body(size, '-');
  15045. auto start = std::chrono::steady_clock::now();
  15046. auto res =
  15047. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15048. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15049. std::chrono::steady_clock::now() - start)
  15050. .count();
  15051. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15052. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15053. return ms;
  15054. };
  15055. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15056. // Windows.
  15057. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15058. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15059. // Comparing the two sizes rather than checking an absolute duration keeps
  15060. // this meaningful across build types and CI load, both of which move the
  15061. // absolute numbers by more than an order of magnitude. Four times the bytes
  15062. // costs about four times the time when parsing is linear, and about sixteen
  15063. // times when the body is buffered and rescanned.
  15064. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15065. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15066. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15067. << "ms, which suggests the body is being buffered and rescanned";
  15068. }
  15069. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15070. // A boundary can only be followed by CRLF or by "--", so anything else is
  15071. // malformed no matter what comes next. The parser must say so right away
  15072. // instead of buffering the rest of the declared body.
  15073. Server svr;
  15074. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15075. res.set_content("ok", "text/plain");
  15076. });
  15077. auto port = svr.bind_to_any_port(HOST);
  15078. thread t = thread([&] { svr.listen_after_bind(); });
  15079. auto se = detail::scope_exit([&] {
  15080. svr.stop();
  15081. t.join();
  15082. ASSERT_FALSE(svr.is_running());
  15083. });
  15084. svr.wait_until_ready();
  15085. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15086. // buffers instead of failing would still be waiting for the remaining bytes.
  15087. const std::string body = "--zzzz\r\n"
  15088. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15089. "\r\n"
  15090. "text1"
  15091. "\r\n--zzzzXX";
  15092. const std::string req = "POST /post HTTP/1.1\r\n"
  15093. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15094. "Content-Length: 1048576\r\n"
  15095. "\r\n" +
  15096. body;
  15097. std::string response;
  15098. ASSERT_TRUE(send_request(3, req, &response, port));
  15099. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15100. EXPECT_EQ("400", response.substr(9, 3));
  15101. }
  15102. // Posts a multipart body split into two writes, so that the server sees the
  15103. // split at whatever offset the caller chose, and expects the single "text1"
  15104. // field to come through.
  15105. static void expect_split_multipart_ok(const std::string &body1,
  15106. const std::string &body2) {
  15107. auto handled = false;
  15108. Server svr;
  15109. svr.Post("/post", [&](const Request &req, Response &) {
  15110. EXPECT_EQ(1u, req.form.fields.size());
  15111. EXPECT_EQ("text1", req.form.get_field("text1"));
  15112. handled = true;
  15113. });
  15114. auto port = svr.bind_to_any_port(HOST);
  15115. thread t = thread([&] { svr.listen_after_bind(); });
  15116. auto se = detail::scope_exit([&] {
  15117. svr.stop();
  15118. t.join();
  15119. ASSERT_FALSE(svr.is_running());
  15120. ASSERT_TRUE(handled);
  15121. });
  15122. svr.wait_until_ready();
  15123. // "Connection: close" makes the server close once it has answered, so the
  15124. // response drain ends immediately instead of idling until the read timeout.
  15125. const std::string head =
  15126. "POST /post HTTP/1.1\r\n"
  15127. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15128. "Connection: close\r\n"
  15129. "Content-Length: " +
  15130. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15131. std::string response;
  15132. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15133. ASSERT_GE(response.size(), 12u) << "no response";
  15134. EXPECT_EQ("200", response.substr(9, 3));
  15135. }
  15136. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15137. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15138. // ignored, including when it does not arrive in the same read as the
  15139. // close-delimiter itself.
  15140. expect_split_multipart_ok("--zzzz\r\n"
  15141. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15142. "\r\n"
  15143. "text1"
  15144. "\r\n--zzzz--",
  15145. "\r\nthis epilogue must be ignored\r\n");
  15146. }
  15147. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15148. // The initial boundary may be preceded by a preamble of any length and may
  15149. // straddle a read boundary. Discarding data while waiting for it must not
  15150. // throw away a partial boundary sitting at the end of the buffer.
  15151. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15152. "zz\r\n"
  15153. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15154. "\r\n"
  15155. "text1"
  15156. "\r\n--zzzz--\r\n");
  15157. }
  15158. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15159. // The received boundary was only checked for being non-empty, so it could be
  15160. // as long as a header is allowed to be. The parser scans the body for
  15161. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15162. // costs a nearly full comparison at nearly every position, making the
  15163. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15164. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15165. Server svr;
  15166. svr.Post("/post", [](const Request &req, Response &res) {
  15167. EXPECT_EQ(1u, req.form.fields.size());
  15168. EXPECT_EQ("text1", req.form.get_field("text1"));
  15169. res.set_content("ok", "text/plain");
  15170. });
  15171. auto port = svr.bind_to_any_port(HOST);
  15172. thread t = thread([&] { svr.listen_after_bind(); });
  15173. auto se = detail::scope_exit([&] {
  15174. svr.stop();
  15175. t.join();
  15176. ASSERT_FALSE(svr.is_running());
  15177. });
  15178. svr.wait_until_ready();
  15179. Client cli(HOST, port);
  15180. auto post_with_boundary_of_length = [&](size_t len) {
  15181. const std::string boundary(len, 'a');
  15182. const std::string body =
  15183. "--" + boundary +
  15184. "\r\n"
  15185. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15186. "\r\n"
  15187. "text1"
  15188. "\r\n--" +
  15189. boundary + "--\r\n";
  15190. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15191. };
  15192. auto res = post_with_boundary_of_length(70);
  15193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15194. EXPECT_EQ(StatusCode::OK_200, res->status);
  15195. res = post_with_boundary_of_length(71);
  15196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15197. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15198. }
  15199. TEST(MakeFileBodyTest, Basic) {
  15200. const std::string file_content(4096, 'Z');
  15201. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15202. {
  15203. std::ofstream ofs(tmp_path, std::ios::binary);
  15204. ofs.write(file_content.data(),
  15205. static_cast<std::streamsize>(file_content.size()));
  15206. }
  15207. auto handled = false;
  15208. Server svr;
  15209. svr.Post("/upload", [&](const Request &req, Response &res) {
  15210. EXPECT_EQ(file_content, req.body);
  15211. handled = true;
  15212. res.status = StatusCode::OK_200;
  15213. });
  15214. auto port = svr.bind_to_any_port(HOST);
  15215. auto t = thread([&] { svr.listen_after_bind(); });
  15216. auto se = detail::scope_exit([&] {
  15217. svr.stop();
  15218. t.join();
  15219. ASSERT_FALSE(svr.is_running());
  15220. ASSERT_TRUE(handled);
  15221. std::remove(tmp_path.c_str());
  15222. });
  15223. svr.wait_until_ready();
  15224. auto fb = make_file_body(tmp_path);
  15225. ASSERT_GT(fb.first, 0u);
  15226. Client cli(HOST, port);
  15227. auto res =
  15228. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15230. EXPECT_EQ(StatusCode::OK_200, res->status);
  15231. }
  15232. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15233. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15234. {
  15235. std::ofstream ofs(path, std::ios::binary);
  15236. const std::string content(100, 'A');
  15237. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15238. }
  15239. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15240. auto body = make_file_body(path);
  15241. ASSERT_EQ(100u, body.first);
  15242. ASSERT_TRUE(static_cast<bool>(body.second));
  15243. // Rewritten shorter after its length was measured - and, on a server, after
  15244. // that length has already gone out as Content-Length.
  15245. {
  15246. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15247. const std::string content(10, 'A');
  15248. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15249. }
  15250. std::string written;
  15251. DataSink sink;
  15252. sink.write = [&](const char *d, size_t l) {
  15253. written.append(d, l);
  15254. return true;
  15255. };
  15256. // The provider has to report failure. write_content_with_progress() advances
  15257. // its offset only by what was written, so a provider that returns true
  15258. // without completing the length it promised is called again straight away,
  15259. // and again.
  15260. EXPECT_FALSE(body.second(0, body.first, sink));
  15261. EXPECT_EQ(std::string(10, 'A'), written);
  15262. }
  15263. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15264. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15265. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15266. {
  15267. std::ofstream ofs(path, std::ios::binary);
  15268. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15269. }
  15270. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15271. auto body = make_file_body(path);
  15272. ASSERT_EQ(content.size(), body.first);
  15273. ASSERT_TRUE(static_cast<bool>(body.second));
  15274. std::string written;
  15275. DataSink sink;
  15276. sink.write = [&](const char *d, size_t l) {
  15277. written.append(d, l);
  15278. return true;
  15279. };
  15280. EXPECT_TRUE(body.second(0, body.first, sink));
  15281. EXPECT_EQ(content, written);
  15282. }
  15283. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15284. static constexpr unsigned int number_of_tasks{1000000};
  15285. std::atomic_uint count{0};
  15286. std::unique_ptr<TaskQueue> task_queue{
  15287. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15288. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15289. auto queued = task_queue->enqueue(
  15290. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15291. EXPECT_TRUE(queued);
  15292. }
  15293. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15294. task_queue->shutdown();
  15295. #else
  15296. EXPECT_NO_THROW(task_queue->shutdown());
  15297. #endif
  15298. EXPECT_EQ(number_of_tasks, count.load());
  15299. }
  15300. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15301. static constexpr unsigned int number_of_tasks{1000000};
  15302. static constexpr unsigned int qlimit{2};
  15303. unsigned int queued_count{0};
  15304. std::atomic_uint count{0};
  15305. std::unique_ptr<TaskQueue> task_queue{
  15306. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15307. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15308. if (task_queue->enqueue(
  15309. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15310. queued_count++;
  15311. }
  15312. }
  15313. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15314. task_queue->shutdown();
  15315. #else
  15316. EXPECT_NO_THROW(task_queue->shutdown());
  15317. #endif
  15318. EXPECT_EQ(queued_count, count.load());
  15319. EXPECT_TRUE(queued_count <= number_of_tasks);
  15320. EXPECT_TRUE(queued_count >= qlimit);
  15321. }
  15322. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15323. // Use a short idle timeout so a dynamic thread spawns, times out and
  15324. // exits during the test, and the pool keeps working afterwards.
  15325. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15326. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15327. /*idle_timeout_sec=*/1}};
  15328. std::atomic_uint count{0};
  15329. std::condition_variable cv;
  15330. std::mutex mtx;
  15331. bool release = false;
  15332. // Block the base thread so the second task spawns a dynamic thread.
  15333. EXPECT_TRUE(task_queue->enqueue([&] {
  15334. std::unique_lock<std::mutex> lock(mtx);
  15335. while (!release) {
  15336. cv.wait(lock);
  15337. }
  15338. count++;
  15339. }));
  15340. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15341. // Let the dynamic thread finish its task and exceed the idle timeout.
  15342. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15343. {
  15344. std::unique_lock<std::mutex> lock(mtx);
  15345. release = true;
  15346. }
  15347. cv.notify_all();
  15348. // The pool must still accept and run tasks after the dynamic thread exited.
  15349. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15350. task_queue->shutdown();
  15351. EXPECT_EQ(3u, count.load());
  15352. }
  15353. TEST(TaskQueueTest, MaxQueuedRequests) {
  15354. static constexpr unsigned int qlimit{3};
  15355. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15356. std::condition_variable sem_cv;
  15357. std::mutex sem_mtx;
  15358. int credits = 0;
  15359. bool queued;
  15360. /* Fill up the queue with tasks that will block until we give them credits to
  15361. * complete. */
  15362. for (unsigned int n = 0; n <= qlimit;) {
  15363. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15364. std::unique_lock<std::mutex> lock(sem_mtx);
  15365. while (credits <= 0) {
  15366. sem_cv.wait(lock);
  15367. }
  15368. /* Consume the credit and signal the test code if they are all gone. */
  15369. if (--credits == 0) { sem_cv.notify_one(); }
  15370. });
  15371. if (n < qlimit) {
  15372. /* The first qlimit enqueues must succeed. */
  15373. EXPECT_TRUE(queued);
  15374. } else {
  15375. /* The last one will succeed only when the worker thread
  15376. * starts and dequeues the first blocking task. Although
  15377. * not necessary for the correctness of this test, we sleep for
  15378. * a short while to avoid busy waiting. */
  15379. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15380. }
  15381. if (queued) { n++; }
  15382. }
  15383. /* Further enqueues must fail since the queue is full. */
  15384. for (auto i = 0; i < 4; i++) {
  15385. queued = task_queue->enqueue([] {});
  15386. EXPECT_FALSE(queued);
  15387. }
  15388. /* Give the credits to allow the previous tasks to complete. */
  15389. {
  15390. std::unique_lock<std::mutex> lock(sem_mtx);
  15391. credits += qlimit + 1;
  15392. }
  15393. sem_cv.notify_all();
  15394. /* Wait for all the credits to be consumed. */
  15395. {
  15396. std::unique_lock<std::mutex> lock(sem_mtx);
  15397. while (credits > 0) {
  15398. sem_cv.wait(lock);
  15399. }
  15400. }
  15401. /* Check that we are able again to enqueue at least qlimit tasks. */
  15402. for (unsigned int i = 0; i < qlimit; i++) {
  15403. queued = task_queue->enqueue([] {});
  15404. EXPECT_TRUE(queued);
  15405. }
  15406. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15407. task_queue->shutdown();
  15408. #else
  15409. EXPECT_NO_THROW(task_queue->shutdown());
  15410. #endif
  15411. }
  15412. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15413. Server svr;
  15414. std::string method;
  15415. std::string body;
  15416. auto has_content_length = false;
  15417. auto has_transfer_encoding = false;
  15418. std::atomic<int> bad_requests{0};
  15419. // Leftover body bytes get parsed as a malformed request and answered with
  15420. // 400
  15421. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15422. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15423. });
  15424. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15425. res.set_redirect("/down", StatusCode::SeeOther_303);
  15426. });
  15427. svr.Get("/down", [&](const Request &req, Response &res) {
  15428. method = req.method;
  15429. body = req.body;
  15430. has_content_length = req.has_header("Content-Length");
  15431. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15432. res.set_content("ok", "text/plain");
  15433. });
  15434. auto port = svr.bind_to_any_port(HOST);
  15435. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15436. auto se = detail::scope_exit([&] {
  15437. svr.stop();
  15438. thread.join();
  15439. ASSERT_FALSE(svr.is_running());
  15440. });
  15441. svr.wait_until_ready();
  15442. const std::string payload = "SECRET-BODY";
  15443. auto check = [&](Client &cli, const Result &res) {
  15444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15445. EXPECT_EQ(StatusCode::OK_200, res->status);
  15446. EXPECT_EQ("ok", res->body);
  15447. EXPECT_EQ("GET", method);
  15448. EXPECT_TRUE(body.empty());
  15449. EXPECT_FALSE(has_content_length);
  15450. EXPECT_FALSE(has_transfer_encoding);
  15451. // Nothing of the original body may be left on the connection
  15452. auto res2 = cli.Get("/down");
  15453. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15454. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15455. EXPECT_EQ("ok", res2->body);
  15456. EXPECT_EQ(0, bad_requests);
  15457. };
  15458. // With content length
  15459. {
  15460. Client cli(HOST, port);
  15461. cli.set_keep_alive(true);
  15462. cli.set_follow_location(true);
  15463. auto res = cli.Post(
  15464. "/up", payload.size(),
  15465. [&](size_t offset, size_t length, DataSink &sink) {
  15466. return sink.write(payload.data() + offset, length);
  15467. },
  15468. "text/plain");
  15469. check(cli, res);
  15470. }
  15471. // Without content length (chunked)
  15472. {
  15473. Client cli(HOST, port);
  15474. cli.set_keep_alive(true);
  15475. cli.set_follow_location(true);
  15476. auto res = cli.Post(
  15477. "/up",
  15478. [&](size_t /*offset*/, DataSink &sink) {
  15479. sink.write(payload.data(), payload.size());
  15480. sink.done();
  15481. return true;
  15482. },
  15483. "text/plain");
  15484. check(cli, res);
  15485. }
  15486. }
  15487. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15488. Server svr;
  15489. std::string target;
  15490. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15491. // Echo the still-encoded name back in the Location
  15492. const std::string prefix = "/start/";
  15493. res.status = StatusCode::Found_302;
  15494. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15495. });
  15496. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15497. target = req.target;
  15498. res.set_content("ok", "text/plain");
  15499. });
  15500. auto port = svr.bind_to_any_port(HOST);
  15501. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15502. auto se = detail::scope_exit([&] {
  15503. svr.stop();
  15504. thread.join();
  15505. ASSERT_FALSE(svr.is_running());
  15506. });
  15507. svr.wait_until_ready();
  15508. // Decoding the Location path would turn the first four into a path
  15509. // separator, a query delimiter, a fragment delimiter and a different
  15510. // percent-encoded octet. The rest must keep reaching the server as they are.
  15511. const std::vector<std::string> names = {
  15512. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15513. };
  15514. for (auto path_encode : {true, false}) {
  15515. Client cli(HOST, port);
  15516. cli.set_follow_location(true);
  15517. cli.set_path_encode(path_encode);
  15518. for (const auto &name : names) {
  15519. target.clear();
  15520. auto res = cli.Get("/start/" + name);
  15521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15522. EXPECT_EQ(StatusCode::OK_200, res->status);
  15523. EXPECT_EQ("/dest/" + name, target);
  15524. }
  15525. }
  15526. }
  15527. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15528. Server svr;
  15529. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15530. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15531. });
  15532. svr.Get("/hello", [](const Request &req, Response &res) {
  15533. res.set_content(req.get_param_value("key"), "text/plain");
  15534. });
  15535. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15536. auto se = detail::scope_exit([&] {
  15537. svr.stop();
  15538. thread.join();
  15539. ASSERT_FALSE(svr.is_running());
  15540. });
  15541. svr.wait_until_ready();
  15542. {
  15543. Client cli(HOST, PORT);
  15544. cli.set_follow_location(true);
  15545. auto res = cli.Get("/");
  15546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15547. EXPECT_EQ(StatusCode::OK_200, res->status);
  15548. EXPECT_EQ("val&key2=val2", res->body);
  15549. }
  15550. }
  15551. #endif
  15552. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15553. Server svr;
  15554. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15555. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15556. });
  15557. svr.Get("/hello", [](const Request &req, Response &res) {
  15558. res.set_content(req.get_param_value("key"), "text/plain");
  15559. });
  15560. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15561. auto se = detail::scope_exit([&] {
  15562. svr.stop();
  15563. thread.join();
  15564. ASSERT_FALSE(svr.is_running());
  15565. });
  15566. svr.wait_until_ready();
  15567. {
  15568. Client cli(HOST, PORT);
  15569. cli.set_follow_location(true);
  15570. auto res = cli.Get("/");
  15571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15572. EXPECT_EQ(StatusCode::OK_200, res->status);
  15573. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15574. }
  15575. }
  15576. TEST(RedirectTest, RedirectWithPlusInPath) {
  15577. Server svr;
  15578. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15579. res.set_redirect("/a+b");
  15580. });
  15581. // Route pattern uses regex; escape + as \\+
  15582. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15583. res.set_content(req.path, "text/plain");
  15584. });
  15585. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15586. auto se = detail::scope_exit([&] {
  15587. svr.stop();
  15588. thread.join();
  15589. ASSERT_FALSE(svr.is_running());
  15590. });
  15591. svr.wait_until_ready();
  15592. {
  15593. Client cli(HOST, PORT);
  15594. cli.set_follow_location(true);
  15595. auto res = cli.Get("/");
  15596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15597. EXPECT_EQ(StatusCode::OK_200, res->status);
  15598. EXPECT_EQ("/a+b", res->body);
  15599. }
  15600. }
  15601. TEST(RedirectTest, ResolveRelativeLocation) {
  15602. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15603. const std::vector<std::pair<std::string, std::string>> cases = {
  15604. {"g", "/b/c/g"},
  15605. {"./g", "/b/c/g"},
  15606. {"g/", "/b/c/g/"},
  15607. {"?y", "/b/c/d;p?y"},
  15608. {"g?y", "/b/c/g?y"},
  15609. {"#s", "/b/c/d;p?q#s"},
  15610. {"g#s", "/b/c/g#s"},
  15611. {"g?y#s", "/b/c/g?y#s"},
  15612. {";x", "/b/c/;x"},
  15613. {"g;x", "/b/c/g;x"},
  15614. {".", "/b/c/"},
  15615. {"./", "/b/c/"},
  15616. {"..", "/b/"},
  15617. {"../", "/b/"},
  15618. {"../g", "/b/g"},
  15619. {"../..", "/"},
  15620. {"../../", "/"},
  15621. {"../../g", "/g"},
  15622. {"../../../g", "/g"},
  15623. {"g.", "/b/c/g."},
  15624. {".g", "/b/c/.g"},
  15625. {"g..", "/b/c/g.."},
  15626. {"..g", "/b/c/..g"},
  15627. {"./../g", "/b/g"},
  15628. {"./g/.", "/b/c/g/"},
  15629. {"g/./h", "/b/c/g/h"},
  15630. {"g/../h", "/b/c/h"},
  15631. {"g;x=1/./y", "/b/c/g;x=1/y"},
  15632. {"g;x=1/../y", "/b/c/y"},
  15633. {"g?y/./x", "/b/c/g?y/./x"},
  15634. {"g#s/../x", "/b/c/g#s/../x"},
  15635. // Not relative-path references, so left for parse_url.
  15636. {"/g", "/g"},
  15637. {"//g", "//g"},
  15638. {"http://g/x", "http://g/x"},
  15639. {"g:h", "g:h"},
  15640. };
  15641. for (const auto &c : cases) {
  15642. EXPECT_EQ(c.second,
  15643. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15644. << c.first;
  15645. }
  15646. }
  15647. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15648. Server svr;
  15649. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15650. res.set_redirect(req.get_param_value("to"));
  15651. });
  15652. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15653. res.set_content(req.target, "text/plain");
  15654. });
  15655. svr.Get("/other", [](const Request &req, Response &res) {
  15656. res.set_content(req.target, "text/plain");
  15657. });
  15658. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15659. auto se = detail::scope_exit([&] {
  15660. svr.stop();
  15661. thread.join();
  15662. ASSERT_FALSE(svr.is_running());
  15663. });
  15664. svr.wait_until_ready();
  15665. const std::vector<std::pair<std::string, std::string>> cases = {
  15666. {"next", "/dir/next"},
  15667. {"./next?x=1", "/dir/next?x=1"},
  15668. {"../other", "/other"},
  15669. };
  15670. for (const auto &c : cases) {
  15671. Client cli(HOST, PORT);
  15672. cli.set_follow_location(true);
  15673. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15674. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15675. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  15676. EXPECT_EQ(c.second, res->body) << c.first;
  15677. }
  15678. }
  15679. #ifdef CPPHTTPLIB_SSL_ENABLED
  15680. TEST(RedirectTest, Issue2185_Online) {
  15681. SSLClient client("github.com");
  15682. client.set_follow_location(true);
  15683. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  15684. "Coollab-Windows.zip");
  15685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15686. EXPECT_EQ(StatusCode::OK_200, res->status);
  15687. EXPECT_EQ(9920427U, res->body.size());
  15688. }
  15689. #endif
  15690. TEST(VulnerabilityTest, CRLFInjection) {
  15691. Server svr;
  15692. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  15693. res.set_content("Hello 1", "text/plain");
  15694. });
  15695. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  15696. res.set_content("Hello 2", "text/plain");
  15697. });
  15698. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  15699. res.set_content("Hello 3", "text/plain");
  15700. });
  15701. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  15702. res.set_content("Hello 4", "text/plain");
  15703. });
  15704. svr.set_logger([](const Request &req, const Response & /*res*/) {
  15705. for (const auto &x : req.headers) {
  15706. auto key = x.first;
  15707. EXPECT_STRNE("evil", key.c_str());
  15708. }
  15709. });
  15710. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15711. auto se = detail::scope_exit([&] {
  15712. svr.stop();
  15713. thread.join();
  15714. ASSERT_FALSE(svr.is_running());
  15715. });
  15716. svr.wait_until_ready();
  15717. {
  15718. Client cli(HOST, PORT);
  15719. cli.Post("/test1", "A=B",
  15720. "application/x-www-form-urlencoded\r\nevil: hello1");
  15721. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  15722. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  15723. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  15724. }
  15725. }
  15726. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  15727. auto server_thread = std::thread([] {
  15728. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15729. default_socket_options(srv);
  15730. sockaddr_in addr{};
  15731. addr.sin_family = AF_INET;
  15732. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15733. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15734. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  15735. ::listen(srv, 1);
  15736. sockaddr_in cli_addr{};
  15737. socklen_t cli_len = sizeof(cli_addr);
  15738. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15739. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  15740. std::string buf_all;
  15741. char buf[2048];
  15742. ssize_t n;
  15743. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  15744. buf_all.append(buf, static_cast<size_t>(n));
  15745. size_t pos;
  15746. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  15747. auto request_block = buf_all.substr(0, pos + 4); // include separator
  15748. auto e = request_block.find("\r\n");
  15749. if (e != std::string::npos) {
  15750. auto request_line = request_block.substr(0, e);
  15751. std::string msg =
  15752. "CRLF injection detected in request line: '" + request_line + "'";
  15753. EXPECT_FALSE(true) << msg;
  15754. }
  15755. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  15756. ::send(cli,
  15757. #ifdef _WIN32
  15758. static_cast<const char *>(resp.c_str()),
  15759. static_cast<int>(resp.size()),
  15760. #else
  15761. resp.c_str(), resp.size(),
  15762. #endif
  15763. 0);
  15764. buf_all.erase(0, pos + 4);
  15765. }
  15766. }
  15767. detail::close_socket(cli);
  15768. detail::close_socket(srv);
  15769. });
  15770. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15771. auto cli = Client("127.0.0.1", PORT + 1);
  15772. auto headers = Headers{
  15773. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  15774. {"Connection", "keep-alive"}};
  15775. auto res = cli.Get("/hi", headers);
  15776. EXPECT_FALSE(res);
  15777. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15778. server_thread.join();
  15779. }
  15780. // A request rejected before any byte reaches the socket must fail right away
  15781. // instead of waiting for a response the server will never send.
  15782. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  15783. // The kernel completes the TCP handshake from the listen backlog, so the
  15784. // client connects, but nothing ever reads, responds or closes.
  15785. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15786. default_socket_options(srv);
  15787. sockaddr_in addr{};
  15788. addr.sin_family = AF_INET;
  15789. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15790. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15791. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15792. ASSERT_EQ(0, ::listen(srv, 8));
  15793. auto cli = Client("127.0.0.1", PORT + 1);
  15794. cli.set_read_timeout(10, 0);
  15795. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  15796. return std::chrono::duration_cast<std::chrono::milliseconds>(
  15797. std::chrono::steady_clock::now() - start)
  15798. .count();
  15799. };
  15800. {
  15801. Request req;
  15802. req.method = "GE T";
  15803. req.path = "/";
  15804. auto start = std::chrono::steady_clock::now();
  15805. auto res = cli.send(req);
  15806. EXPECT_FALSE(res);
  15807. EXPECT_EQ(Error::Write, res.error());
  15808. EXPECT_LT(elapsed_ms(start), 1000);
  15809. }
  15810. {
  15811. auto start = std::chrono::steady_clock::now();
  15812. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  15813. EXPECT_FALSE(res);
  15814. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15815. EXPECT_LT(elapsed_ms(start), 1000);
  15816. }
  15817. EXPECT_FALSE(cli.is_socket_open());
  15818. detail::close_socket(srv);
  15819. }
  15820. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  15821. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15822. default_socket_options(srv);
  15823. sockaddr_in addr{};
  15824. addr.sin_family = AF_INET;
  15825. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15826. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15827. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15828. ASSERT_EQ(0, ::listen(srv, 1));
  15829. std::string received;
  15830. auto server_thread = std::thread([&] {
  15831. auto sock = ::accept(srv, nullptr, nullptr);
  15832. if (sock == INVALID_SOCKET) { return; }
  15833. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  15834. char buf[2048];
  15835. ssize_t n;
  15836. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  15837. received.append(buf, static_cast<size_t>(n));
  15838. }
  15839. detail::close_socket(sock);
  15840. });
  15841. {
  15842. auto cli = Client("127.0.0.1", PORT + 1);
  15843. // "Z" sorts after the default headers, so writing straight to the socket
  15844. // would have sent the request line and those headers before the rejection.
  15845. auto handle =
  15846. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  15847. EXPECT_FALSE(handle.is_valid());
  15848. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  15849. }
  15850. server_thread.join();
  15851. detail::close_socket(srv);
  15852. EXPECT_TRUE(received.empty()) << received;
  15853. }
  15854. TEST(PathParamsTest, StaticMatch) {
  15855. const auto pattern = "/users/all";
  15856. detail::PathParamsMatcher matcher(pattern);
  15857. Request request;
  15858. request.path = "/users/all";
  15859. ASSERT_TRUE(matcher.match(request));
  15860. std::unordered_map<std::string, std::string> expected_params = {};
  15861. EXPECT_EQ(request.path_params, expected_params);
  15862. }
  15863. TEST(PathParamsTest, StaticMismatch) {
  15864. const auto pattern = "/users/all";
  15865. detail::PathParamsMatcher matcher(pattern);
  15866. Request request;
  15867. request.path = "/users/1";
  15868. ASSERT_FALSE(matcher.match(request));
  15869. }
  15870. TEST(PathParamsTest, SingleParamInTheMiddle) {
  15871. const auto pattern = "/users/:id/subscriptions";
  15872. detail::PathParamsMatcher matcher(pattern);
  15873. Request request;
  15874. request.path = "/users/42/subscriptions";
  15875. ASSERT_TRUE(matcher.match(request));
  15876. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15877. EXPECT_EQ(request.path_params, expected_params);
  15878. }
  15879. TEST(PathParamsTest, SingleParamInTheEnd) {
  15880. const auto pattern = "/users/:id";
  15881. detail::PathParamsMatcher matcher(pattern);
  15882. Request request;
  15883. request.path = "/users/24";
  15884. ASSERT_TRUE(matcher.match(request));
  15885. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  15886. EXPECT_EQ(request.path_params, expected_params);
  15887. }
  15888. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  15889. const auto pattern = "/users/:id/";
  15890. detail::PathParamsMatcher matcher(pattern);
  15891. Request request;
  15892. request.path = "/users/42/";
  15893. ASSERT_TRUE(matcher.match(request));
  15894. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15895. EXPECT_EQ(request.path_params, expected_params);
  15896. }
  15897. TEST(PathParamsTest, EmptyParam) {
  15898. const auto pattern = "/users/:id/";
  15899. detail::PathParamsMatcher matcher(pattern);
  15900. Request request;
  15901. request.path = "/users//";
  15902. ASSERT_TRUE(matcher.match(request));
  15903. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  15904. EXPECT_EQ(request.path_params, expected_params);
  15905. }
  15906. TEST(PathParamsTest, FragmentMismatch) {
  15907. const auto pattern = "/users/:id/";
  15908. detail::PathParamsMatcher matcher(pattern);
  15909. Request request;
  15910. request.path = "/admins/24/";
  15911. ASSERT_FALSE(matcher.match(request));
  15912. }
  15913. TEST(PathParamsTest, ExtraFragments) {
  15914. const auto pattern = "/users/:id";
  15915. detail::PathParamsMatcher matcher(pattern);
  15916. Request request;
  15917. request.path = "/users/42/subscriptions";
  15918. ASSERT_FALSE(matcher.match(request));
  15919. }
  15920. TEST(PathParamsTest, MissingTrailingParam) {
  15921. const auto pattern = "/users/:id";
  15922. detail::PathParamsMatcher matcher(pattern);
  15923. Request request;
  15924. request.path = "/users";
  15925. ASSERT_FALSE(matcher.match(request));
  15926. }
  15927. TEST(PathParamsTest, MissingParamInTheMiddle) {
  15928. const auto pattern = "/users/:id/subscriptions";
  15929. detail::PathParamsMatcher matcher(pattern);
  15930. Request request;
  15931. request.path = "/users/subscriptions";
  15932. ASSERT_FALSE(matcher.match(request));
  15933. }
  15934. TEST(PathParamsTest, MultipleParams) {
  15935. const auto pattern = "/users/:userid/subscriptions/:subid";
  15936. detail::PathParamsMatcher matcher(pattern);
  15937. Request request;
  15938. request.path = "/users/42/subscriptions/2";
  15939. ASSERT_TRUE(matcher.match(request));
  15940. std::unordered_map<std::string, std::string> expected_params = {
  15941. {"userid", "42"}, {"subid", "2"}};
  15942. EXPECT_EQ(request.path_params, expected_params);
  15943. }
  15944. TEST(PathParamsTest, SequenceOfParams) {
  15945. const auto pattern = "/values/:x/:y/:z";
  15946. detail::PathParamsMatcher matcher(pattern);
  15947. Request request;
  15948. request.path = "/values/1/2/3";
  15949. ASSERT_TRUE(matcher.match(request));
  15950. std::unordered_map<std::string, std::string> expected_params = {
  15951. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  15952. EXPECT_EQ(request.path_params, expected_params);
  15953. }
  15954. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  15955. const auto pattern = "/prefix:suffix";
  15956. detail::PathParamsMatcher matcher(pattern);
  15957. Request request;
  15958. request.path = "/prefix:suffix";
  15959. ASSERT_TRUE(matcher.match(request));
  15960. const std::unordered_map<std::string, std::string> expected_params = {};
  15961. EXPECT_EQ(request.path_params, expected_params);
  15962. }
  15963. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  15964. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  15965. // calling thread's stack on a long enough path for a quantified pattern;
  15966. // RegexMatcher must refuse to run regex matching on paths beyond
  15967. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  15968. detail::RegexMatcher matcher("/files/(.*)");
  15969. Request within_limit;
  15970. within_limit.path = "/files/" + std::string(10, 'A');
  15971. EXPECT_TRUE(matcher.match(within_limit));
  15972. Request over_limit;
  15973. over_limit.path =
  15974. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  15975. EXPECT_FALSE(matcher.match(over_limit));
  15976. }
  15977. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  15978. Server svr;
  15979. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  15980. res.set_content("ok", "text/plain");
  15981. });
  15982. auto port = svr.bind_to_any_port(HOST);
  15983. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15984. auto se = detail::scope_exit([&] {
  15985. svr.stop();
  15986. thread.join();
  15987. ASSERT_FALSE(svr.is_running());
  15988. });
  15989. svr.wait_until_ready();
  15990. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  15991. // request URI limit; this used to be able to crash the process.
  15992. std::string path =
  15993. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  15994. std::string req = "GET " + path +
  15995. " HTTP/1.1\r\n"
  15996. "Host: " +
  15997. std::string(HOST) + ":" + std::to_string(port) +
  15998. "\r\n"
  15999. "Connection: close\r\n"
  16000. "\r\n";
  16001. std::string response;
  16002. ASSERT_TRUE(send_request(5, req, &response, port));
  16003. EXPECT_NE(std::string::npos, response.find("404"));
  16004. }
  16005. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16006. Server svr;
  16007. auto handler = [](const Request & /*req*/, Response &res) {
  16008. res.set_content("hit", "text/plain");
  16009. };
  16010. // No regex metacharacter, so this one is compared literally
  16011. svr.Get("/literal/route", handler);
  16012. // '.' is a regex metacharacter, so this one must keep regex semantics
  16013. svr.Get("/a.c", handler);
  16014. auto port = svr.bind_to_any_port(HOST);
  16015. std::thread t([&]() { svr.listen_after_bind(); });
  16016. auto se = detail::scope_exit([&] {
  16017. svr.stop();
  16018. t.join();
  16019. ASSERT_FALSE(svr.is_running());
  16020. });
  16021. svr.wait_until_ready();
  16022. Client cli(HOST, port);
  16023. struct {
  16024. const char *path;
  16025. int status;
  16026. } cases[] = {
  16027. {"/literal/route", StatusCode::OK_200},
  16028. {"/literal/routes", StatusCode::NotFound_404},
  16029. {"/literal/rout", StatusCode::NotFound_404},
  16030. {"/abc", StatusCode::OK_200},
  16031. {"/a.c", StatusCode::OK_200},
  16032. };
  16033. for (const auto &x : cases) {
  16034. auto res = cli.Get(x.path);
  16035. ASSERT_TRUE(res) << x.path;
  16036. EXPECT_EQ(x.status, res->status) << x.path;
  16037. }
  16038. }
  16039. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16040. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16041. // from exhausting the stack, so it must only constrain routes that actually
  16042. // run a regular expression. A literal route is matched by comparison and
  16043. // stays usable at any length.
  16044. Server svr;
  16045. const std::string pattern =
  16046. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16047. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16048. res.set_content("hit", "text/plain");
  16049. });
  16050. auto port = svr.bind_to_any_port(HOST);
  16051. std::thread t([&]() { svr.listen_after_bind(); });
  16052. auto se = detail::scope_exit([&] {
  16053. svr.stop();
  16054. t.join();
  16055. ASSERT_FALSE(svr.is_running());
  16056. });
  16057. svr.wait_until_ready();
  16058. Client cli(HOST, port);
  16059. auto res = cli.Get(pattern);
  16060. ASSERT_TRUE(res);
  16061. EXPECT_EQ(StatusCode::OK_200, res->status);
  16062. }
  16063. TEST(ParseUrlTest, VariousPatterns) {
  16064. {
  16065. detail::UrlComponents uc;
  16066. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16067. EXPECT_EQ("http", uc.scheme);
  16068. EXPECT_EQ("example.com", uc.host);
  16069. EXPECT_EQ("8080", uc.port);
  16070. EXPECT_EQ("/path", uc.path);
  16071. EXPECT_EQ("?q=1", uc.query);
  16072. }
  16073. {
  16074. detail::UrlComponents uc;
  16075. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16076. EXPECT_EQ("https", uc.scheme);
  16077. EXPECT_EQ("example.com", uc.host);
  16078. EXPECT_TRUE(uc.port.empty());
  16079. EXPECT_EQ("/path", uc.path);
  16080. }
  16081. {
  16082. detail::UrlComponents uc;
  16083. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16084. EXPECT_EQ("::1", uc.host);
  16085. EXPECT_EQ("8080", uc.port);
  16086. EXPECT_EQ("/path", uc.path);
  16087. }
  16088. {
  16089. detail::UrlComponents uc;
  16090. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16091. }
  16092. {
  16093. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16094. // the path while the connection still targets the bracketed host.
  16095. detail::UrlComponents uc;
  16096. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16097. }
  16098. {
  16099. detail::UrlComponents uc;
  16100. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16101. }
  16102. {
  16103. detail::UrlComponents uc;
  16104. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16105. EXPECT_EQ("::1", uc.host);
  16106. EXPECT_TRUE(uc.port.empty());
  16107. EXPECT_EQ("/path", uc.path);
  16108. }
  16109. {
  16110. detail::UrlComponents uc;
  16111. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16112. EXPECT_TRUE(uc.scheme.empty());
  16113. EXPECT_EQ("example.com", uc.host);
  16114. EXPECT_EQ("/path", uc.path);
  16115. EXPECT_EQ("?q=1", uc.query);
  16116. }
  16117. {
  16118. detail::UrlComponents uc;
  16119. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16120. EXPECT_TRUE(uc.host.empty());
  16121. EXPECT_EQ("/path", uc.path);
  16122. EXPECT_EQ("?q=1", uc.query);
  16123. }
  16124. {
  16125. detail::UrlComponents uc;
  16126. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16127. EXPECT_EQ("example.com", uc.host);
  16128. EXPECT_EQ("8080", uc.port);
  16129. }
  16130. {
  16131. // Unix socket path — must not be parsed as host
  16132. detail::UrlComponents uc;
  16133. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16134. EXPECT_TRUE(uc.host.empty());
  16135. }
  16136. {
  16137. detail::UrlComponents uc;
  16138. ASSERT_TRUE(detail::parse_url("", uc));
  16139. EXPECT_TRUE(uc.host.empty());
  16140. EXPECT_TRUE(uc.path.empty());
  16141. }
  16142. {
  16143. detail::UrlComponents uc;
  16144. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16145. }
  16146. {
  16147. detail::UrlComponents uc;
  16148. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16149. }
  16150. {
  16151. // Accepted by parse_url; callers restrict to http/https
  16152. detail::UrlComponents uc;
  16153. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16154. EXPECT_EQ("ftp", uc.scheme);
  16155. }
  16156. {
  16157. detail::UrlComponents uc;
  16158. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16159. }
  16160. {
  16161. detail::UrlComponents uc;
  16162. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16163. }
  16164. }
  16165. TEST(ParseUrlTest, FragmentHandling) {
  16166. {
  16167. detail::UrlComponents uc;
  16168. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16169. EXPECT_EQ("/path", uc.path);
  16170. EXPECT_TRUE(uc.query.empty());
  16171. }
  16172. {
  16173. detail::UrlComponents uc;
  16174. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16175. EXPECT_TRUE(uc.path.empty());
  16176. EXPECT_TRUE(uc.query.empty());
  16177. }
  16178. }
  16179. TEST(ParseUrlTest, UserinfoHandling) {
  16180. // Userinfo with @ but no colon — host includes @
  16181. detail::UrlComponents uc;
  16182. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  16183. EXPECT_EQ("user@host.com", uc.host);
  16184. EXPECT_EQ("/path", uc.path);
  16185. }
  16186. TEST(ParseUrlTest, IPv6EdgeCases) {
  16187. {
  16188. detail::UrlComponents uc;
  16189. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16190. EXPECT_TRUE(uc.scheme.empty());
  16191. EXPECT_EQ("::1", uc.host);
  16192. EXPECT_EQ("8080", uc.port);
  16193. }
  16194. {
  16195. // Zone ID '%25' is not in [a-fA-F0-9:]
  16196. detail::UrlComponents uc;
  16197. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16198. }
  16199. }
  16200. TEST(ParseUrlTest, SchemeEdgeCases) {
  16201. {
  16202. detail::UrlComponents uc;
  16203. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16204. }
  16205. {
  16206. detail::UrlComponents uc;
  16207. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16208. }
  16209. {
  16210. detail::UrlComponents uc;
  16211. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16212. }
  16213. }
  16214. TEST(ParseUrlTest, PortEdgeCases) {
  16215. {
  16216. detail::UrlComponents uc;
  16217. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16218. EXPECT_TRUE(uc.port.empty());
  16219. EXPECT_EQ("/path", uc.path);
  16220. }
  16221. {
  16222. // parse_url accepts any port string; validation is done by parse_port
  16223. detail::UrlComponents uc;
  16224. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16225. EXPECT_EQ("abc", uc.port);
  16226. }
  16227. }
  16228. TEST(ParseUrlTest, WebSocketPatterns) {
  16229. {
  16230. detail::UrlComponents uc;
  16231. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16232. EXPECT_EQ("ws", uc.scheme);
  16233. EXPECT_EQ("echo.example.com", uc.host);
  16234. EXPECT_EQ("8080", uc.port);
  16235. EXPECT_EQ("/ws", uc.path);
  16236. }
  16237. {
  16238. detail::UrlComponents uc;
  16239. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16240. EXPECT_EQ("wss", uc.scheme);
  16241. EXPECT_EQ("echo.example.com", uc.host);
  16242. EXPECT_TRUE(uc.port.empty());
  16243. EXPECT_EQ("/ws", uc.path);
  16244. }
  16245. }
  16246. TEST(ParseUrlTest, QueryOnly) {
  16247. detail::UrlComponents uc;
  16248. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16249. EXPECT_TRUE(uc.host.empty());
  16250. EXPECT_TRUE(uc.path.empty());
  16251. EXPECT_EQ("?q=1&r=2", uc.query);
  16252. }
  16253. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16254. detail::UrlComponents uc;
  16255. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16256. EXPECT_TRUE(uc.scheme.empty());
  16257. EXPECT_EQ("example.com", uc.host);
  16258. EXPECT_EQ("443", uc.port);
  16259. EXPECT_EQ("/path", uc.path);
  16260. }
  16261. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16262. // If ipv6 regex working, regex match codepath is taken.
  16263. // else port will default to 80 in Client impl
  16264. int clientImplMagicPort = 80;
  16265. int port = 4321;
  16266. // above ports must be different to avoid false negative
  16267. EXPECT_NE(clientImplMagicPort, port);
  16268. std::string ipV6TestURL = "http://[ff06::c3]";
  16269. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16270. CLIENT_PRIVATE_KEY_FILE);
  16271. EXPECT_EQ(cli.port(), port);
  16272. }
  16273. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16274. auto file_path = "./www/dir/index.html";
  16275. auto dir_path = "./www/dir";
  16276. detail::FileStat stat_file(file_path);
  16277. EXPECT_TRUE(stat_file.is_file());
  16278. EXPECT_FALSE(stat_file.is_dir());
  16279. detail::FileStat stat_dir(dir_path);
  16280. EXPECT_FALSE(stat_dir.is_file());
  16281. EXPECT_TRUE(stat_dir.is_dir());
  16282. }
  16283. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16284. // IPv4 with default HTTP port (80)
  16285. EXPECT_EQ("example.com",
  16286. detail::make_host_and_port_string("example.com", 80, false));
  16287. // IPv4 with default HTTPS port (443)
  16288. EXPECT_EQ("example.com",
  16289. detail::make_host_and_port_string("example.com", 443, true));
  16290. // IPv4 with non-default HTTP port
  16291. EXPECT_EQ("example.com:8080",
  16292. detail::make_host_and_port_string("example.com", 8080, false));
  16293. // IPv4 with non-default HTTPS port
  16294. EXPECT_EQ("example.com:8443",
  16295. detail::make_host_and_port_string("example.com", 8443, true));
  16296. // IPv6 with default HTTP port (80)
  16297. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16298. // IPv6 with default HTTPS port (443)
  16299. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16300. // IPv6 with non-default HTTP port
  16301. EXPECT_EQ("[::1]:8080",
  16302. detail::make_host_and_port_string("::1", 8080, false));
  16303. // IPv6 with non-default HTTPS port
  16304. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16305. // IPv6 full address with default port
  16306. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16307. detail::make_host_and_port_string(
  16308. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16309. // IPv6 full address with non-default port
  16310. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16311. detail::make_host_and_port_string(
  16312. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16313. // IPv6 localhost with non-default port
  16314. EXPECT_EQ("[::1]:3000",
  16315. detail::make_host_and_port_string("::1", 3000, false));
  16316. // IPv6 with zone ID (link-local address) with default port
  16317. EXPECT_EQ("[fe80::1%eth0]",
  16318. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16319. // IPv6 with zone ID (link-local address) with non-default port
  16320. EXPECT_EQ("[fe80::1%eth0]:8080",
  16321. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16322. // Edge case: Port 443 with is_ssl=false (should add port)
  16323. EXPECT_EQ("example.com:443",
  16324. detail::make_host_and_port_string("example.com", 443, false));
  16325. // Edge case: Port 80 with is_ssl=true (should add port)
  16326. EXPECT_EQ("example.com:80",
  16327. detail::make_host_and_port_string("example.com", 80, true));
  16328. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16329. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16330. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16331. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16332. // Security fix: Already bracketed IPv6 should not get double brackets
  16333. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16334. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16335. EXPECT_EQ("[::1]:8080",
  16336. detail::make_host_and_port_string("[::1]", 8080, false));
  16337. EXPECT_EQ("[2001:db8::1]:8080",
  16338. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16339. EXPECT_EQ("[fe80::1%eth0]",
  16340. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16341. EXPECT_EQ("[fe80::1%eth0]:8080",
  16342. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16343. // Edge case: Empty host (should return as-is)
  16344. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16345. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16346. // This is a known limitation but shouldn't crash
  16347. EXPECT_EQ("[host:name]",
  16348. detail::make_host_and_port_string("host:name", 80, false));
  16349. // Port number edge cases (no validation, but should not crash)
  16350. EXPECT_EQ("example.com:0",
  16351. detail::make_host_and_port_string("example.com", 0, false));
  16352. EXPECT_EQ("example.com:-1",
  16353. detail::make_host_and_port_string("example.com", -1, false));
  16354. EXPECT_EQ("example.com:65535",
  16355. detail::make_host_and_port_string("example.com", 65535, false));
  16356. EXPECT_EQ("example.com:65536",
  16357. detail::make_host_and_port_string("example.com", 65536, false));
  16358. }
  16359. #ifdef CPPHTTPLIB_SSL_ENABLED
  16360. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16361. httplib::SSLClient cli("roblox.com", 443);
  16362. cli.set_follow_location(true);
  16363. auto res = cli.Get("/");
  16364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16365. EXPECT_EQ(StatusCode::OK_200, res->status);
  16366. }
  16367. #endif
  16368. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16369. Server svr;
  16370. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16371. EXPECT_EQ(res.status, 400);
  16372. });
  16373. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16374. auto se = detail::scope_exit([&] {
  16375. svr.stop();
  16376. thread.join();
  16377. ASSERT_FALSE(svr.is_running());
  16378. });
  16379. svr.wait_until_ready();
  16380. Client cli(HOST, PORT);
  16381. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16382. }
  16383. TEST(InvalidHeaderCharsTest, is_field_name) {
  16384. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16385. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16386. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16387. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16388. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16389. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16390. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16391. EXPECT_FALSE(detail::fields::is_field_name(""));
  16392. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16393. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16394. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16395. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16396. }
  16397. TEST(InvalidHeaderCharsTest, is_field_value) {
  16398. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16399. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16400. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16401. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16402. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16403. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16404. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16405. EXPECT_TRUE(detail::fields::is_field_value(""));
  16406. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16407. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16408. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16409. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16410. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16411. }
  16412. TEST(InvalidHeaderCharsTest, OnServer) {
  16413. Server svr;
  16414. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16415. std::string header = "Not Set";
  16416. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16417. res.set_header(header, "value");
  16418. res.set_content("Page Content Page Content", "text/plain");
  16419. });
  16420. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16421. std::string header = "Not Set";
  16422. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16423. res.set_header("X-Test", header);
  16424. res.set_content("Page Content Page Content", "text/plain");
  16425. });
  16426. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16427. auto se = detail::scope_exit([&] {
  16428. svr.stop();
  16429. thread.join();
  16430. ASSERT_FALSE(svr.is_running());
  16431. });
  16432. svr.wait_until_ready();
  16433. Client cli(HOST, PORT);
  16434. {
  16435. auto res = cli.Get(
  16436. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16438. EXPECT_EQ("Page Content Page Content", res->body);
  16439. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16440. }
  16441. {
  16442. auto res = cli.Get(
  16443. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16445. EXPECT_EQ("Page Content Page Content", res->body);
  16446. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16447. }
  16448. }
  16449. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16450. auto handled = false;
  16451. Server svr;
  16452. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16453. thread t = thread([&] { svr.listen(HOST, PORT); });
  16454. auto se = detail::scope_exit([&] {
  16455. svr.stop();
  16456. t.join();
  16457. ASSERT_FALSE(svr.is_running());
  16458. ASSERT_FALSE(handled);
  16459. });
  16460. svr.wait_until_ready();
  16461. auto req = "POST /test HTTP/1.1\r\n"
  16462. "Content-Length: x\r\n"
  16463. "\r\n";
  16464. std::string response;
  16465. ASSERT_TRUE(send_request(1, req, &response));
  16466. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16467. response.substr(0, response.find("\r\n")));
  16468. }
  16469. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16470. // case-insensitive, and a server that receives a 100-continue expectation in
  16471. // an HTTP/1.0 request MUST ignore it.
  16472. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16473. std::string response;
  16474. ASSERT_TRUE(send_request(1, req, &response, port));
  16475. *got_100 = response.find("100 Continue") != std::string::npos;
  16476. }
  16477. class ExpectTokenTest : public ::testing::Test {
  16478. protected:
  16479. void SetUp() override {
  16480. svr_.Post("/p", [](const Request &, Response &res) {
  16481. res.set_content("ok", "text/plain");
  16482. });
  16483. port_ = svr_.bind_to_any_port(HOST);
  16484. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16485. svr_.wait_until_ready();
  16486. }
  16487. void TearDown() override {
  16488. svr_.stop();
  16489. if (thread_.joinable()) { thread_.join(); }
  16490. }
  16491. std::string request(const char *version, const char *expect_value) const {
  16492. return std::string("POST /p ") + version +
  16493. "\r\n"
  16494. "Host: localhost\r\n"
  16495. "Content-Length: 2\r\n"
  16496. "Connection: close\r\n"
  16497. "Expect: " +
  16498. expect_value +
  16499. "\r\n"
  16500. "\r\n"
  16501. "hi";
  16502. }
  16503. Server svr_;
  16504. int port_ = 0;
  16505. thread thread_;
  16506. };
  16507. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16508. bool got_100 = false;
  16509. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16510. EXPECT_TRUE(got_100);
  16511. }
  16512. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16513. bool got_100 = true;
  16514. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16515. EXPECT_FALSE(got_100);
  16516. }
  16517. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16518. bool got_100 = false;
  16519. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16520. EXPECT_TRUE(got_100);
  16521. }
  16522. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16523. bool got_100 = false;
  16524. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16525. EXPECT_TRUE(got_100);
  16526. }
  16527. // `100 Continue` is sent only when the server starts reading the body, so a
  16528. // request rejected before that never invites the client to send it. The
  16529. // requests below carry the expectation but withhold the body, as a client
  16530. // waiting for `100 Continue` would.
  16531. // A POST that expects `100 Continue` and withholds its two-byte body.
  16532. static std::string expect_headers_only(const std::string &path) {
  16533. return "POST " + path +
  16534. " HTTP/1.1\r\n"
  16535. "Host: localhost\r\n"
  16536. "Content-Length: 2\r\n"
  16537. "Expect: 100-continue\r\n"
  16538. "\r\n";
  16539. }
  16540. class ExpectLazyContinueTest : public ::testing::Test {
  16541. protected:
  16542. void SetUp() override {
  16543. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16544. if (req.path == "/pre-routing") {
  16545. res.status = StatusCode::Unauthorized_401;
  16546. return Server::HandlerResponse::Handled;
  16547. }
  16548. return Server::HandlerResponse::Unhandled;
  16549. });
  16550. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16551. if (req.matched_route == "/pre-request") {
  16552. res.status = StatusCode::Forbidden_403;
  16553. return Server::HandlerResponse::Handled;
  16554. }
  16555. return Server::HandlerResponse::Unhandled;
  16556. });
  16557. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16558. res.set_content("ok", "text/plain");
  16559. });
  16560. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16561. res.set_content("ok", "text/plain");
  16562. });
  16563. svr_.Post("/reader-used", [](const Request &, Response &res,
  16564. const ContentReader &content_reader) {
  16565. std::string body;
  16566. content_reader([&](const char *data, size_t len) {
  16567. body.append(data, len);
  16568. return true;
  16569. });
  16570. res.set_content(body, "text/plain");
  16571. });
  16572. svr_.Post("/reader-unused",
  16573. [](const Request &, Response &res, const ContentReader &) {
  16574. res.set_content("ignored", "text/plain");
  16575. });
  16576. port_ = svr_.bind_to_any_port(HOST);
  16577. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16578. svr_.wait_until_ready();
  16579. }
  16580. void TearDown() override {
  16581. svr_.stop();
  16582. if (thread_.joinable()) { thread_.join(); }
  16583. }
  16584. // Sends `req` and reads until the server closes the connection. Returns
  16585. // false if the read had to wait for the client-side timeout instead.
  16586. bool send_until_closed(const std::string &req, std::string *resp) const {
  16587. auto start = std::chrono::steady_clock::now();
  16588. if (!send_request(3, req, resp, port_)) { return false; }
  16589. auto elapsed = std::chrono::steady_clock::now() - start;
  16590. return elapsed < std::chrono::seconds(2);
  16591. }
  16592. // The final response comes without `100 Continue`, and the server closes
  16593. // the connection since the body may or may not follow.
  16594. void expect_final_without_interim(const std::string &path,
  16595. const char *status_line) const {
  16596. std::string resp;
  16597. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16598. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16599. EXPECT_EQ(0u, resp.find(status_line));
  16600. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16601. }
  16602. Server svr_;
  16603. int port_ = 0;
  16604. thread thread_;
  16605. };
  16606. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16607. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16608. }
  16609. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16610. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16611. }
  16612. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16613. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16614. }
  16615. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16616. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16617. }
  16618. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16619. // The body follows once `100 Continue` has had time to arrive.
  16620. auto req = expect_headers_only("/reader-used");
  16621. req.insert(req.size() - 2, "Connection: close\r\n");
  16622. std::string resp;
  16623. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16624. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  16625. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  16626. EXPECT_NE(std::string::npos, resp.find("hi"));
  16627. }
  16628. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  16629. // Large enough for the client to add `Expect: 100-continue` itself.
  16630. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  16631. std::atomic<bool> body_sent{false};
  16632. Client cli(HOST, port_);
  16633. auto res = cli.Post(
  16634. "/pre-request", length,
  16635. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  16636. body_sent = true;
  16637. std::string chunk(len, 'x');
  16638. sink.write(chunk.data(), chunk.size());
  16639. return true;
  16640. },
  16641. "application/octet-stream");
  16642. ASSERT_TRUE(res);
  16643. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16644. EXPECT_FALSE(body_sent);
  16645. }
  16646. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16647. Server svr;
  16648. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16649. return StatusCode::ExpectationFailed_417;
  16650. });
  16651. svr.Post("/p", [](const Request &, Response &res) {
  16652. res.set_content("ok", "text/plain");
  16653. });
  16654. auto port = svr.bind_to_any_port(HOST);
  16655. thread t = thread([&] { svr.listen_after_bind(); });
  16656. auto se = detail::scope_exit([&] {
  16657. svr.stop();
  16658. t.join();
  16659. });
  16660. svr.wait_until_ready();
  16661. std::string resp;
  16662. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16663. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16664. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16665. // Exactly one response: the route handler must not run after the 417.
  16666. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16667. }
  16668. #ifndef _WIN32
  16669. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16670. static constexpr char reject[] = "Unauthorized";
  16671. static constexpr char accept[] = "Upload accepted";
  16672. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  16673. Server svr;
  16674. svr.set_expect_100_continue_handler(
  16675. [](const Request & /*req*/, Response &res) {
  16676. res.status = StatusCode::Unauthorized_401;
  16677. res.set_content(reject, "text/plain");
  16678. return res.status;
  16679. });
  16680. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  16681. res.set_content(accept, "text/plain");
  16682. });
  16683. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16684. auto se = detail::scope_exit([&] {
  16685. svr.stop();
  16686. thread.join();
  16687. ASSERT_FALSE(svr.is_running());
  16688. });
  16689. svr.wait_until_ready();
  16690. {
  16691. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  16692. curl_easy_init(), &curl_easy_cleanup};
  16693. ASSERT_NE(curl, nullptr);
  16694. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  16695. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  16696. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  16697. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  16698. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  16699. &curl_slist_free_all};
  16700. ASSERT_NE(list, nullptr);
  16701. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  16702. struct read_data {
  16703. size_t read_size;
  16704. size_t total_size;
  16705. } data = {0, total_size};
  16706. using read_callback_t =
  16707. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16708. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  16709. void *userdata) -> size_t {
  16710. read_data *d = (read_data *)userdata;
  16711. if (!userdata || d->read_size >= d->total_size) { return 0; }
  16712. std::fill_n(ptr, size * nmemb, 'A');
  16713. d->read_size += size * nmemb;
  16714. return size * nmemb;
  16715. };
  16716. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  16717. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  16718. std::vector<char> buffer;
  16719. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  16720. using write_callback_t =
  16721. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16722. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  16723. void *userdata) -> size_t {
  16724. std::vector<char> *buf = (std::vector<char> *)userdata;
  16725. buf->reserve(buf->size() + size * nmemb + 1);
  16726. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  16727. return size * nmemb;
  16728. };
  16729. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  16730. {
  16731. const auto res = curl_easy_perform(curl.get());
  16732. ASSERT_EQ(res, CURLE_OK);
  16733. }
  16734. {
  16735. auto response_code = long{};
  16736. const auto res =
  16737. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  16738. ASSERT_EQ(res, CURLE_OK);
  16739. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  16740. }
  16741. {
  16742. auto dl = curl_off_t{};
  16743. const auto res =
  16744. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  16745. ASSERT_EQ(res, CURLE_OK);
  16746. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  16747. }
  16748. {
  16749. buffer.push_back('\0');
  16750. ASSERT_STRCASEEQ(buffer.data(), reject);
  16751. }
  16752. }
  16753. }
  16754. #endif
  16755. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  16756. // Regression test for #2458.
  16757. //
  16758. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  16759. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  16760. // ticket can make the client socket spuriously readable during the
  16761. // 100-continue wait. If the readiness is mistaken for an incoming response,
  16762. // the client withholds the body and then blocks reading a response that never
  16763. // comes, failing with `Failed to read connection`.
  16764. //
  16765. // A correct client (like curl) sends the body once no `100 Continue` arrives
  16766. // within the timeout. This raw OpenSSL server deliberately never sends
  16767. // `100 Continue`; the client must still deliver the body and receive 200.
  16768. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  16769. signal(SIGPIPE, SIG_IGN);
  16770. const auto port = PORT + 4;
  16771. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16772. ASSERT_NE(srv, INVALID_SOCKET);
  16773. int opt = 1;
  16774. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  16775. sockaddr_in addr{};
  16776. addr.sin_family = AF_INET;
  16777. addr.sin_port = htons(static_cast<uint16_t>(port));
  16778. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16779. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16780. ASSERT_EQ(0, ::listen(srv, 1));
  16781. std::atomic<size_t> server_body_bytes{0};
  16782. auto server_thread = std::thread([&] {
  16783. sockaddr_in cli_addr{};
  16784. socklen_t cli_len = sizeof(cli_addr);
  16785. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16786. if (cli == INVALID_SOCKET) { return; }
  16787. // Bound the lifetime of the server side so a buggy client (which never
  16788. // sends the body) cannot make this thread block forever on join.
  16789. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  16790. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16791. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  16792. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  16793. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  16794. SSL *ssl = SSL_new(ctx);
  16795. SSL_set_fd(ssl, static_cast<int>(cli));
  16796. if (SSL_accept(ssl) > 0) {
  16797. // Read the request headers. Reading here also flushes the TLS 1.3
  16798. // session tickets to the client. Deliberately do NOT send
  16799. // `100 Continue`.
  16800. std::string buf;
  16801. char tmp[1024];
  16802. while (buf.find("\r\n\r\n") == std::string::npos) {
  16803. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16804. if (n <= 0) { break; }
  16805. buf.append(tmp, static_cast<size_t>(n));
  16806. }
  16807. // A correct client sends the body now; count what arrives.
  16808. auto pos = buf.find("\r\n\r\n");
  16809. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  16810. while (body < 4096) {
  16811. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16812. if (n <= 0) { break; }
  16813. body += static_cast<size_t>(n);
  16814. }
  16815. server_body_bytes = body;
  16816. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  16817. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  16818. SSL_shutdown(ssl);
  16819. }
  16820. SSL_free(ssl);
  16821. detail::close_socket(cli);
  16822. SSL_CTX_free(ctx);
  16823. });
  16824. auto se = detail::scope_exit([&] {
  16825. server_thread.join();
  16826. detail::close_socket(srv);
  16827. });
  16828. SSLClient cli("127.0.0.1", port);
  16829. cli.enable_server_certificate_verification(false);
  16830. cli.set_connection_timeout(5, 0);
  16831. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  16832. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  16833. std::string body(4096, 'A');
  16834. auto res = cli.Put("/api/test", body, "application/json");
  16835. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  16836. EXPECT_EQ(StatusCode::OK_200, res->status);
  16837. EXPECT_EQ(body.size(), server_body_bytes.load());
  16838. }
  16839. #endif
  16840. template <typename S, typename C>
  16841. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  16842. svr.Get("/stream", [&](const Request &, Response &res) {
  16843. auto data = new std::string("01234567890123456789");
  16844. res.set_content_provider(
  16845. data->size(), "text/plain",
  16846. [&, data](size_t offset, size_t length, DataSink &sink) {
  16847. const size_t DATA_CHUNK_SIZE = 4;
  16848. const auto &d = *data;
  16849. std::this_thread::sleep_for(std::chrono::seconds(1));
  16850. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  16851. return true;
  16852. },
  16853. [data](bool success) {
  16854. EXPECT_FALSE(success);
  16855. delete data;
  16856. });
  16857. });
  16858. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  16859. auto i = new size_t(0);
  16860. res.set_content_provider(
  16861. "text/plain",
  16862. [i](size_t, DataSink &sink) {
  16863. if (*i < 5) {
  16864. std::this_thread::sleep_for(std::chrono::seconds(1));
  16865. sink.write("abcd", 4);
  16866. (*i)++;
  16867. } else {
  16868. sink.done();
  16869. }
  16870. return true;
  16871. },
  16872. [i](bool success) {
  16873. EXPECT_FALSE(success);
  16874. delete i;
  16875. });
  16876. });
  16877. svr.Get("/chunked", [&](const Request &, Response &res) {
  16878. auto i = new size_t(0);
  16879. res.set_chunked_content_provider(
  16880. "text/plain",
  16881. [i](size_t, DataSink &sink) {
  16882. if (*i < 5) {
  16883. std::this_thread::sleep_for(std::chrono::seconds(1));
  16884. sink.os << "abcd";
  16885. (*i)++;
  16886. } else {
  16887. sink.done();
  16888. }
  16889. return true;
  16890. },
  16891. [i](bool success) {
  16892. EXPECT_FALSE(success);
  16893. delete i;
  16894. });
  16895. });
  16896. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16897. auto se = detail::scope_exit([&] {
  16898. svr.stop();
  16899. listen_thread.join();
  16900. ASSERT_FALSE(svr.is_running());
  16901. });
  16902. svr.wait_until_ready();
  16903. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  16904. {
  16905. auto start = std::chrono::steady_clock::now();
  16906. auto res = cli.Get("/stream");
  16907. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16908. std::chrono::steady_clock::now() - start)
  16909. .count();
  16910. ASSERT_FALSE(res);
  16911. EXPECT_EQ(Error::Read, res.error());
  16912. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16913. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16914. }
  16915. {
  16916. auto start = std::chrono::steady_clock::now();
  16917. auto res = cli.Get("/stream_without_length");
  16918. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16919. std::chrono::steady_clock::now() - start)
  16920. .count();
  16921. ASSERT_FALSE(res);
  16922. EXPECT_EQ(Error::Read, res.error());
  16923. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16924. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16925. }
  16926. {
  16927. auto start = std::chrono::steady_clock::now();
  16928. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  16929. EXPECT_EQ("abcd", string(data, data_length));
  16930. return true;
  16931. });
  16932. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16933. std::chrono::steady_clock::now() - start)
  16934. .count();
  16935. ASSERT_FALSE(res);
  16936. EXPECT_EQ(Error::Read, res.error());
  16937. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16938. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16939. }
  16940. }
  16941. TEST(MaxTimeoutTest, ContentStream) {
  16942. time_t timeout = 2000;
  16943. time_t threshold = 200;
  16944. Server svr;
  16945. Client cli("localhost", PORT);
  16946. max_timeout_test(svr, cli, timeout, threshold);
  16947. }
  16948. #ifdef CPPHTTPLIB_SSL_ENABLED
  16949. TEST(MaxTimeoutTest, ContentStreamSSL) {
  16950. time_t timeout = 2000;
  16951. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  16952. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16953. SSLClient cli("localhost", PORT);
  16954. cli.enable_server_certificate_verification(false);
  16955. max_timeout_test(svr, cli, timeout, threshold);
  16956. }
  16957. #endif
  16958. class EventDispatcher {
  16959. public:
  16960. EventDispatcher() {}
  16961. bool wait_event(DataSink *sink) {
  16962. unique_lock<mutex> lk(m_);
  16963. int id = id_;
  16964. // Wait with timeout to prevent hanging if client disconnects
  16965. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  16966. [&] { return cid_ == id; })) {
  16967. return false; // Timeout occurred
  16968. }
  16969. sink->write(message_.data(), message_.size());
  16970. return true;
  16971. }
  16972. void send_event(const string &message) {
  16973. lock_guard<mutex> lk(m_);
  16974. cid_ = id_++;
  16975. message_ = message;
  16976. cv_.notify_all();
  16977. }
  16978. private:
  16979. mutex m_;
  16980. condition_variable cv_;
  16981. atomic_int id_{0};
  16982. atomic_int cid_{-1};
  16983. string message_;
  16984. };
  16985. TEST(ClientInThreadTest, Issue2068) {
  16986. EventDispatcher ed;
  16987. Server svr;
  16988. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  16989. res.set_chunked_content_provider("text/event-stream",
  16990. [&](size_t /*offset*/, DataSink &sink) {
  16991. return ed.wait_event(&sink);
  16992. });
  16993. });
  16994. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  16995. svr.wait_until_ready();
  16996. thread event_thread([&] {
  16997. int id = 0;
  16998. while (svr.is_running()) {
  16999. this_thread::sleep_for(chrono::milliseconds(500));
  17000. std::stringstream ss;
  17001. ss << "data: " << id << "\n\n";
  17002. ed.send_event(ss.str());
  17003. id++;
  17004. }
  17005. });
  17006. auto se = detail::scope_exit([&] {
  17007. svr.stop();
  17008. listen_thread.join();
  17009. event_thread.join();
  17010. ASSERT_FALSE(svr.is_running());
  17011. });
  17012. {
  17013. auto client = detail::make_unique<Client>(HOST, PORT);
  17014. client->set_read_timeout(std::chrono::minutes(10));
  17015. std::atomic<bool> stop{false};
  17016. std::thread t([&] {
  17017. client->Get("/event1",
  17018. [&](const char *, size_t) -> bool { return !stop; });
  17019. });
  17020. std::this_thread::sleep_for(std::chrono::seconds(2));
  17021. stop = true;
  17022. client->stop();
  17023. t.join();
  17024. // Reset client after thread has finished
  17025. client.reset();
  17026. }
  17027. }
  17028. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17029. auto handled = false;
  17030. Server svr;
  17031. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17032. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17033. auto se = detail::scope_exit([&] {
  17034. svr.stop();
  17035. t.join();
  17036. ASSERT_FALSE(svr.is_running());
  17037. ASSERT_FALSE(handled);
  17038. });
  17039. svr.wait_until_ready();
  17040. // Two Content-Length headers with different values — must be rejected
  17041. auto req = "POST /test HTTP/1.1\r\n"
  17042. "Content-Length: 5\r\n"
  17043. "Content-Length: 10\r\n"
  17044. "\r\n"
  17045. "hello";
  17046. std::string response;
  17047. ASSERT_TRUE(send_request(1, req, &response));
  17048. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17049. response.substr(0, response.find("\r\n")));
  17050. }
  17051. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17052. auto handled = false;
  17053. Server svr;
  17054. svr.Post("/test", [&](const Request &, Response &res) {
  17055. handled = true;
  17056. res.set_content("ok", "text/plain");
  17057. });
  17058. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17059. auto se = detail::scope_exit([&] {
  17060. svr.stop();
  17061. t.join();
  17062. ASSERT_FALSE(svr.is_running());
  17063. ASSERT_TRUE(handled);
  17064. });
  17065. svr.wait_until_ready();
  17066. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17067. auto req = "POST /test HTTP/1.1\r\n"
  17068. "Content-Length: 5\r\n"
  17069. "Content-Length: 5\r\n"
  17070. "\r\n"
  17071. "hello";
  17072. std::string response;
  17073. ASSERT_TRUE(send_request(1, req, &response));
  17074. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17075. }
  17076. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17077. Server svr;
  17078. svr.Get("/test", [](const Request &, Response &res) {
  17079. res.set_content("ok", "text/plain");
  17080. });
  17081. auto port = svr.bind_to_any_port(HOST);
  17082. thread t = thread([&] { svr.listen_after_bind(); });
  17083. auto se = detail::scope_exit([&] {
  17084. svr.stop();
  17085. t.join();
  17086. ASSERT_FALSE(svr.is_running());
  17087. });
  17088. svr.wait_until_ready();
  17089. auto status_line = [&](const std::string &host_lines) {
  17090. std::string res;
  17091. send_request(
  17092. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17093. &res, port);
  17094. return res.substr(0, res.find("\r\n"));
  17095. };
  17096. const char *accepted[] = {
  17097. "Host: localhost\r\n",
  17098. "Host: a.example:8080\r\n",
  17099. "Host: my_service\r\n",
  17100. "Host: [::1]:8080\r\n",
  17101. "Host: [fe80::1%25eth0]\r\n",
  17102. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17103. };
  17104. for (auto host_lines : accepted) {
  17105. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17106. }
  17107. const char *rejected[] = {
  17108. "Host: a.example\r\nHost: b.example\r\n",
  17109. "Host: a.example\r\nHost: a.example\r\n",
  17110. "Host: a@b.example\r\n",
  17111. "Host: a.example/b\r\n",
  17112. "Host: a.example\\b\r\n",
  17113. "Host: a.example?b\r\n",
  17114. "Host: a.example#b\r\n",
  17115. "Host: a.example b.example\r\n",
  17116. };
  17117. for (auto host_lines : rejected) {
  17118. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17119. << host_lines;
  17120. }
  17121. }
  17122. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17123. Server svr;
  17124. svr.Get("/", [](const Request &req, Response &res) {
  17125. EXPECT_EQ(2U, req.trailers.size());
  17126. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17127. // Denied
  17128. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17129. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17130. // Accepted
  17131. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17132. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17133. EXPECT_TRUE(req.has_trailer("X-World"));
  17134. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17135. res.set_content("ok", "text/plain");
  17136. });
  17137. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17138. auto se = detail::scope_exit([&] {
  17139. svr.stop();
  17140. t.join();
  17141. ASSERT_FALSE(svr.is_running());
  17142. });
  17143. svr.wait_until_ready();
  17144. const std::string req = "GET / HTTP/1.1\r\n"
  17145. "Transfer-Encoding: chunked\r\n"
  17146. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17147. "\r\n"
  17148. "0\r\n"
  17149. "Content-Length: 10\r\n"
  17150. "Host: internal.local\r\n"
  17151. "Content-Type: malicious/content\r\n"
  17152. "Cookie: any\r\n"
  17153. "Set-Cookie: any\r\n"
  17154. "X-Forwarded-For: attacker.com\r\n"
  17155. "X-Real-Ip: 1.1.1.1\r\n"
  17156. "X-Hello: hello\r\n"
  17157. "X-World: world\r\n"
  17158. "\r\n";
  17159. std::string res;
  17160. ASSERT_TRUE(send_request(1, req, &res));
  17161. }
  17162. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17163. // several field lines, and the combined value is what has to be parsed. A
  17164. // Trailer field split across lines therefore declares every name it lists;
  17165. // reading only the first line silently drops the trailers the later lines
  17166. // declare. The prohibited-trailer filter still applies to every line.
  17167. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17168. Server svr;
  17169. size_t observed_trailer_count = 0;
  17170. std::string observed_hello;
  17171. std::string observed_world;
  17172. bool observed_content_length = true;
  17173. svr.Get("/", [&](const Request &req, Response &res) {
  17174. observed_trailer_count = req.trailers.size();
  17175. observed_hello = req.get_trailer_value("X-Hello");
  17176. observed_world = req.get_trailer_value("X-World");
  17177. observed_content_length = req.has_trailer("Content-Length");
  17178. res.set_content("ok", "text/plain");
  17179. });
  17180. auto port = svr.bind_to_any_port(HOST);
  17181. thread t = thread([&]() { svr.listen_after_bind(); });
  17182. auto se = detail::scope_exit([&] {
  17183. svr.stop();
  17184. t.join();
  17185. ASSERT_FALSE(svr.is_running());
  17186. });
  17187. svr.wait_until_ready();
  17188. const std::string req = "GET / HTTP/1.1\r\n"
  17189. "Transfer-Encoding: chunked\r\n"
  17190. "Trailer: X-Hello\r\n"
  17191. "Trailer: X-World, Content-Length\r\n"
  17192. "\r\n"
  17193. "0\r\n"
  17194. "X-Hello: hello\r\n"
  17195. "X-World: world\r\n"
  17196. "Content-Length: 10\r\n"
  17197. "\r\n";
  17198. std::string res;
  17199. ASSERT_TRUE(send_request(1, req, &res, port));
  17200. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17201. // Accepted: both field lines contribute to the declared set
  17202. EXPECT_EQ(2U, observed_trailer_count);
  17203. EXPECT_EQ(observed_hello, "hello");
  17204. EXPECT_EQ(observed_world, "world");
  17205. // Denied: a prohibited name stays prohibited on a later field line
  17206. EXPECT_FALSE(observed_content_length);
  17207. }
  17208. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17209. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17210. // unbounded run of fields that are never declared, because the counter would
  17211. // only advance for declared fields.
  17212. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17213. Server svr;
  17214. bool handler_called = false;
  17215. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17216. handler_called = true;
  17217. res.set_content("ok", "text/plain");
  17218. });
  17219. auto port = svr.bind_to_any_port(HOST);
  17220. thread t = thread([&]() { svr.listen_after_bind(); });
  17221. auto se = detail::scope_exit([&] {
  17222. svr.stop();
  17223. t.join();
  17224. ASSERT_FALSE(svr.is_running());
  17225. });
  17226. svr.wait_until_ready();
  17227. // Declare nothing, then send far more undeclared trailer fields than the
  17228. // header-count limit. Parsing must stop and reject the request rather than
  17229. // read every line.
  17230. std::string req = "GET / HTTP/1.1\r\n"
  17231. "Transfer-Encoding: chunked\r\n"
  17232. "\r\n"
  17233. "0\r\n";
  17234. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17235. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17236. }
  17237. req += "\r\n";
  17238. std::string res;
  17239. ASSERT_TRUE(send_request(1, req, &res, port));
  17240. // The request is rejected before the handler runs.
  17241. EXPECT_FALSE(handler_called);
  17242. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17243. }
  17244. // The set of declared trailer names is capped so a peer cannot grow it without
  17245. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17246. // declared past the cap is not honored, even if the field is actually sent.
  17247. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17248. Server svr;
  17249. // One name inside the cap and one past it, so the test tracks the cap rather
  17250. // than a fixed count.
  17251. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17252. const std::string within_cap_name = "X-T-0";
  17253. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17254. bool observed_within_cap = false;
  17255. bool observed_past_cap = false;
  17256. svr.Get("/", [&](const Request &req, Response &res) {
  17257. observed_within_cap = req.has_trailer(within_cap_name);
  17258. observed_past_cap = req.has_trailer(past_cap_name);
  17259. res.set_content("ok", "text/plain");
  17260. });
  17261. auto port = svr.bind_to_any_port(HOST);
  17262. thread t = thread([&]() { svr.listen_after_bind(); });
  17263. auto se = detail::scope_exit([&] {
  17264. svr.stop();
  17265. t.join();
  17266. ASSERT_FALSE(svr.is_running());
  17267. });
  17268. svr.wait_until_ready();
  17269. // Declare more trailer names than the cap in a single Trailer field, then
  17270. // actually send the first (within the cap) and the last (past it).
  17271. std::string trailer_decl = "Trailer: ";
  17272. for (int i = 0; i < declared_count; i++) {
  17273. if (i != 0) { trailer_decl += ", "; }
  17274. trailer_decl += "X-T-" + std::to_string(i);
  17275. }
  17276. trailer_decl += "\r\n";
  17277. const std::string req = "GET / HTTP/1.1\r\n"
  17278. "Transfer-Encoding: chunked\r\n" +
  17279. trailer_decl +
  17280. "\r\n"
  17281. "0\r\n" +
  17282. within_cap_name + ": a\r\n" + past_cap_name +
  17283. ": b\r\n"
  17284. "\r\n";
  17285. std::string res;
  17286. ASSERT_TRUE(send_request(1, req, &res, port));
  17287. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17288. // A name within the cap is honored; one declared past the cap is dropped.
  17289. EXPECT_TRUE(observed_within_cap);
  17290. EXPECT_FALSE(observed_past_cap);
  17291. }
  17292. // A direct client that is not listed in trusted_proxies must not be able to
  17293. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17294. // the peer address on the actual TCP connection determines whether the
  17295. // header is honored.
  17296. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17297. Server svr;
  17298. // Deliberately does NOT include the loopback address the test client
  17299. // actually connects from, so the direct connection is not a trusted proxy.
  17300. svr.set_trusted_proxies({"203.0.113.66"});
  17301. std::string observed_remote_addr;
  17302. svr.Get("/ip", [&](const Request &req, Response &res) {
  17303. observed_remote_addr = req.remote_addr;
  17304. res.set_content("ok", "text/plain");
  17305. });
  17306. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17307. auto se = detail::scope_exit([&] {
  17308. svr.stop();
  17309. t.join();
  17310. ASSERT_FALSE(svr.is_running());
  17311. });
  17312. svr.wait_until_ready();
  17313. Client cli(HOST, PORT);
  17314. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17316. EXPECT_EQ(StatusCode::OK_200, res->status);
  17317. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17318. // ignored entirely and the real connection-level address retained.
  17319. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17320. observed_remote_addr == "127.0.0.1");
  17321. }
  17322. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17323. Server svr;
  17324. std::string observed_remote_addr;
  17325. std::string observed_xff;
  17326. svr.Get("/ip", [&](const Request &req, Response &res) {
  17327. observed_remote_addr = req.remote_addr;
  17328. observed_xff = req.get_header_value("X-Forwarded-For");
  17329. res.set_content("ok", "text/plain");
  17330. });
  17331. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17332. auto se = detail::scope_exit([&] {
  17333. svr.stop();
  17334. t.join();
  17335. ASSERT_FALSE(svr.is_running());
  17336. });
  17337. svr.wait_until_ready();
  17338. Client cli(HOST, PORT);
  17339. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17341. EXPECT_EQ(StatusCode::OK_200, res->status);
  17342. EXPECT_EQ(observed_xff, "203.0.113.66");
  17343. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17344. observed_remote_addr == "127.0.0.1");
  17345. }
  17346. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17347. Server svr;
  17348. svr.set_trusted_proxies({"203.0.113.66"});
  17349. std::string observed_remote_addr;
  17350. std::string observed_xff;
  17351. svr.Get("/ip", [&](const Request &req, Response &res) {
  17352. observed_remote_addr = req.remote_addr;
  17353. observed_xff = req.get_header_value("X-Forwarded-For");
  17354. res.set_content("ok", "text/plain");
  17355. });
  17356. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17357. auto se = detail::scope_exit([&] {
  17358. svr.stop();
  17359. t.join();
  17360. ASSERT_FALSE(svr.is_running());
  17361. });
  17362. svr.wait_until_ready();
  17363. Client cli(HOST, PORT);
  17364. auto res = cli.Get("/ip");
  17365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17366. EXPECT_EQ(StatusCode::OK_200, res->status);
  17367. EXPECT_EQ(observed_xff, "");
  17368. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17369. observed_remote_addr == "127.0.0.1");
  17370. }
  17371. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17372. Server svr;
  17373. // Include the loopback address the test client actually connects from, so
  17374. // the direct connection itself is recognized as the trusted proxy hop.
  17375. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17376. std::string observed_remote_addr;
  17377. std::string observed_xff;
  17378. svr.Get("/ip", [&](const Request &req, Response &res) {
  17379. observed_remote_addr = req.remote_addr;
  17380. observed_xff = req.get_header_value("X-Forwarded-For");
  17381. res.set_content("ok", "text/plain");
  17382. });
  17383. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17384. auto se = detail::scope_exit([&] {
  17385. svr.stop();
  17386. t.join();
  17387. ASSERT_FALSE(svr.is_running());
  17388. });
  17389. svr.wait_until_ready();
  17390. Client cli(HOST, PORT);
  17391. auto res = cli.Get(
  17392. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17394. EXPECT_EQ(StatusCode::OK_200, res->status);
  17395. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17396. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17397. }
  17398. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17399. Server svr;
  17400. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17401. std::string observed_remote_addr;
  17402. std::string observed_xff;
  17403. svr.Get("/ip", [&](const Request &req, Response &res) {
  17404. observed_remote_addr = req.remote_addr;
  17405. observed_xff = req.get_header_value("X-Forwarded-For");
  17406. res.set_content("ok", "text/plain");
  17407. });
  17408. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17409. auto se = detail::scope_exit([&] {
  17410. svr.stop();
  17411. t.join();
  17412. ASSERT_FALSE(svr.is_running());
  17413. });
  17414. svr.wait_until_ready();
  17415. Client cli(HOST, PORT);
  17416. auto res = cli.Get(
  17417. "/ip",
  17418. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17420. EXPECT_EQ(StatusCode::OK_200, res->status);
  17421. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17422. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17423. }
  17424. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17425. Server svr;
  17426. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17427. std::string observed_remote_addr;
  17428. std::string observed_xff;
  17429. svr.Get("/ip", [&](const Request &req, Response &res) {
  17430. observed_remote_addr = req.remote_addr;
  17431. observed_xff = req.get_header_value("X-Forwarded-For");
  17432. res.set_content("ok", "text/plain");
  17433. });
  17434. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17435. auto se = detail::scope_exit([&] {
  17436. svr.stop();
  17437. t.join();
  17438. ASSERT_FALSE(svr.is_running());
  17439. });
  17440. svr.wait_until_ready();
  17441. Client cli(HOST, PORT);
  17442. auto res = cli.Get(
  17443. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17445. EXPECT_EQ(StatusCode::OK_200, res->status);
  17446. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17447. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17448. // and must not be selected.
  17449. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17450. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17451. }
  17452. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17453. Server svr;
  17454. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17455. std::string observed_remote_addr;
  17456. svr.Get("/ip", [&](const Request &req, Response &res) {
  17457. observed_remote_addr = req.remote_addr;
  17458. res.set_content("ok", "text/plain");
  17459. });
  17460. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17461. auto se = detail::scope_exit([&] {
  17462. svr.stop();
  17463. t.join();
  17464. ASSERT_FALSE(svr.is_running());
  17465. });
  17466. svr.wait_until_ready();
  17467. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17468. // a forged address and the trusted proxy's own address; the forged value must
  17469. // not win over the address the trusted proxy actually recorded.
  17470. Client cli(HOST, PORT);
  17471. auto res = cli.Get(
  17472. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17474. EXPECT_EQ(StatusCode::OK_200, res->status);
  17475. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17476. }
  17477. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17478. Server svr;
  17479. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17480. std::string observed_remote_addr;
  17481. std::string observed_xff;
  17482. svr.Get("/ip", [&](const Request &req, Response &res) {
  17483. observed_remote_addr = req.remote_addr;
  17484. observed_xff = req.get_header_value("X-Forwarded-For");
  17485. res.set_content("ok", "text/plain");
  17486. });
  17487. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17488. auto se = detail::scope_exit([&] {
  17489. svr.stop();
  17490. t.join();
  17491. ASSERT_FALSE(svr.is_running());
  17492. });
  17493. svr.wait_until_ready();
  17494. Client cli(HOST, PORT);
  17495. auto res = cli.Get(
  17496. "/ip",
  17497. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17499. EXPECT_EQ(StatusCode::OK_200, res->status);
  17500. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17501. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17502. }
  17503. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17504. Server svr;
  17505. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17506. std::string observed_remote_addr;
  17507. std::string observed_xff;
  17508. svr.Get("/ip", [&](const Request &req, Response &res) {
  17509. observed_remote_addr = req.remote_addr;
  17510. observed_xff = req.get_header_value("X-Forwarded-For");
  17511. res.set_content("ok", "text/plain");
  17512. });
  17513. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17514. auto se = detail::scope_exit([&] {
  17515. svr.stop();
  17516. t.join();
  17517. ASSERT_FALSE(svr.is_running());
  17518. });
  17519. svr.wait_until_ready();
  17520. std::string raw_req =
  17521. "GET /ip HTTP/1.1\r\n"
  17522. "Host: localhost\r\n"
  17523. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17524. "Connection: close\r\n"
  17525. "\r\n";
  17526. std::string out;
  17527. ASSERT_TRUE(send_request(5, raw_req, &out));
  17528. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17529. // Header parser trims surrounding whitespace of the header value
  17530. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17531. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17532. }
  17533. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17534. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17535. // their own X-Forwarded-For as a separate field line rather than extending the
  17536. // one the client sent, so every occurrence has to be taken into account.
  17537. // Reading only the first one hands back the address the client chose.
  17538. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17539. Server svr;
  17540. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17541. std::string observed_remote_addr;
  17542. size_t observed_xff_count = 0;
  17543. svr.Get("/ip", [&](const Request &req, Response &res) {
  17544. observed_remote_addr = req.remote_addr;
  17545. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17546. res.set_content("ok", "text/plain");
  17547. });
  17548. auto port = svr.bind_to_any_port(HOST);
  17549. thread t = thread([&]() { svr.listen_after_bind(); });
  17550. auto se = detail::scope_exit([&] {
  17551. svr.stop();
  17552. t.join();
  17553. ASSERT_FALSE(svr.is_running());
  17554. });
  17555. svr.wait_until_ready();
  17556. // The client supplies the first field line; the trusted proxy appends the
  17557. // address it observed as a second one.
  17558. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17559. "Host: localhost\r\n"
  17560. "X-Forwarded-For: 1.2.3.4\r\n"
  17561. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17562. "Connection: close\r\n"
  17563. "\r\n";
  17564. std::string out;
  17565. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17566. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17567. EXPECT_EQ(observed_xff_count, 2U);
  17568. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17569. // The same chain spread over one field line per hop derives the same client
  17570. // address, i.e. the split and the comma-joined representations agree.
  17571. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17572. "Host: localhost\r\n"
  17573. "X-Forwarded-For: 1.2.3.4\r\n"
  17574. "X-Forwarded-For: 198.51.100.23\r\n"
  17575. "X-Forwarded-For: 192.0.2.45\r\n"
  17576. "Connection: close\r\n"
  17577. "\r\n";
  17578. out.clear();
  17579. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17580. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17581. EXPECT_EQ(observed_xff_count, 3U);
  17582. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17583. }
  17584. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17585. // crash the server (it used to call front() on an empty vector inside
  17586. // get_client_ip). The connection-level remote address must be retained instead.
  17587. static void run_malformed_xff_test(const std::string &xff_value) {
  17588. Server svr;
  17589. svr.set_trusted_proxies({"192.0.2.45"});
  17590. std::string observed_remote_addr;
  17591. svr.Get("/ip", [&](const Request &req, Response &res) {
  17592. observed_remote_addr = req.remote_addr;
  17593. res.set_content("ok", "text/plain");
  17594. });
  17595. int port = 0;
  17596. thread t = thread([&]() {
  17597. port = svr.bind_to_any_port(HOST);
  17598. svr.listen_after_bind();
  17599. });
  17600. auto se = detail::scope_exit([&] {
  17601. svr.stop();
  17602. t.join();
  17603. ASSERT_FALSE(svr.is_running());
  17604. });
  17605. svr.wait_until_ready();
  17606. Client cli(HOST, port);
  17607. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17609. EXPECT_EQ(StatusCode::OK_200, res->status);
  17610. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17611. observed_remote_addr == "127.0.0.1");
  17612. }
  17613. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  17614. run_malformed_xff_test("");
  17615. }
  17616. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  17617. run_malformed_xff_test(",");
  17618. }
  17619. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  17620. run_malformed_xff_test(", , ,");
  17621. }
  17622. // The same rule applies to Accept: a request whose acceptable types are spread
  17623. // over several field lines must be negotiated against all of them.
  17624. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  17625. // case-insensitive connection options. Comparing the whole field value against
  17626. // one option misses a client that sends several of them, and misses every
  17627. // casing but the one written in the comparison.
  17628. //
  17629. // Sends req, reads the response, then reuses the same socket for a second
  17630. // request to find out whether the server kept the connection.
  17631. static void probe_connection_reuse(int port, const std::string &req,
  17632. bool *announced_close, bool *reusable) {
  17633. auto error = Error::Success;
  17634. auto sock = detail::create_client_socket(
  17635. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17636. /*connection_timeout_sec=*/5, 0,
  17637. /*read_timeout_sec=*/1, 0,
  17638. /*write_timeout_sec=*/5, 0, std::string(), error);
  17639. ASSERT_NE(sock, INVALID_SOCKET);
  17640. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  17641. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  17642. "Host: localhost\r\n"
  17643. "Connection: close\r\n"
  17644. "\r\n";
  17645. std::string first_response;
  17646. std::string second_response;
  17647. detail::process_client_socket(
  17648. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  17649. [&](Stream &strm) {
  17650. if (strm.write(req.data(), req.size()) !=
  17651. static_cast<ssize_t>(req.size())) {
  17652. return false;
  17653. }
  17654. char buf[512];
  17655. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  17656. // Headers plus the two-byte body of the handler below
  17657. while (reader.getline()) {
  17658. first_response += reader.ptr();
  17659. if (first_response.find("ok") != std::string::npos) { break; }
  17660. }
  17661. if (strm.write(second.data(), second.size()) !=
  17662. static_cast<ssize_t>(second.size())) {
  17663. return true;
  17664. }
  17665. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  17666. while (reader2.getline()) {
  17667. second_response += reader2.ptr();
  17668. if (second_response.find("ok") != std::string::npos) { break; }
  17669. }
  17670. return true;
  17671. });
  17672. *announced_close =
  17673. first_response.find("Connection: close") != std::string::npos;
  17674. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  17675. }
  17676. class ConnectionTokenTest : public ::testing::Test {
  17677. protected:
  17678. void SetUp() override {
  17679. svr_.Get("/keepalive", [](const Request &, Response &res) {
  17680. res.set_content("ok", "text/plain");
  17681. });
  17682. port_ = svr_.bind_to_any_port(HOST);
  17683. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17684. svr_.wait_until_ready();
  17685. }
  17686. void TearDown() override {
  17687. svr_.stop();
  17688. if (thread_.joinable()) { thread_.join(); }
  17689. }
  17690. Server svr_;
  17691. int port_ = 0;
  17692. thread thread_;
  17693. };
  17694. // "close" alongside another option still closes the connection, and the
  17695. // response says so rather than leaving the peer to discover it.
  17696. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  17697. bool announced_close = false;
  17698. bool reusable = true;
  17699. probe_connection_reuse(port_,
  17700. "GET /keepalive HTTP/1.1\r\n"
  17701. "Host: localhost\r\n"
  17702. "Connection: keep-alive, close\r\n"
  17703. "\r\n",
  17704. &announced_close, &reusable);
  17705. EXPECT_TRUE(announced_close);
  17706. EXPECT_FALSE(reusable);
  17707. }
  17708. // "close" split over two field lines is the same list, so it is honored too.
  17709. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  17710. bool announced_close = false;
  17711. bool reusable = true;
  17712. probe_connection_reuse(port_,
  17713. "GET /keepalive HTTP/1.1\r\n"
  17714. "Host: localhost\r\n"
  17715. "Connection: keep-alive\r\n"
  17716. "Connection: close\r\n"
  17717. "\r\n",
  17718. &announced_close, &reusable);
  17719. EXPECT_TRUE(announced_close);
  17720. EXPECT_FALSE(reusable);
  17721. }
  17722. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  17723. // keep-alive in the spelling everyone actually sends keeps its connection.
  17724. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  17725. bool announced_close = false;
  17726. bool reusable = false;
  17727. probe_connection_reuse(port_,
  17728. "GET /keepalive HTTP/1.0\r\n"
  17729. "Host: localhost\r\n"
  17730. "Connection: keep-alive\r\n"
  17731. "\r\n",
  17732. &announced_close, &reusable);
  17733. EXPECT_FALSE(announced_close);
  17734. EXPECT_TRUE(reusable);
  17735. }
  17736. // A token the value merely contains is not the token itself.
  17737. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  17738. bool announced_close = false;
  17739. bool reusable = false;
  17740. probe_connection_reuse(port_,
  17741. "GET /keepalive HTTP/1.1\r\n"
  17742. "Host: localhost\r\n"
  17743. "Connection: notclose\r\n"
  17744. "\r\n",
  17745. &announced_close, &reusable);
  17746. EXPECT_FALSE(announced_close);
  17747. EXPECT_TRUE(reusable);
  17748. }
  17749. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  17750. Server svr;
  17751. std::vector<std::string> observed_types;
  17752. svr.Get("/", [&](const Request &req, Response &res) {
  17753. observed_types = req.accept_content_types;
  17754. res.set_content("ok", "text/plain");
  17755. });
  17756. auto port = svr.bind_to_any_port(HOST);
  17757. thread t = thread([&]() { svr.listen_after_bind(); });
  17758. auto se = detail::scope_exit([&] {
  17759. svr.stop();
  17760. t.join();
  17761. ASSERT_FALSE(svr.is_running());
  17762. });
  17763. svr.wait_until_ready();
  17764. Client cli(HOST, port);
  17765. Headers headers;
  17766. headers.emplace("Accept", "text/plain;q=0.5");
  17767. headers.emplace("Accept", "application/json");
  17768. auto res = cli.Get("/", headers);
  17769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17770. EXPECT_EQ(StatusCode::OK_200, res->status);
  17771. // Sorted by q-value, so the second field line's type comes first
  17772. ASSERT_EQ(2U, observed_types.size());
  17773. EXPECT_EQ("application/json", observed_types[0]);
  17774. EXPECT_EQ("text/plain", observed_types[1]);
  17775. }
  17776. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  17777. // empty field line must not contribute a bare comma to the combined value.
  17778. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  17779. Server svr;
  17780. std::vector<std::string> observed_types;
  17781. svr.Get("/", [&](const Request &req, Response &res) {
  17782. observed_types = req.accept_content_types;
  17783. res.set_content("ok", "text/plain");
  17784. });
  17785. auto port = svr.bind_to_any_port(HOST);
  17786. thread t = thread([&]() { svr.listen_after_bind(); });
  17787. auto se = detail::scope_exit([&] {
  17788. svr.stop();
  17789. t.join();
  17790. ASSERT_FALSE(svr.is_running());
  17791. });
  17792. svr.wait_until_ready();
  17793. // Empty first field line, then a real one
  17794. std::string raw_req = "GET / HTTP/1.1\r\n"
  17795. "Host: localhost\r\n"
  17796. "Accept:\r\n"
  17797. "Accept: application/json\r\n"
  17798. "Connection: close\r\n"
  17799. "\r\n";
  17800. std::string out;
  17801. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17802. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17803. ASSERT_EQ(1U, observed_types.size());
  17804. EXPECT_EQ("application/json", observed_types[0]);
  17805. }
  17806. // The skip in get_combined_header_value() is what keeps an empty field line
  17807. // from contributing a bare comma. Only a trailing empty field line exercises
  17808. // it: a leading one is already covered by the "combined is still empty" check,
  17809. // and parse_accept_header() now ignores the empty element either way, so the
  17810. // request-level test above can no longer tell the two apart.
  17811. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  17812. Headers headers;
  17813. headers.emplace("Accept", "text/html");
  17814. headers.emplace("Accept", "");
  17815. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  17816. headers.clear();
  17817. headers.emplace("Accept", "");
  17818. headers.emplace("Accept", "application/json");
  17819. EXPECT_EQ("application/json",
  17820. detail::get_combined_header_value(headers, "Accept"));
  17821. }
  17822. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17823. // An encoding offered on a later Accept-Encoding field line is still offered.
  17824. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  17825. Server svr;
  17826. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17827. res.set_content(std::string(1024, 'x'), "text/plain");
  17828. });
  17829. auto port = svr.bind_to_any_port(HOST);
  17830. thread t = thread([&]() { svr.listen_after_bind(); });
  17831. auto se = detail::scope_exit([&] {
  17832. svr.stop();
  17833. t.join();
  17834. ASSERT_FALSE(svr.is_running());
  17835. });
  17836. svr.wait_until_ready();
  17837. Client cli(HOST, port);
  17838. cli.set_decompress(false);
  17839. Headers headers;
  17840. headers.emplace("Accept-Encoding", "identity");
  17841. headers.emplace("Accept-Encoding", "gzip");
  17842. auto res = cli.Get("/", headers);
  17843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17844. EXPECT_EQ(StatusCode::OK_200, res->status);
  17845. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  17846. }
  17847. #endif
  17848. #ifndef _WIN32
  17849. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  17850. Server svr;
  17851. svr.Post("/post", [&](const Request &req, Response &res) {
  17852. res.set_content(req.body, "text/plain");
  17853. });
  17854. svr.Put("/put", [&](const Request &req, Response &res) {
  17855. res.set_content(req.body, "text/plain");
  17856. });
  17857. svr.Patch("/patch", [&](const Request &req, Response &res) {
  17858. res.set_content(req.body, "text/plain");
  17859. });
  17860. svr.Delete("/delete", [&](const Request &req, Response &res) {
  17861. res.set_content(req.body, "text/plain");
  17862. });
  17863. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17864. auto se = detail::scope_exit([&] {
  17865. svr.stop();
  17866. t.join();
  17867. ASSERT_FALSE(svr.is_running());
  17868. });
  17869. svr.wait_until_ready();
  17870. std::string resp;
  17871. // POST without Content-Length
  17872. ASSERT_TRUE(send_request(5,
  17873. "POST /post HTTP/1.1\r\n"
  17874. "Host: localhost\r\n"
  17875. "Connection: close\r\n"
  17876. "\r\n",
  17877. &resp));
  17878. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17879. // PUT without Content-Length
  17880. resp.clear();
  17881. ASSERT_TRUE(send_request(5,
  17882. "PUT /put HTTP/1.1\r\n"
  17883. "Host: localhost\r\n"
  17884. "Connection: close\r\n"
  17885. "\r\n",
  17886. &resp));
  17887. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17888. // PATCH without Content-Length
  17889. resp.clear();
  17890. ASSERT_TRUE(send_request(5,
  17891. "PATCH /patch HTTP/1.1\r\n"
  17892. "Host: localhost\r\n"
  17893. "Connection: close\r\n"
  17894. "\r\n",
  17895. &resp));
  17896. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17897. // DELETE without Content-Length
  17898. resp.clear();
  17899. ASSERT_TRUE(send_request(5,
  17900. "DELETE /delete HTTP/1.1\r\n"
  17901. "Host: localhost\r\n"
  17902. "Connection: close\r\n"
  17903. "\r\n",
  17904. &resp));
  17905. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17906. }
  17907. #endif
  17908. //==============================================================================
  17909. // open_stream() Tests
  17910. //==============================================================================
  17911. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  17912. std::string result;
  17913. char buf[8192];
  17914. ssize_t n;
  17915. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17916. result.append(buf, static_cast<size_t>(n));
  17917. }
  17918. return result;
  17919. }
  17920. // Mock stream for unit tests
  17921. class MockStream : public Stream {
  17922. public:
  17923. std::string data;
  17924. size_t pos = 0;
  17925. ssize_t error_after = -1; // -1 = no error
  17926. explicit MockStream(const std::string &d, ssize_t err = -1)
  17927. : data(d), error_after(err) {}
  17928. bool is_readable() const override { return true; }
  17929. bool wait_readable() const override { return true; }
  17930. bool wait_writable() const override { return true; }
  17931. ssize_t read(char *ptr, size_t size) override {
  17932. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  17933. if (pos >= data.size()) return 0;
  17934. size_t limit =
  17935. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  17936. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  17937. std::memcpy(ptr, data.data() + pos, to_read);
  17938. pos += to_read;
  17939. return static_cast<ssize_t>(to_read);
  17940. }
  17941. ssize_t write(const char *, size_t) override { return -1; }
  17942. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  17943. ip = "127.0.0.1";
  17944. port = 0;
  17945. }
  17946. void get_local_ip_and_port(std::string &ip, int &port) const override {
  17947. ip = "127.0.0.1";
  17948. port = 0;
  17949. }
  17950. socket_t socket() const override { return INVALID_SOCKET; }
  17951. time_t duration() const override { return 0; }
  17952. };
  17953. TEST(StreamHandleTest, Basic) {
  17954. ClientImpl::StreamHandle handle;
  17955. EXPECT_FALSE(handle.is_valid());
  17956. handle.response = detail::make_unique<Response>();
  17957. handle.error = Error::Connection;
  17958. EXPECT_FALSE(handle.is_valid());
  17959. handle.error = Error::Success;
  17960. EXPECT_TRUE(handle.is_valid());
  17961. }
  17962. TEST(BodyReaderTest, Basic) {
  17963. MockStream stream("Hello, World!");
  17964. detail::BodyReader reader;
  17965. reader.stream = &stream;
  17966. reader.content_length = 13;
  17967. char buf[32];
  17968. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  17969. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  17970. EXPECT_TRUE(reader.eof);
  17971. }
  17972. TEST(BodyReaderTest, NoStream) {
  17973. detail::BodyReader reader;
  17974. char buf[32];
  17975. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17976. EXPECT_EQ(Error::Connection, reader.last_error);
  17977. }
  17978. TEST(BodyReaderTest, Error) {
  17979. MockStream stream("Hello, World!", 5);
  17980. detail::BodyReader reader;
  17981. reader.stream = &stream;
  17982. reader.content_length = 13;
  17983. char buf[32];
  17984. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  17985. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17986. EXPECT_EQ(Error::Read, reader.last_error);
  17987. }
  17988. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  17989. // Mock-based StreamHandle tests relying on private internals are removed.
  17990. class OpenStreamTest : public ::testing::Test {
  17991. protected:
  17992. void SetUp() override {
  17993. svr_.Get("/hello", [](const Request &, Response &res) {
  17994. res.set_content("Hello World!", "text/plain");
  17995. });
  17996. svr_.Get("/large", [](const Request &, Response &res) {
  17997. res.set_content(std::string(10000, 'X'), "text/plain");
  17998. });
  17999. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18000. res.set_content("Hello World!", "image/jpeg");
  18001. res.set_header("Content-Encoding", "UTF-8");
  18002. });
  18003. svr_.Get("/chunked", [](const Request &, Response &res) {
  18004. res.set_chunked_content_provider("text/plain",
  18005. [](size_t offset, DataSink &sink) {
  18006. if (offset < 15) {
  18007. sink.write("chunk", 5);
  18008. return true;
  18009. }
  18010. sink.done();
  18011. return true;
  18012. });
  18013. });
  18014. svr_.Get("/compressible", [](const Request &, Response &res) {
  18015. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18016. DataSink &sink) {
  18017. if (offset < 100 * 1024) {
  18018. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18019. sink.write(chunk.data(), chunk.size());
  18020. return true;
  18021. }
  18022. sink.done();
  18023. return true;
  18024. });
  18025. });
  18026. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18027. [](const Request & /*req*/, Response &res) {
  18028. auto i = new int(0);
  18029. res.set_header("Trailer", "Content-Length, X-Allowed");
  18030. res.set_chunked_content_provider(
  18031. "text/plain",
  18032. [i](size_t /*offset*/, DataSink &sink) {
  18033. switch (*i) {
  18034. case 0: sink.os << "123"; break;
  18035. case 1: sink.os << "456"; break;
  18036. case 2: sink.os << "789"; break;
  18037. case 3: {
  18038. sink.done_with_trailer(
  18039. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18040. } break;
  18041. }
  18042. (*i)++;
  18043. return true;
  18044. },
  18045. [i](bool success) {
  18046. EXPECT_TRUE(success);
  18047. delete i;
  18048. });
  18049. });
  18050. // Echo headers endpoint for header-related tests
  18051. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18052. std::string body;
  18053. for (const auto &h : req.headers) {
  18054. body.append(h.first);
  18055. body.push_back(':');
  18056. body.append(h.second);
  18057. body.push_back('\n');
  18058. }
  18059. res.set_content(body, "text/plain");
  18060. });
  18061. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18062. std::string body;
  18063. for (const auto &h : req.headers) {
  18064. body.append(h.first);
  18065. body.push_back(':');
  18066. body.append(h.second);
  18067. body.push_back('\n');
  18068. }
  18069. res.set_content(body, "text/plain");
  18070. });
  18071. port_ = svr_.bind_to_any_port("127.0.0.1");
  18072. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18073. svr_.wait_until_ready();
  18074. }
  18075. void TearDown() override {
  18076. svr_.stop();
  18077. if (thread_.joinable()) thread_.join();
  18078. }
  18079. Server svr_;
  18080. std::thread thread_;
  18081. int port_ = 0;
  18082. };
  18083. TEST_F(OpenStreamTest, Basic) {
  18084. Client cli("127.0.0.1", port_);
  18085. auto handle = cli.open_stream("GET", "/hello");
  18086. EXPECT_TRUE(handle.is_valid());
  18087. EXPECT_EQ("Hello World!", read_all(handle));
  18088. }
  18089. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18090. Client cli("127.0.0.1", port_);
  18091. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18092. ASSERT_TRUE(handle.is_valid());
  18093. EXPECT_EQ("Hello World!", read_all(handle));
  18094. }
  18095. TEST_F(OpenStreamTest, SmallBuffer) {
  18096. Client cli("127.0.0.1", port_);
  18097. auto handle = cli.open_stream("GET", "/hello");
  18098. std::string result;
  18099. char buf[4];
  18100. ssize_t n;
  18101. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18102. result.append(buf, static_cast<size_t>(n));
  18103. EXPECT_EQ("Hello World!", result);
  18104. }
  18105. TEST_F(OpenStreamTest, DefaultHeaders) {
  18106. Client cli("127.0.0.1", port_);
  18107. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18108. {
  18109. auto handle = cli.open_stream("GET", "/echo-headers");
  18110. ASSERT_TRUE(handle.is_valid());
  18111. auto body = read_all(handle);
  18112. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18113. std::string::npos);
  18114. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18115. std::string::npos);
  18116. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18117. }
  18118. // open_stream POST with body and no explicit content_type should NOT add
  18119. // text/plain Content-Type (behavior differs from non-streaming path), but
  18120. // should include Content-Length
  18121. {
  18122. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18123. ASSERT_TRUE(handle.is_valid());
  18124. auto body = read_all(handle);
  18125. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18126. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18127. }
  18128. // open_stream POST with explicit Content-Type should preserve it
  18129. {
  18130. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18131. {{"Content-Type", "application/custom"}},
  18132. "{}", "application/custom");
  18133. ASSERT_TRUE(handle.is_valid());
  18134. auto body = read_all(handle);
  18135. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18136. }
  18137. // User-specified User-Agent must not be overwritten for stream API
  18138. {
  18139. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18140. {{"User-Agent", "MyAgent/1.2"}});
  18141. ASSERT_TRUE(handle.is_valid());
  18142. auto body = read_all(handle);
  18143. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18144. }
  18145. }
  18146. TEST_F(OpenStreamTest, Large) {
  18147. Client cli("127.0.0.1", port_);
  18148. auto handle = cli.open_stream("GET", "/large");
  18149. EXPECT_EQ(10000u, read_all(handle).size());
  18150. }
  18151. TEST_F(OpenStreamTest, ConnectionError) {
  18152. Client cli("127.0.0.1", 9999);
  18153. auto handle = cli.open_stream("GET", "/hello");
  18154. EXPECT_FALSE(handle.is_valid());
  18155. }
  18156. TEST_F(OpenStreamTest, Chunked) {
  18157. Client cli("127.0.0.1", port_);
  18158. auto handle = cli.open_stream("GET", "/chunked");
  18159. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18160. "Transfer-Encoding") == "chunked");
  18161. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18162. }
  18163. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18164. Client cli("127.0.0.1", port_);
  18165. auto handle =
  18166. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18167. ASSERT_TRUE(handle.is_valid());
  18168. // Consume body to allow trailers to be received/parsed
  18169. auto body = read_all(handle);
  18170. // Explicitly parse trailers (ensure trailers are available for assertion)
  18171. handle.parse_trailers_if_needed();
  18172. EXPECT_EQ(std::string("123456789"), body);
  18173. // The response should include a Trailer header declaring both names
  18174. ASSERT_TRUE(handle.response);
  18175. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18176. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18177. handle.response->get_header_value("Trailer"));
  18178. // Prohibited trailer must not be present
  18179. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18180. // Allowed trailer should be present
  18181. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18182. EXPECT_EQ(std::string("yes"),
  18183. handle.response->get_trailer_value("X-Allowed"));
  18184. // Verify trailers are NOT present as regular headers
  18185. EXPECT_EQ(std::string(""),
  18186. handle.response->get_header_value("Content-Length"));
  18187. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18188. }
  18189. static std::thread serve_single_response(std::promise<int> &port_promise,
  18190. const std::string &response) {
  18191. return std::thread([&port_promise, response] {
  18192. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18193. default_socket_options(srv);
  18194. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18195. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18196. sockaddr_in addr{};
  18197. addr.sin_family = AF_INET;
  18198. addr.sin_port = htons(0); // Let OS assign a free port
  18199. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18200. int opt = 1;
  18201. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18202. #ifdef _WIN32
  18203. reinterpret_cast<const char *>(&opt),
  18204. #else
  18205. &opt,
  18206. #endif
  18207. sizeof(opt));
  18208. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18209. ::listen(srv, 1) != 0) {
  18210. port_promise.set_value(-1);
  18211. detail::close_socket(srv);
  18212. return;
  18213. }
  18214. socklen_t addr_len = sizeof(addr);
  18215. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18216. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18217. sockaddr_in cli_addr{};
  18218. socklen_t cli_len = sizeof(cli_addr);
  18219. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18220. if (cli != INVALID_SOCKET) {
  18221. // Read the complete HTTP request (until the blank line that terminates
  18222. // headers) before sending the response. If the server closes the socket
  18223. // while the client's request data is still unread in the kernel receive
  18224. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18225. // connection on both sides: it discards the client's receive buffer
  18226. // (which already holds our response) and causes any in-progress write on
  18227. // the client to fail with ECONNRESET. Reading all request data first
  18228. // ensures close() emits a graceful FIN.
  18229. {
  18230. char rbuf[256];
  18231. std::string req;
  18232. while (req.find("\r\n\r\n") == std::string::npos) {
  18233. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18234. if (n <= 0) { break; }
  18235. req.append(rbuf, static_cast<size_t>(n));
  18236. }
  18237. }
  18238. ::send(cli,
  18239. #ifdef _WIN32
  18240. static_cast<const char *>(response.c_str()),
  18241. static_cast<int>(response.size()),
  18242. #else
  18243. response.c_str(), response.size(),
  18244. #endif
  18245. 0);
  18246. detail::close_socket(cli);
  18247. }
  18248. detail::close_socket(srv);
  18249. });
  18250. }
  18251. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18252. #ifndef _WIN32
  18253. signal(SIGPIPE, SIG_IGN);
  18254. #endif
  18255. std::promise<int> port_promise;
  18256. auto port_future = port_promise.get_future();
  18257. auto server_thread =
  18258. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18259. "Content-Type: text/plain\r\n"
  18260. "Content-Length: not-a-number\r\n"
  18261. "Connection: close\r\n"
  18262. "\r\n"
  18263. "hello");
  18264. auto port = port_future.get();
  18265. ASSERT_GT(port, 0);
  18266. Client cli("127.0.0.1", port);
  18267. auto handle = cli.open_stream("GET", "/");
  18268. EXPECT_FALSE(handle.is_valid());
  18269. server_thread.join();
  18270. }
  18271. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18272. #ifndef _WIN32
  18273. signal(SIGPIPE, SIG_IGN);
  18274. #endif
  18275. std::promise<int> port_promise;
  18276. auto port_future = port_promise.get_future();
  18277. auto server_thread = serve_single_response(
  18278. port_promise, "HTTP/1.1 200 OK\r\n"
  18279. "Content-Type: text/plain\r\n"
  18280. "Content-Length: 99999999999999999999999999\r\n"
  18281. "Connection: close\r\n"
  18282. "\r\n"
  18283. "hello");
  18284. auto port = port_future.get();
  18285. ASSERT_GT(port, 0);
  18286. // Historically std::stoull would throw std::out_of_range here and crash
  18287. // the process, then parsing silently clamped to a bogus framing length and
  18288. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18289. // so the stream fails to open, matching the not-a-number case above. The
  18290. // process still must NOT terminate.
  18291. Client cli("127.0.0.1", port);
  18292. auto handle = cli.open_stream("GET", "/");
  18293. EXPECT_FALSE(handle.is_valid());
  18294. server_thread.join();
  18295. }
  18296. // Serves `response` to the single request `fn` makes with a fresh client.
  18297. template <typename Fn>
  18298. static void with_single_response(const std::string &response, Fn fn) {
  18299. #ifndef _WIN32
  18300. signal(SIGPIPE, SIG_IGN);
  18301. #endif
  18302. std::promise<int> port_promise;
  18303. auto port_future = port_promise.get_future();
  18304. auto server_thread = serve_single_response(port_promise, response);
  18305. auto se = detail::scope_exit([&] { server_thread.join(); });
  18306. auto port = port_future.get();
  18307. ASSERT_GT(port, 0);
  18308. Client cli("127.0.0.1", port);
  18309. fn(cli);
  18310. }
  18311. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18312. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18313. // the chunked coding and drop Content-Length, so a front-end that trusts
  18314. // Content-Length would disagree about where the body ends (response
  18315. // smuggling). The client must reject such a response.
  18316. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18317. for (const char *te : {"chunked", "gzip, chunked"}) {
  18318. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18319. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18320. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18321. "5\r\nhello\r\n0\r\n\r\n";
  18322. with_single_response(response, [&](Client &cli) {
  18323. auto res = cli.Get("/");
  18324. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18325. EXPECT_EQ(Error::Read, res.error()) << te;
  18326. });
  18327. with_single_response(response, [&](Client &cli) {
  18328. auto handle = cli.open_stream("GET", "/");
  18329. EXPECT_FALSE(handle.is_valid()) << te;
  18330. EXPECT_EQ(Error::Read, handle.error) << te;
  18331. });
  18332. }
  18333. }
  18334. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18335. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18336. // closing the connection (unlike a request, which must be rejected).
  18337. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18338. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18339. "Transfer-Encoding: chunked\r\n"
  18340. "Connection: close\r\n"
  18341. "\r\n"
  18342. "5\r\nhello\r\n0\r\n\r\n",
  18343. "HTTP/1.1 200 OK\r\n"
  18344. "Transfer-Encoding: gzip\r\n"
  18345. "Connection: close\r\n"
  18346. "\r\n"
  18347. "hello"}) {
  18348. with_single_response(response, [&](Client &cli) {
  18349. auto res = cli.Get("/");
  18350. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18351. EXPECT_EQ("hello", res->body);
  18352. });
  18353. with_single_response(response, [&](Client &cli) {
  18354. auto handle = cli.open_stream("GET", "/");
  18355. ASSERT_TRUE(handle.is_valid()) << response;
  18356. EXPECT_EQ("hello", read_all(handle));
  18357. });
  18358. }
  18359. }
  18360. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18361. // framing headers describe nothing to read and must not be rejected.
  18362. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18363. const std::string framing = "Content-Length: 5\r\n"
  18364. "Transfer-Encoding: chunked\r\n"
  18365. "Connection: close\r\n"
  18366. "\r\n";
  18367. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18368. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18369. });
  18370. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18371. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18372. });
  18373. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18374. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18375. with_single_response(response, [&](Client &cli) {
  18376. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18377. });
  18378. with_single_response(response, [&](Client &cli) {
  18379. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18380. });
  18381. }
  18382. }
  18383. // A payload max length of 0 means no limit, however the body is framed.
  18384. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18385. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18386. "Transfer-Encoding: chunked\r\n"
  18387. "\r\n"
  18388. "5\r\nhello\r\n0\r\n\r\n",
  18389. "HTTP/1.1 200 OK\r\n"
  18390. "Connection: close\r\n"
  18391. "\r\n"
  18392. "hello"}) {
  18393. with_single_response(response, [&](Client &cli) {
  18394. cli.set_payload_max_length(0);
  18395. auto res = cli.Get("/");
  18396. ASSERT_TRUE(res) << response;
  18397. EXPECT_EQ("hello", res->body) << response;
  18398. });
  18399. }
  18400. }
  18401. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18402. Server svr;
  18403. svr.set_payload_max_length(0);
  18404. svr.Post("/echo", [](const Request &req, Response &res) {
  18405. res.set_content(req.body, "text/plain");
  18406. });
  18407. auto port = svr.bind_to_any_port(HOST);
  18408. thread t = thread([&] { svr.listen_after_bind(); });
  18409. auto se = detail::scope_exit([&] {
  18410. svr.stop();
  18411. t.join();
  18412. ASSERT_FALSE(svr.is_running());
  18413. });
  18414. svr.wait_until_ready();
  18415. Client cli(HOST, port);
  18416. auto res = cli.Post(
  18417. "/echo",
  18418. [](size_t /*offset*/, DataSink &sink) {
  18419. sink.write("hello", 5);
  18420. sink.done();
  18421. return true;
  18422. },
  18423. "text/plain");
  18424. ASSERT_TRUE(res);
  18425. EXPECT_EQ(StatusCode::OK_200, res->status);
  18426. EXPECT_EQ("hello", res->body);
  18427. }
  18428. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18429. TEST_F(OpenStreamTest, Gzip) {
  18430. Client cli("127.0.0.1", port_);
  18431. auto handle = cli.open_stream("GET", "/compressible", {},
  18432. {{"Accept-Encoding", "gzip"}});
  18433. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18434. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18435. }
  18436. #endif
  18437. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18438. TEST_F(OpenStreamTest, Brotli) {
  18439. Client cli("127.0.0.1", port_);
  18440. auto handle =
  18441. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18442. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18443. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18444. }
  18445. #endif
  18446. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18447. TEST_F(OpenStreamTest, Zstd) {
  18448. Client cli("127.0.0.1", port_);
  18449. auto handle = cli.open_stream("GET", "/compressible", {},
  18450. {{"Accept-Encoding", "zstd"}});
  18451. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18452. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18453. }
  18454. #endif
  18455. #ifdef CPPHTTPLIB_SSL_ENABLED
  18456. class SSLOpenStreamTest : public ::testing::Test {
  18457. protected:
  18458. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18459. void SetUp() override {
  18460. svr_.Get("/hello", [](const Request &, Response &res) {
  18461. res.set_content("Hello SSL World!", "text/plain");
  18462. });
  18463. svr_.Get("/chunked", [](const Request &, Response &res) {
  18464. res.set_chunked_content_provider("text/plain",
  18465. [](size_t offset, DataSink &sink) {
  18466. if (offset < 15) {
  18467. sink.write("chunk", 5);
  18468. return true;
  18469. }
  18470. sink.done();
  18471. return true;
  18472. });
  18473. });
  18474. svr_.Post("/echo", [](const Request &req, Response &res) {
  18475. res.set_content(req.body, req.get_header_value("Content-Type"));
  18476. });
  18477. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18478. std::string body = req.body;
  18479. res.set_chunked_content_provider(
  18480. "text/plain", [body](size_t offset, DataSink &sink) {
  18481. if (offset < body.size()) {
  18482. sink.write(body.data() + offset, body.size() - offset);
  18483. }
  18484. sink.done();
  18485. return true;
  18486. });
  18487. });
  18488. port_ = svr_.bind_to_any_port("127.0.0.1");
  18489. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18490. svr_.wait_until_ready();
  18491. }
  18492. void TearDown() override {
  18493. svr_.stop();
  18494. if (thread_.joinable()) thread_.join();
  18495. }
  18496. SSLServer svr_;
  18497. std::thread thread_;
  18498. int port_ = 0;
  18499. };
  18500. TEST_F(SSLOpenStreamTest, Basic) {
  18501. SSLClient cli("127.0.0.1", port_);
  18502. cli.enable_server_certificate_verification(false);
  18503. auto handle = cli.open_stream("GET", "/hello");
  18504. ASSERT_TRUE(handle.is_valid());
  18505. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18506. }
  18507. TEST_F(SSLOpenStreamTest, Chunked) {
  18508. SSLClient cli("127.0.0.1", port_);
  18509. cli.enable_server_certificate_verification(false);
  18510. auto handle = cli.open_stream("GET", "/chunked");
  18511. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18512. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18513. "Transfer-Encoding") == "chunked");
  18514. auto body = read_all(handle);
  18515. EXPECT_EQ("chunkchunkchunk", body);
  18516. }
  18517. TEST_F(SSLOpenStreamTest, Post) {
  18518. SSLClient cli("127.0.0.1", port_);
  18519. cli.enable_server_certificate_verification(false);
  18520. auto handle =
  18521. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  18522. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18523. EXPECT_EQ(200, handle.response->status);
  18524. auto body = read_all(handle);
  18525. EXPECT_EQ("Hello SSL POST", body);
  18526. }
  18527. TEST_F(SSLOpenStreamTest, PostChunked) {
  18528. SSLClient cli("127.0.0.1", port_);
  18529. cli.enable_server_certificate_verification(false);
  18530. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  18531. "Chunked SSL Data", "text/plain");
  18532. ASSERT_TRUE(handle.is_valid());
  18533. EXPECT_EQ(200, handle.response->status);
  18534. auto body = read_all(handle);
  18535. EXPECT_EQ("Chunked SSL Data", body);
  18536. }
  18537. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  18538. // Content-Length is terminated by the server closing the connection. When the
  18539. // SSL peer sends a close_notify after the body, the client must treat it as a
  18540. // clean EOF and return a successful response rather than an error.
  18541. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  18542. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18543. ASSERT_TRUE(svr.is_valid());
  18544. svr.set_keep_alive_max_count(1);
  18545. const std::string expected_body = "Hello from connection-close response!";
  18546. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  18547. res.set_content_provider("text/plain",
  18548. [&](size_t offset, DataSink &sink) -> bool {
  18549. if (offset < expected_body.size()) {
  18550. sink.write(expected_body.data() + offset,
  18551. expected_body.size() - offset);
  18552. }
  18553. sink.done();
  18554. return true;
  18555. });
  18556. });
  18557. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  18558. auto se = detail::scope_exit([&] {
  18559. svr.stop();
  18560. listen_thread.join();
  18561. ASSERT_FALSE(svr.is_running());
  18562. });
  18563. svr.wait_until_ready();
  18564. SSLClient cli(HOST, PORT);
  18565. cli.enable_server_certificate_verification(false);
  18566. auto res = cli.Get("/no-content-length");
  18567. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18568. EXPECT_EQ(StatusCode::OK_200, res->status);
  18569. EXPECT_EQ(expected_body, res->body);
  18570. }
  18571. #endif // CPPHTTPLIB_SSL_ENABLED
  18572. //==============================================================================
  18573. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18574. // results for various scenarios.
  18575. //==============================================================================
  18576. TEST(ParityTest, GetVsOpenStream) {
  18577. Server svr;
  18578. const std::string path = "/parity";
  18579. const std::string content = "Parity test content: hello world";
  18580. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18581. res.set_content(content, "text/plain");
  18582. });
  18583. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18584. auto se = detail::scope_exit([&] {
  18585. svr.stop();
  18586. t.join();
  18587. ASSERT_FALSE(svr.is_running());
  18588. });
  18589. svr.wait_until_ready();
  18590. Client cli(HOST, PORT);
  18591. // Non-stream path
  18592. auto r1 = cli.Get(path);
  18593. ASSERT_TRUE(r1);
  18594. EXPECT_EQ(StatusCode::OK_200, r1->status);
  18595. // Stream path
  18596. auto h = cli.open_stream("GET", path);
  18597. ASSERT_TRUE(h.is_valid());
  18598. EXPECT_EQ(r1->body, read_all(h));
  18599. }
  18600. // Helper to compress data with provided compressor type T
  18601. template <typename Compressor>
  18602. static std::string compress_payload_for_parity(const std::string &in) {
  18603. std::string out;
  18604. Compressor compressor;
  18605. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  18606. [&](const char *data, size_t n) {
  18607. out.append(data, n);
  18608. return true;
  18609. });
  18610. EXPECT_TRUE(ok);
  18611. return out;
  18612. }
  18613. // Helper function for compression parity tests
  18614. template <typename Compressor>
  18615. static void test_compression_parity(const std::string &original,
  18616. const std::string &path,
  18617. const std::string &encoding) {
  18618. const std::string compressed =
  18619. compress_payload_for_parity<Compressor>(original);
  18620. Server svr;
  18621. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18622. res.set_content(compressed, "application/octet-stream");
  18623. res.set_header("Content-Encoding", encoding);
  18624. });
  18625. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  18626. auto se = detail::scope_exit([&] {
  18627. svr.stop();
  18628. t.join();
  18629. ASSERT_FALSE(svr.is_running());
  18630. });
  18631. svr.wait_until_ready();
  18632. Client cli(HOST, PORT);
  18633. // Non-streaming
  18634. {
  18635. auto res = cli.Get(path);
  18636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18637. EXPECT_EQ(StatusCode::OK_200, res->status);
  18638. EXPECT_EQ(original, res->body);
  18639. }
  18640. // Streaming
  18641. {
  18642. auto h = cli.open_stream("GET", path);
  18643. ASSERT_TRUE(h.is_valid());
  18644. EXPECT_EQ(original, read_all(h));
  18645. }
  18646. }
  18647. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18648. TEST(ParityTest, Gzip) {
  18649. test_compression_parity<detail::gzip_compressor>(
  18650. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  18651. }
  18652. #endif
  18653. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18654. TEST(ParityTest, Brotli) {
  18655. test_compression_parity<detail::brotli_compressor>(
  18656. "Hello, brotli parity test payload", "/parity-br", "br");
  18657. }
  18658. #endif
  18659. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18660. TEST(ParityTest, Zstd) {
  18661. test_compression_parity<detail::zstd_compressor>(
  18662. "Zstandard parity test payload", "/parity-zstd", "zstd");
  18663. }
  18664. #endif
  18665. //==============================================================================
  18666. // New Stream API Tests
  18667. //==============================================================================
  18668. inline std::string read_body(httplib::stream::Result &result) {
  18669. std::string body;
  18670. while (result.next()) {
  18671. body.append(result.data(), result.size());
  18672. }
  18673. return body;
  18674. }
  18675. TEST(ClientConnectionTest, Basic) {
  18676. httplib::ClientConnection conn;
  18677. EXPECT_FALSE(conn.is_open());
  18678. conn.sock = 1;
  18679. EXPECT_TRUE(conn.is_open());
  18680. httplib::ClientConnection conn2(std::move(conn));
  18681. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  18682. conn2.sock = INVALID_SOCKET;
  18683. }
  18684. // Unified test server for all stream::* tests
  18685. class StreamApiTest : public ::testing::Test {
  18686. protected:
  18687. void SetUp() override {
  18688. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18689. res.set_content("Hello World!", "text/plain");
  18690. });
  18691. svr_.Get("/echo-params",
  18692. [](const httplib::Request &req, httplib::Response &res) {
  18693. std::string r;
  18694. for (const auto &p : req.params) {
  18695. if (!r.empty()) r += "&";
  18696. r += p.first + "=" + p.second;
  18697. }
  18698. res.set_content(r, "text/plain");
  18699. });
  18700. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18701. res.set_content(req.body, req.get_header_value("Content-Type"));
  18702. });
  18703. svr_.Post("/echo-headers",
  18704. [](const httplib::Request &req, httplib::Response &res) {
  18705. std::string r;
  18706. for (const auto &h : req.headers)
  18707. r += h.first + ": " + h.second + "\n";
  18708. res.set_content(r, "text/plain");
  18709. });
  18710. svr_.Post("/echo-params",
  18711. [](const httplib::Request &req, httplib::Response &res) {
  18712. std::string r = "params:";
  18713. for (const auto &p : req.params)
  18714. r += p.first + "=" + p.second + ";";
  18715. res.set_content(r + " body:" + req.body, "text/plain");
  18716. });
  18717. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  18718. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  18719. });
  18720. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18721. res.set_content("PUT:" + req.body, "text/plain");
  18722. });
  18723. svr_.Patch("/echo",
  18724. [](const httplib::Request &req, httplib::Response &res) {
  18725. res.set_content("PATCH:" + req.body, "text/plain");
  18726. });
  18727. svr_.Delete(
  18728. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  18729. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  18730. "text/plain");
  18731. });
  18732. svr_.Get("/head-test",
  18733. [](const httplib::Request &, httplib::Response &res) {
  18734. res.set_content("body for HEAD", "text/plain");
  18735. });
  18736. svr_.Options("/options",
  18737. [](const httplib::Request &, httplib::Response &res) {
  18738. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  18739. });
  18740. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  18741. svr_.wait_until_ready();
  18742. }
  18743. void TearDown() override {
  18744. svr_.stop();
  18745. if (thread_.joinable()) thread_.join();
  18746. }
  18747. httplib::Server svr_;
  18748. std::thread thread_;
  18749. };
  18750. // stream::Get tests
  18751. TEST_F(StreamApiTest, GetBasic) {
  18752. httplib::Client cli(HOST, PORT);
  18753. auto result = httplib::stream::Get(cli, "/hello");
  18754. ASSERT_TRUE(result.is_valid());
  18755. EXPECT_EQ(200, result.status());
  18756. EXPECT_EQ("Hello World!", read_body(result));
  18757. }
  18758. TEST_F(StreamApiTest, GetWithParams) {
  18759. httplib::Client cli(HOST, PORT);
  18760. httplib::Params params{{"foo", "bar"}};
  18761. auto result = httplib::stream::Get(cli, "/echo-params", params);
  18762. ASSERT_TRUE(result.is_valid());
  18763. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  18764. }
  18765. TEST_F(StreamApiTest, GetConnectionError) {
  18766. httplib::Client cli(HOST, 9999);
  18767. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  18768. }
  18769. TEST_F(StreamApiTest, Get404) {
  18770. httplib::Client cli(HOST, PORT);
  18771. auto result = httplib::stream::Get(cli, "/nonexistent");
  18772. EXPECT_TRUE(result.is_valid());
  18773. EXPECT_EQ(404, result.status());
  18774. }
  18775. // stream::Post tests
  18776. TEST_F(StreamApiTest, PostBasic) {
  18777. httplib::Client cli(HOST, PORT);
  18778. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  18779. "application/json");
  18780. ASSERT_TRUE(result.is_valid());
  18781. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  18782. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  18783. }
  18784. TEST_F(StreamApiTest, PostWithHeaders) {
  18785. httplib::Client cli(HOST, PORT);
  18786. httplib::Headers headers{{"X-Custom", "value"}};
  18787. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  18788. "text/plain");
  18789. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  18790. }
  18791. TEST_F(StreamApiTest, PostWithParams) {
  18792. httplib::Client cli(HOST, PORT);
  18793. httplib::Params params{{"k", "v"}};
  18794. auto result =
  18795. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  18796. auto body = read_body(result);
  18797. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  18798. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  18799. }
  18800. TEST_F(StreamApiTest, PostLarge) {
  18801. httplib::Client cli(HOST, PORT);
  18802. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  18803. size_t total = 0;
  18804. while (result.next()) {
  18805. total += result.size();
  18806. }
  18807. EXPECT_EQ(100u * 1024u, total);
  18808. }
  18809. // stream::Put/Patch tests
  18810. TEST_F(StreamApiTest, PutAndPatch) {
  18811. httplib::Client cli(HOST, PORT);
  18812. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  18813. EXPECT_EQ("PUT:test", read_body(put));
  18814. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  18815. EXPECT_EQ("PATCH:test", read_body(patch));
  18816. }
  18817. // stream::Delete tests
  18818. TEST_F(StreamApiTest, Delete) {
  18819. httplib::Client cli(HOST, PORT);
  18820. auto del1 = httplib::stream::Delete(cli, "/resource");
  18821. EXPECT_EQ("Deleted", read_body(del1));
  18822. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  18823. EXPECT_EQ("Deleted:data", read_body(del2));
  18824. }
  18825. // stream::Head/Options tests
  18826. TEST_F(StreamApiTest, HeadAndOptions) {
  18827. httplib::Client cli(HOST, PORT);
  18828. auto head = httplib::stream::Head(cli, "/head-test");
  18829. EXPECT_TRUE(head.is_valid());
  18830. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  18831. auto opts = httplib::stream::Options(cli, "/options");
  18832. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  18833. }
  18834. // SSL stream::* tests
  18835. #ifdef CPPHTTPLIB_SSL_ENABLED
  18836. class SSLStreamApiTest : public ::testing::Test {
  18837. protected:
  18838. void SetUp() override {
  18839. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18840. res.set_content("Hello SSL!", "text/plain");
  18841. });
  18842. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18843. res.set_content(req.body, "text/plain");
  18844. });
  18845. port_ = svr_.bind_to_any_port("127.0.0.1");
  18846. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18847. svr_.wait_until_ready();
  18848. }
  18849. void TearDown() override {
  18850. svr_.stop();
  18851. if (thread_.joinable()) thread_.join();
  18852. }
  18853. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  18854. std::thread thread_;
  18855. int port_ = 0;
  18856. };
  18857. TEST_F(SSLStreamApiTest, GetAndPost) {
  18858. httplib::SSLClient cli("127.0.0.1", port_);
  18859. cli.enable_server_certificate_verification(false);
  18860. auto get = httplib::stream::Get(cli, "/hello");
  18861. EXPECT_EQ("Hello SSL!", read_body(get));
  18862. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  18863. EXPECT_EQ("test", read_body(post));
  18864. }
  18865. #endif
  18866. // Tests for Error::Timeout and Error::ConnectionClosed error types
  18867. // These errors are set in SocketStream/SSLSocketStream and propagated through
  18868. // BodyReader
  18869. TEST(ErrorHandlingTest, StreamReadTimeout) {
  18870. // Test that read timeout during streaming is detected
  18871. // Use a large content-length response where server delays mid-stream
  18872. Server svr;
  18873. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18874. // Send a large response with delay in the middle
  18875. res.set_content_provider(
  18876. 1000, // content_length
  18877. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  18878. if (offset < 100) {
  18879. // Send first 100 bytes immediately
  18880. std::string data(100, 'A');
  18881. sink.write(data.c_str(), data.size());
  18882. return true;
  18883. }
  18884. // Then delay longer than client timeout
  18885. std::this_thread::sleep_for(std::chrono::seconds(3));
  18886. std::string data(900, 'B');
  18887. sink.write(data.c_str(), data.size());
  18888. return true;
  18889. });
  18890. });
  18891. auto port = 8091;
  18892. std::thread t([&]() { svr.listen("localhost", port); });
  18893. svr.wait_until_ready();
  18894. Client cli("localhost", port);
  18895. cli.set_read_timeout(1, 0); // 1 second timeout
  18896. auto handle = cli.open_stream("GET", "/slow-stream");
  18897. ASSERT_TRUE(handle.is_valid());
  18898. char buf[256];
  18899. ssize_t total = 0;
  18900. ssize_t n;
  18901. bool got_error = false;
  18902. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18903. total += n;
  18904. }
  18905. if (n < 0) {
  18906. got_error = true;
  18907. // Should be timeout or read error
  18908. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18909. handle.get_read_error() == Error::Read)
  18910. << "Actual error: " << to_string(handle.get_read_error());
  18911. }
  18912. // Either we got an error, or we got less data than expected
  18913. EXPECT_TRUE(got_error || total < 1000)
  18914. << "Expected timeout but got all " << total << " bytes";
  18915. svr.stop();
  18916. t.join();
  18917. }
  18918. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  18919. // Test connection closed detection via BodyReader
  18920. Server svr;
  18921. std::atomic<bool> close_now{false};
  18922. svr.Get("/will-close", [&](const Request &, Response &res) {
  18923. res.set_content_provider(
  18924. 10000, // Large content_length that we won't fully send
  18925. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18926. if (offset < 100) {
  18927. std::string data(100, 'X');
  18928. sink.write(data.c_str(), data.size());
  18929. return true;
  18930. }
  18931. // Wait for signal then abort
  18932. while (!close_now) {
  18933. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18934. }
  18935. return false; // Abort - server will close connection
  18936. });
  18937. });
  18938. auto port = 8092;
  18939. std::thread t([&]() { svr.listen("localhost", port); });
  18940. svr.wait_until_ready();
  18941. Client cli("localhost", port);
  18942. auto handle = cli.open_stream("GET", "/will-close");
  18943. ASSERT_TRUE(handle.is_valid());
  18944. char buf[256];
  18945. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18946. EXPECT_GT(n, 0) << "First read should succeed";
  18947. // Signal server to close
  18948. close_now = true;
  18949. // Keep reading until error or EOF
  18950. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18951. // Keep reading
  18952. }
  18953. // Should get an error since content_length wasn't satisfied
  18954. if (n < 0) {
  18955. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18956. handle.get_read_error() == Error::Read)
  18957. << "Actual error: " << to_string(handle.get_read_error());
  18958. }
  18959. svr.stop();
  18960. t.join();
  18961. }
  18962. #ifdef CPPHTTPLIB_SSL_ENABLED
  18963. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  18964. // Test that read timeout during SSL streaming is detected
  18965. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18966. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18967. res.set_content_provider(
  18968. 1000, "text/plain",
  18969. [](size_t offset, size_t /*length*/, DataSink &sink) {
  18970. if (offset < 100) {
  18971. std::string data(100, 'A');
  18972. sink.write(data.c_str(), data.size());
  18973. return true;
  18974. }
  18975. std::this_thread::sleep_for(std::chrono::seconds(3));
  18976. std::string data(900, 'B');
  18977. sink.write(data.c_str(), data.size());
  18978. return true;
  18979. });
  18980. });
  18981. auto port = 8093;
  18982. std::thread t([&]() { svr.listen("localhost", port); });
  18983. svr.wait_until_ready();
  18984. SSLClient cli("localhost", port);
  18985. cli.enable_server_certificate_verification(false);
  18986. cli.set_read_timeout(1, 0); // 1 second timeout
  18987. auto handle = cli.open_stream("GET", "/slow-stream");
  18988. ASSERT_TRUE(handle.is_valid());
  18989. char buf[256];
  18990. ssize_t total = 0;
  18991. ssize_t n;
  18992. bool got_error = false;
  18993. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18994. total += n;
  18995. }
  18996. if (n < 0) {
  18997. got_error = true;
  18998. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18999. handle.get_read_error() == Error::Read)
  19000. << "Actual error: " << to_string(handle.get_read_error());
  19001. }
  19002. EXPECT_TRUE(got_error || total < 1000)
  19003. << "Expected timeout but got all " << total << " bytes";
  19004. svr.stop();
  19005. t.join();
  19006. }
  19007. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  19008. // Test SSL connection closed detection
  19009. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19010. std::atomic<bool> close_now{false};
  19011. svr.Get("/will-close", [&](const Request &, Response &res) {
  19012. res.set_content_provider(
  19013. 10000, "text/plain",
  19014. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19015. if (offset < 100) {
  19016. std::string data(100, 'X');
  19017. sink.write(data.c_str(), data.size());
  19018. return true;
  19019. }
  19020. while (!close_now) {
  19021. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19022. }
  19023. return false;
  19024. });
  19025. });
  19026. auto port = 8094;
  19027. std::thread t([&]() { svr.listen("localhost", port); });
  19028. svr.wait_until_ready();
  19029. SSLClient cli("localhost", port);
  19030. cli.enable_server_certificate_verification(false);
  19031. auto handle = cli.open_stream("GET", "/will-close");
  19032. ASSERT_TRUE(handle.is_valid());
  19033. char buf[256];
  19034. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19035. EXPECT_GT(n, 0);
  19036. // Signal server to close
  19037. close_now = true;
  19038. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19039. // Keep reading
  19040. }
  19041. if (n < 0) {
  19042. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19043. handle.get_read_error() == Error::Read)
  19044. << "Actual error: " << to_string(handle.get_read_error());
  19045. }
  19046. svr.stop();
  19047. t.join();
  19048. }
  19049. #endif
  19050. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19051. using namespace httplib;
  19052. // Create a test file
  19053. const char *fname = "etag_testfile.txt";
  19054. const char *content = "etag-content";
  19055. {
  19056. std::ofstream ofs(fname);
  19057. ofs << content;
  19058. ASSERT_TRUE(ofs.good());
  19059. }
  19060. Server svr;
  19061. svr.set_mount_point("/static", ".");
  19062. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19063. svr.wait_until_ready();
  19064. Client cli(HOST, PORT);
  19065. // First request: should get 200 with ETag header
  19066. auto res1 = cli.Get("/static/etag_testfile.txt");
  19067. ASSERT_TRUE(res1);
  19068. ASSERT_EQ(200, res1->status);
  19069. ASSERT_TRUE(res1->has_header("ETag"));
  19070. std::string etag = res1->get_header_value("ETag");
  19071. EXPECT_FALSE(etag.empty());
  19072. // Verify ETag format: W/"hex-hex"
  19073. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19074. EXPECT_EQ('W', etag[0]);
  19075. EXPECT_EQ('/', etag[1]);
  19076. EXPECT_EQ('"', etag[2]);
  19077. EXPECT_EQ('"', etag.back());
  19078. // Exact match: expect 304 Not Modified
  19079. Headers h2 = {{"If-None-Match", etag}};
  19080. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19081. ASSERT_TRUE(res2);
  19082. EXPECT_EQ(304, res2->status);
  19083. // Wildcard match: expect 304 Not Modified
  19084. Headers h3 = {{"If-None-Match", "*"}};
  19085. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19086. ASSERT_TRUE(res3);
  19087. EXPECT_EQ(304, res3->status);
  19088. // Non-matching ETag: expect 200
  19089. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19090. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19091. ASSERT_TRUE(res4);
  19092. EXPECT_EQ(200, res4->status);
  19093. // Multiple ETags with one matching: expect 304
  19094. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19095. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19096. ASSERT_TRUE(res5);
  19097. EXPECT_EQ(304, res5->status);
  19098. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19099. // that equivalent to the single comma-separated list above, so the match on
  19100. // the second line must still be found.
  19101. Headers h6;
  19102. h6.emplace("If-None-Match", "W/\"other\"");
  19103. h6.emplace("If-None-Match", etag);
  19104. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19105. ASSERT_TRUE(res6);
  19106. EXPECT_EQ(304, res6->status);
  19107. svr.stop();
  19108. t.join();
  19109. std::remove(fname);
  19110. }
  19111. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19112. using namespace httplib;
  19113. Server svr;
  19114. svr.set_mount_point("/static", ".");
  19115. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19116. svr.wait_until_ready();
  19117. Client cli(HOST, PORT);
  19118. // Send If-None-Match: * to a non-existent file
  19119. Headers h = {{"If-None-Match", "*"}};
  19120. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19122. EXPECT_EQ(404, res->status);
  19123. svr.stop();
  19124. t.join();
  19125. }
  19126. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  19127. using namespace httplib;
  19128. // Create a test file
  19129. const char *fname = "etag_boundary_testfile.txt";
  19130. const char *content = "boundary-test";
  19131. {
  19132. std::ofstream ofs(fname);
  19133. ofs << content;
  19134. ASSERT_TRUE(ofs.good());
  19135. }
  19136. Server svr;
  19137. svr.set_mount_point("/static", ".");
  19138. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19139. svr.wait_until_ready();
  19140. Client cli(HOST, PORT);
  19141. // Get the actual ETag
  19142. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  19143. ASSERT_TRUE(res1);
  19144. ASSERT_EQ(200, res1->status);
  19145. ASSERT_TRUE(res1->has_header("ETag"));
  19146. std::string etag = res1->get_header_value("ETag");
  19147. // Test 1: Very long ETag value (longer than actual ETag)
  19148. // Should NOT match and return 200 (not trigger out-of-bounds read)
  19149. Headers h1 = {{"If-None-Match", "W/"
  19150. "\"very-long-etag-value-that-is-much-longer-"
  19151. "than-the-actual-etag-value\""}};
  19152. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  19153. ASSERT_TRUE(res2);
  19154. EXPECT_EQ(200, res2->status); // Should not match
  19155. // Test 2: Long string followed by wildcard
  19156. // Should match on "*" and return 304 (without out-of-bounds read on the long
  19157. // string)
  19158. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19159. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19160. ASSERT_TRUE(res3);
  19161. EXPECT_EQ(304, res3->status); // Should match on "*"
  19162. // Test 3: Wildcard followed by long string
  19163. // Should match on "*" immediately and return 304
  19164. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  19165. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  19166. ASSERT_TRUE(res4);
  19167. EXPECT_EQ(304, res4->status); // Should match on "*"
  19168. // Test 4: Multiple long non-matching values
  19169. // Should NOT match and return 200 (test that all comparisons are safe)
  19170. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  19171. "W/\"second-long-non-matching-value\", "
  19172. "W/\"third-long-non-matching-value\""}};
  19173. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  19174. ASSERT_TRUE(res5);
  19175. EXPECT_EQ(200, res5->status); // Should not match
  19176. // Test 5: Single character that is not "*" (edge case)
  19177. Headers h5 = {{"If-None-Match", "X"}};
  19178. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  19179. ASSERT_TRUE(res6);
  19180. EXPECT_EQ(200, res6->status); // Should not match
  19181. svr.stop();
  19182. t.join();
  19183. std::remove(fname);
  19184. }
  19185. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  19186. using namespace httplib;
  19187. // Create a test file
  19188. const char *fname = "ims_testfile.txt";
  19189. const char *content = "if-modified-since-test";
  19190. {
  19191. std::ofstream ofs(fname);
  19192. ofs << content;
  19193. ASSERT_TRUE(ofs.good());
  19194. }
  19195. Server svr;
  19196. svr.set_mount_point("/static", ".");
  19197. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19198. svr.wait_until_ready();
  19199. Client cli(HOST, PORT);
  19200. // First request: should get 200 with Last-Modified header
  19201. auto res1 = cli.Get("/static/ims_testfile.txt");
  19202. ASSERT_TRUE(res1);
  19203. ASSERT_EQ(200, res1->status);
  19204. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19205. std::string last_modified = res1->get_header_value("Last-Modified");
  19206. EXPECT_FALSE(last_modified.empty());
  19207. // If-Modified-Since with same time: expect 304
  19208. Headers h2 = {{"If-Modified-Since", last_modified}};
  19209. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  19210. ASSERT_TRUE(res2);
  19211. EXPECT_EQ(304, res2->status);
  19212. // If-Modified-Since with future time: expect 304
  19213. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19214. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  19215. ASSERT_TRUE(res3);
  19216. EXPECT_EQ(304, res3->status);
  19217. // If-Modified-Since with past time: expect 200
  19218. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19219. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  19220. ASSERT_TRUE(res4);
  19221. EXPECT_EQ(200, res4->status);
  19222. // If-None-Match takes precedence over If-Modified-Since
  19223. // (send matching ETag with old If-Modified-Since -> should still be 304)
  19224. ASSERT_TRUE(res1->has_header("ETag"));
  19225. std::string etag = res1->get_header_value("ETag");
  19226. Headers h5 = {{"If-None-Match", etag},
  19227. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19228. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  19229. ASSERT_TRUE(res5);
  19230. EXPECT_EQ(304, res5->status);
  19231. svr.stop();
  19232. t.join();
  19233. std::remove(fname);
  19234. }
  19235. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  19236. using namespace httplib;
  19237. Server svr;
  19238. // Endpoint that returns compressible content
  19239. svr.Get("/compressible", [](const Request &, Response &res) {
  19240. // Return a large enough body to trigger compression
  19241. std::string body(1000, 'a');
  19242. res.set_content(body, "text/plain");
  19243. });
  19244. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19245. svr.wait_until_ready();
  19246. Client cli(HOST, PORT);
  19247. // Request with gzip support: should get Vary header when compressed
  19248. cli.set_compress(true);
  19249. auto res1 = cli.Get("/compressible");
  19250. ASSERT_TRUE(res1);
  19251. EXPECT_EQ(200, res1->status);
  19252. // If Content-Encoding is set, Vary should also be set
  19253. if (res1->has_header("Content-Encoding")) {
  19254. EXPECT_TRUE(res1->has_header("Vary"));
  19255. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  19256. }
  19257. // Request without Accept-Encoding header: should not have compression
  19258. Headers h_no_compress;
  19259. auto res2 = cli.Get("/compressible", h_no_compress);
  19260. ASSERT_TRUE(res2);
  19261. EXPECT_EQ(200, res2->status);
  19262. // Verify Vary header is present when compression is applied
  19263. // (the exact behavior depends on server configuration)
  19264. svr.stop();
  19265. t.join();
  19266. }
  19267. TEST(ETagTest, IfRangeWithETag) {
  19268. using namespace httplib;
  19269. // Create a test file with known content
  19270. const char *fname = "if_range_testfile.txt";
  19271. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  19272. {
  19273. std::ofstream ofs(fname);
  19274. ofs << content;
  19275. ASSERT_TRUE(ofs.good());
  19276. }
  19277. Server svr;
  19278. svr.set_mount_point("/static", ".");
  19279. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19280. svr.wait_until_ready();
  19281. Client cli(HOST, PORT);
  19282. // First request: get ETag
  19283. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19284. ASSERT_TRUE(res1);
  19285. ASSERT_EQ(200, res1->status);
  19286. ASSERT_TRUE(res1->has_header("ETag"));
  19287. std::string etag = res1->get_header_value("ETag");
  19288. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  19289. // Since our server generates weak ETags (W/"..."), If-Range with our
  19290. // ETag should NOT result in partial content - it should return full content.
  19291. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  19292. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  19293. ASSERT_TRUE(res2);
  19294. // Weak ETag in If-Range -> full content (200), not partial (206)
  19295. EXPECT_EQ(200, res2->status);
  19296. EXPECT_EQ(content, res2->body);
  19297. EXPECT_FALSE(res2->has_header("Content-Range"));
  19298. // Range request with non-matching If-Range (ETag): should get 200 (full
  19299. // content)
  19300. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  19301. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  19302. ASSERT_TRUE(res3);
  19303. EXPECT_EQ(200, res3->status);
  19304. EXPECT_EQ(content, res3->body);
  19305. EXPECT_FALSE(res3->has_header("Content-Range"));
  19306. // Range request with strong ETag (hypothetical - our server doesn't generate
  19307. // strong ETags, but if client sends a strong ETag that doesn't match, it
  19308. // should return full content)
  19309. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19310. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19311. ASSERT_TRUE(res4);
  19312. EXPECT_EQ(200, res4->status);
  19313. EXPECT_EQ(content, res4->body);
  19314. EXPECT_FALSE(res4->has_header("Content-Range"));
  19315. svr.stop();
  19316. t.join();
  19317. std::remove(fname);
  19318. }
  19319. TEST(ETagTest, IfRangeWithDate) {
  19320. using namespace httplib;
  19321. // Create a test file
  19322. const char *fname = "if_range_date_testfile.txt";
  19323. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  19324. {
  19325. std::ofstream ofs(fname);
  19326. ofs << content;
  19327. ASSERT_TRUE(ofs.good());
  19328. }
  19329. Server svr;
  19330. svr.set_mount_point("/static", ".");
  19331. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19332. svr.wait_until_ready();
  19333. Client cli(HOST, PORT);
  19334. // First request: get Last-Modified
  19335. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  19336. ASSERT_TRUE(res1);
  19337. ASSERT_EQ(200, res1->status);
  19338. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19339. std::string last_modified = res1->get_header_value("Last-Modified");
  19340. // Range request with matching If-Range (date): should get 206
  19341. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19342. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19343. ASSERT_TRUE(res2);
  19344. EXPECT_EQ(206, res2->status);
  19345. EXPECT_EQ("FGHIJ", res2->body);
  19346. // Range request with old If-Range date: should get 200 (full content)
  19347. Headers h3 = {{"Range", "bytes=5-9"},
  19348. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19349. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19350. ASSERT_TRUE(res3);
  19351. EXPECT_EQ(200, res3->status);
  19352. EXPECT_EQ(content, res3->body);
  19353. // Range request with future If-Range date: should get 206
  19354. Headers h4 = {{"Range", "bytes=0-4"},
  19355. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19356. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19357. ASSERT_TRUE(res4);
  19358. EXPECT_EQ(206, res4->status);
  19359. EXPECT_EQ("ABCDE", res4->body);
  19360. svr.stop();
  19361. t.join();
  19362. std::remove(fname);
  19363. }
  19364. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19365. using namespace httplib;
  19366. const char *fname = "etag_malformed.txt";
  19367. const char *content = "malformed-etag";
  19368. {
  19369. std::ofstream ofs(fname);
  19370. ofs << content;
  19371. ASSERT_TRUE(ofs.good());
  19372. }
  19373. Server svr;
  19374. svr.set_mount_point("/static", ".");
  19375. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19376. svr.wait_until_ready();
  19377. Client cli(HOST, PORT);
  19378. // baseline: should get 200 and an ETag
  19379. auto res1 = cli.Get("/static/etag_malformed.txt");
  19380. ASSERT_TRUE(res1);
  19381. ASSERT_EQ(200, res1->status);
  19382. ASSERT_TRUE(res1->has_header("ETag"));
  19383. // Malformed ETag value (missing quotes) should be treated as non-matching
  19384. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19385. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19386. ASSERT_TRUE(res_bad);
  19387. EXPECT_EQ(200, res_bad->status);
  19388. // Whitespace-only header value should be considered invalid / non-matching
  19389. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19390. "Host: localhost\r\n"
  19391. "If-None-Match: \r\n"
  19392. "Connection: close\r\n"
  19393. "\r\n";
  19394. std::string out;
  19395. ASSERT_TRUE(send_request(5, raw_req, &out));
  19396. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19397. svr.stop();
  19398. t.join();
  19399. std::remove(fname);
  19400. }
  19401. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19402. using namespace httplib;
  19403. const char *fname = "ims_invalid_format.txt";
  19404. const char *content = "ims-bad-format";
  19405. {
  19406. std::ofstream ofs(fname);
  19407. ofs << content;
  19408. ASSERT_TRUE(ofs.good());
  19409. }
  19410. Server svr;
  19411. svr.set_mount_point("/static", ".");
  19412. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19413. svr.wait_until_ready();
  19414. Client cli(HOST, PORT);
  19415. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19416. ASSERT_TRUE(res1);
  19417. ASSERT_EQ(200, res1->status);
  19418. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19419. // If-Modified-Since with invalid format should not result in 304
  19420. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19421. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19422. ASSERT_TRUE(res_bad);
  19423. EXPECT_EQ(200, res_bad->status);
  19424. // If-Range with invalid date format should be treated as mismatch -> full
  19425. // content (200)
  19426. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19427. {"If-Range", "invalid-date"}};
  19428. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19429. ASSERT_TRUE(res_ifrange);
  19430. EXPECT_EQ(200, res_ifrange->status);
  19431. svr.stop();
  19432. t.join();
  19433. std::remove(fname);
  19434. }
  19435. TEST(ETagTest, IfRangeWithMalformedETag) {
  19436. using namespace httplib;
  19437. const char *fname = "ifrange_malformed.txt";
  19438. const std::string content = "0123456789";
  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. // First request: get ETag
  19450. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19451. ASSERT_TRUE(res1);
  19452. ASSERT_EQ(200, res1->status);
  19453. ASSERT_TRUE(res1->has_header("ETag"));
  19454. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19455. // full content (200)
  19456. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19457. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19458. ASSERT_TRUE(res2);
  19459. EXPECT_EQ(200, res2->status);
  19460. EXPECT_EQ(content, res2->body);
  19461. svr.stop();
  19462. t.join();
  19463. std::remove(fname);
  19464. }
  19465. TEST(ETagTest, ExtremeLargeDateValues) {
  19466. using namespace httplib;
  19467. const char *fname = "ims_extreme_date.txt";
  19468. const char *content = "ims-extreme-date";
  19469. {
  19470. std::ofstream ofs(fname);
  19471. ofs << content;
  19472. ASSERT_TRUE(ofs.good());
  19473. }
  19474. Server svr;
  19475. svr.set_mount_point("/static", ".");
  19476. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19477. svr.wait_until_ready();
  19478. Client cli(HOST, PORT);
  19479. auto res1 = cli.Get(std::string("/static/") + fname);
  19480. ASSERT_TRUE(res1);
  19481. ASSERT_EQ(200, res1->status);
  19482. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19483. // Extremely large year that may overflow date parsing routines.
  19484. Headers h_large_date = {
  19485. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19486. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19487. ASSERT_TRUE(res_bad);
  19488. // Expect server to treat this as invalid/mismatch and return full content
  19489. EXPECT_EQ(200, res_bad->status);
  19490. // If-Range with extremely large date should be treated as mismatch -> full
  19491. // content (200)
  19492. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19493. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19494. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19495. ASSERT_TRUE(res_ifrange);
  19496. EXPECT_EQ(200, res_ifrange->status);
  19497. svr.stop();
  19498. t.join();
  19499. std::remove(fname);
  19500. }
  19501. TEST(ETagTest, NegativeFileModificationTime) {
  19502. using namespace httplib;
  19503. const char *fname = "ims_negative_mtime.txt";
  19504. const std::string content = "negative-mtime";
  19505. {
  19506. std::ofstream ofs(fname);
  19507. ofs << content;
  19508. ASSERT_TRUE(ofs.good());
  19509. }
  19510. // Try to set file mtime to a negative value. This may fail on some
  19511. // platforms/filesystems; if it fails, the test will still verify server
  19512. // behaves safely by performing a regular conditional request.
  19513. #if defined(__APPLE__) || defined(__linux__)
  19514. bool set_negative = false;
  19515. do {
  19516. struct timeval times[2];
  19517. // access time: now
  19518. times[0].tv_sec = time(nullptr);
  19519. times[0].tv_usec = 0;
  19520. // modification time: negative (e.g., -1)
  19521. times[1].tv_sec = -1;
  19522. times[1].tv_usec = 0;
  19523. if (utimes(fname, times) == 0) { set_negative = true; }
  19524. } while (0);
  19525. #else
  19526. bool set_negative = false;
  19527. #endif
  19528. Server svr;
  19529. svr.set_mount_point("/static", ".");
  19530. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19531. svr.wait_until_ready();
  19532. Client cli(HOST, PORT);
  19533. auto res1 = cli.Get(std::string("/static/") + fname);
  19534. ASSERT_TRUE(res1);
  19535. ASSERT_EQ(200, res1->status);
  19536. bool has_last_modified = res1->has_header("Last-Modified");
  19537. std::string last_modified;
  19538. if (has_last_modified) {
  19539. last_modified = res1->get_header_value("Last-Modified");
  19540. }
  19541. if (set_negative) {
  19542. // If we successfully set a negative mtime, ensure server returns a
  19543. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  19544. // with an old date and ensure server handles it without crash.
  19545. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  19546. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  19547. ASSERT_TRUE(res2);
  19548. // Behavior may vary; at minimum ensure server responds (200 or 304).
  19549. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  19550. } else {
  19551. // Could not set negative mtime on this platform; fall back to verifying
  19552. // that normal invalid/malformed dates are treated safely (non-304).
  19553. Headers h_bad_date = {
  19554. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19555. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  19556. ASSERT_TRUE(res_bad);
  19557. EXPECT_EQ(200, res_bad->status);
  19558. }
  19559. svr.stop();
  19560. t.join();
  19561. std::remove(fname);
  19562. }
  19563. //==============================================================================
  19564. // Integration Tests with Server
  19565. //==============================================================================
  19566. class SSEIntegrationTest : public ::testing::Test {
  19567. protected:
  19568. void SetUp() override {
  19569. stop_server_.store(false);
  19570. events_.clear();
  19571. server_ = httplib::detail::make_unique<Server>();
  19572. setup_server();
  19573. start_server();
  19574. }
  19575. void TearDown() override {
  19576. stop_server_.store(true);
  19577. event_cv_.notify_all();
  19578. server_->stop();
  19579. if (server_thread_.joinable()) { server_thread_.join(); }
  19580. }
  19581. void setup_server() {
  19582. // Simple SSE endpoint
  19583. server_->Get("/events", [this](const Request &req, Response &res) {
  19584. auto last_id = req.get_header_value("Last-Event-ID");
  19585. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  19586. res.set_chunked_content_provider(
  19587. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  19588. std::unique_lock<std::mutex> lock(event_mutex_);
  19589. if (event_cv_.wait_for(
  19590. lock, std::chrono::milliseconds(200), [this] {
  19591. return !events_.empty() || stop_server_.load();
  19592. })) {
  19593. if (stop_server_.load()) { return false; }
  19594. if (!events_.empty()) {
  19595. std::string event = events_.front();
  19596. events_.erase(events_.begin());
  19597. sink.write(event.data(), event.size());
  19598. return true;
  19599. }
  19600. }
  19601. return !stop_server_.load();
  19602. });
  19603. });
  19604. // Endpoint that returns error
  19605. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  19606. res.status = 500;
  19607. res.set_content("Internal Server Error", "text/plain");
  19608. });
  19609. // Endpoint for custom event types
  19610. server_->Get("/custom-events", [](const Request &, Response &res) {
  19611. res.set_chunked_content_provider(
  19612. "text/event-stream", [](size_t offset, DataSink &sink) {
  19613. if (offset == 0) {
  19614. std::string event = "event: update\ndata: updated\n\n"
  19615. "event: delete\ndata: deleted\n\n";
  19616. sink.write(event.data(), event.size());
  19617. }
  19618. return false; // End stream after sending
  19619. });
  19620. });
  19621. }
  19622. void start_server() {
  19623. port_ = server_->bind_to_any_port(HOST);
  19624. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19625. // Wait for server to start
  19626. while (!server_->is_running()) {
  19627. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19628. }
  19629. }
  19630. int get_port() const { return port_; }
  19631. void send_event(const std::string &event) {
  19632. std::lock_guard<std::mutex> lock(event_mutex_);
  19633. events_.push_back(event);
  19634. event_cv_.notify_all();
  19635. }
  19636. std::unique_ptr<Server> server_;
  19637. std::thread server_thread_;
  19638. std::mutex event_mutex_;
  19639. std::condition_variable event_cv_;
  19640. std::vector<std::string> events_;
  19641. std::atomic<bool> stop_server_{false};
  19642. std::string last_received_event_id_;
  19643. int port_ = 0;
  19644. };
  19645. //==============================================================================
  19646. // SSE Parsing Tests
  19647. //==============================================================================
  19648. class SSEParsingTest : public SSEIntegrationTest {
  19649. protected:
  19650. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  19651. // A trailing sentinel event tells when the whole stream has been parsed.
  19652. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  19653. auto body = stream + "event: end\ndata: end\n\n";
  19654. server_->Get("/parse", [body](const Request &, Response &res) {
  19655. res.set_content(body, "text/event-stream");
  19656. });
  19657. return collect("/parse");
  19658. }
  19659. // Runs SSEClient against path until an "end" event arrives and returns the
  19660. // messages dispatched before it
  19661. std::vector<sse::SSEMessage> collect(const std::string &path) {
  19662. Client client(HOST, get_port());
  19663. sse::SSEClient sse(client, path);
  19664. std::mutex mutex;
  19665. std::condition_variable cv;
  19666. std::vector<sse::SSEMessage> messages;
  19667. auto done = false;
  19668. sse.on_message([&](const sse::SSEMessage &msg) {
  19669. std::lock_guard<std::mutex> lock(mutex);
  19670. // Ignore a replay from a reconnect that races with stop()
  19671. if (!done) { messages.push_back(msg); }
  19672. });
  19673. sse.on_event("end", [&](const sse::SSEMessage &) {
  19674. std::lock_guard<std::mutex> lock(mutex);
  19675. done = true;
  19676. cv.notify_all();
  19677. });
  19678. sse.set_reconnect_interval(100);
  19679. sse.start_async();
  19680. {
  19681. std::unique_lock<std::mutex> lock(mutex);
  19682. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  19683. }
  19684. sse.stop();
  19685. EXPECT_TRUE(done);
  19686. return messages;
  19687. }
  19688. };
  19689. TEST_F(SSEParsingTest, SingleLineData) {
  19690. auto msgs = parse("data: hello\n\n");
  19691. ASSERT_EQ(msgs.size(), 1u);
  19692. EXPECT_EQ(msgs[0].data, "hello");
  19693. EXPECT_EQ(msgs[0].event, "message");
  19694. }
  19695. TEST_F(SSEParsingTest, MultiLineData) {
  19696. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  19697. ASSERT_EQ(msgs.size(), 1u);
  19698. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  19699. }
  19700. TEST_F(SSEParsingTest, CustomEventType) {
  19701. auto msgs = parse("event: update\ndata: payload\n\n");
  19702. ASSERT_EQ(msgs.size(), 1u);
  19703. EXPECT_EQ(msgs[0].event, "update");
  19704. EXPECT_EQ(msgs[0].data, "payload");
  19705. }
  19706. TEST_F(SSEParsingTest, EventIdHandling) {
  19707. auto msgs = parse("id: 12345\ndata: test\n\n");
  19708. ASSERT_EQ(msgs.size(), 1u);
  19709. EXPECT_EQ(msgs[0].id, "12345");
  19710. }
  19711. TEST_F(SSEParsingTest, EmptyEventId) {
  19712. auto msgs = parse("id:\ndata: test\n\n");
  19713. ASSERT_EQ(msgs.size(), 1u);
  19714. EXPECT_EQ(msgs[0].id, "");
  19715. }
  19716. TEST_F(SSEParsingTest, CommentsIgnored) {
  19717. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  19718. ASSERT_EQ(msgs.size(), 1u);
  19719. EXPECT_EQ(msgs[0].data, "hello");
  19720. EXPECT_EQ(msgs[0].event, "message");
  19721. }
  19722. TEST_F(SSEParsingTest, ColonInValue) {
  19723. auto msgs = parse("data: hello:world:test\n\n");
  19724. ASSERT_EQ(msgs.size(), 1u);
  19725. EXPECT_EQ(msgs[0].data, "hello:world:test");
  19726. }
  19727. TEST_F(SSEParsingTest, FieldNameOnly) {
  19728. // A line without a colon is a field name with an empty value
  19729. auto msgs = parse("data\n\n");
  19730. ASSERT_EQ(msgs.size(), 1u);
  19731. EXPECT_EQ(msgs[0].data, "");
  19732. }
  19733. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  19734. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  19735. ASSERT_EQ(msgs.size(), 1u);
  19736. EXPECT_EQ(msgs[0].event, "update");
  19737. EXPECT_EQ(msgs[0].data, "hello");
  19738. }
  19739. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  19740. auto msgs = parse("data\r\n\r\n");
  19741. ASSERT_EQ(msgs.size(), 1u);
  19742. EXPECT_EQ(msgs[0].data, "");
  19743. }
  19744. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  19745. auto msgs = parse("event: update\rdata: hello\r\r");
  19746. ASSERT_EQ(msgs.size(), 1u);
  19747. EXPECT_EQ(msgs[0].event, "update");
  19748. EXPECT_EQ(msgs[0].data, "hello");
  19749. }
  19750. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  19751. // Chunk boundaries fall inside every \r\n and right before the first one
  19752. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  19753. "\n\r", "\nevent: end\ndata: end\n\n"};
  19754. server_->Get("/split", [chunks](const Request &, Response &res) {
  19755. auto i = std::make_shared<size_t>(0);
  19756. res.set_chunked_content_provider(
  19757. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  19758. if (*i == chunks.size()) {
  19759. sink.done();
  19760. } else {
  19761. sink.write(chunks[*i].data(), chunks[*i].size());
  19762. (*i)++;
  19763. }
  19764. return true;
  19765. });
  19766. });
  19767. auto msgs = collect("/split");
  19768. ASSERT_EQ(msgs.size(), 1u);
  19769. EXPECT_EQ(msgs[0].event, "update");
  19770. EXPECT_EQ(msgs[0].data, "hello");
  19771. }
  19772. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  19773. // Only a BOM at the start of the stream is ignored
  19774. auto msgs = parse("\xEF\xBB\xBF"
  19775. "data: first\n\n"
  19776. "\xEF\xBB\xBF"
  19777. "data: second\n\n");
  19778. ASSERT_EQ(msgs.size(), 1u);
  19779. EXPECT_EQ(msgs[0].data, "first");
  19780. }
  19781. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  19782. auto msgs = parse("unknown: value\ndata: hello\n\n");
  19783. ASSERT_EQ(msgs.size(), 1u);
  19784. EXPECT_EQ(msgs[0].data, "hello");
  19785. EXPECT_EQ(msgs[0].event, "message");
  19786. }
  19787. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  19788. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  19789. ASSERT_EQ(msgs.size(), 2u);
  19790. EXPECT_EQ(msgs[0].data, "hello");
  19791. EXPECT_EQ(msgs[1].data, "hello");
  19792. }
  19793. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  19794. // An event without data is not dispatched, and its type must not leak
  19795. // into the next event
  19796. auto msgs = parse("event: update\n\ndata: hello\n\n");
  19797. ASSERT_EQ(msgs.size(), 1u);
  19798. EXPECT_EQ(msgs[0].event, "message");
  19799. EXPECT_EQ(msgs[0].data, "hello");
  19800. }
  19801. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  19802. // The first connection sends only an id; the second echoes back the
  19803. // Last-Event-ID it was reconnected with
  19804. std::atomic<int> connection_count{0};
  19805. server_->Get("/id-only", [&](const Request &req, Response &res) {
  19806. if (connection_count++ == 0) {
  19807. res.set_content("id: 42\n\n", "text/event-stream");
  19808. } else {
  19809. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19810. "\n\nevent: end\ndata: end\n\n",
  19811. "text/event-stream");
  19812. }
  19813. });
  19814. auto msgs = collect("/id-only");
  19815. ASSERT_EQ(msgs.size(), 1u);
  19816. EXPECT_EQ(msgs[0].data, "42");
  19817. }
  19818. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  19819. // The first connection sets an id and then clears it with an empty one; the
  19820. // second reports whether it was reconnected with a Last-Event-ID
  19821. std::atomic<int> connection_count{0};
  19822. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  19823. if (connection_count++ == 0) {
  19824. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  19825. "text/event-stream");
  19826. } else {
  19827. res.set_content(
  19828. std::string("data: ") +
  19829. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  19830. "\n\nevent: end\ndata: end\n\n",
  19831. "text/event-stream");
  19832. }
  19833. });
  19834. auto msgs = collect("/id-clear");
  19835. ASSERT_EQ(msgs.size(), 3u);
  19836. EXPECT_EQ(msgs[0].id, "1");
  19837. EXPECT_EQ(msgs[1].id, "");
  19838. EXPECT_EQ(msgs[2].data, "not sent");
  19839. }
  19840. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  19841. // The first connection sets an id and then sends ids that cannot be carried
  19842. // in a header; the second echoes back the Last-Event-ID it was reconnected
  19843. // with
  19844. std::atomic<int> connection_count{0};
  19845. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  19846. if (connection_count++ == 0) {
  19847. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  19848. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  19849. "text/event-stream");
  19850. } else {
  19851. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19852. "\n\nevent: end\ndata: end\n\n",
  19853. "text/event-stream");
  19854. }
  19855. });
  19856. auto msgs = collect("/id-unsendable");
  19857. ASSERT_EQ(msgs.size(), 1u);
  19858. EXPECT_EQ(msgs[0].data, "42");
  19859. }
  19860. TEST_F(SSEParsingTest, CompleteEventParsing) {
  19861. auto msgs = parse("event: notification\nid: evt-42\n"
  19862. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  19863. ASSERT_EQ(msgs.size(), 1u);
  19864. EXPECT_EQ(msgs[0].event, "notification");
  19865. EXPECT_EQ(msgs[0].id, "evt-42");
  19866. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  19867. }
  19868. TEST(SSEMessageTest, Clear) {
  19869. sse::SSEMessage msg;
  19870. msg.event = "custom";
  19871. msg.data = "some data";
  19872. msg.id = "123";
  19873. msg.clear();
  19874. EXPECT_EQ(msg.event, "message");
  19875. EXPECT_EQ(msg.data, "");
  19876. EXPECT_EQ(msg.id, "");
  19877. }
  19878. //==============================================================================
  19879. // SSE Integration Tests
  19880. //==============================================================================
  19881. // Test: Successful connection and on_open callback
  19882. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  19883. // Add a simple endpoint that sends one event and closes
  19884. server_->Get("/simple-event", [](const Request &, Response &res) {
  19885. res.set_chunked_content_provider(
  19886. "text/event-stream", [](size_t offset, DataSink &sink) {
  19887. if (offset == 0) {
  19888. std::string event = "data: hello\n\n";
  19889. sink.write(event.data(), event.size());
  19890. }
  19891. return false; // Close stream after sending
  19892. });
  19893. });
  19894. Client client("localhost", get_port());
  19895. sse::SSEClient sse(client, "/simple-event");
  19896. std::atomic<bool> open_called{false};
  19897. std::atomic<bool> message_received{false};
  19898. sse.on_open([&open_called]() { open_called.store(true); });
  19899. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  19900. if (msg.data == "hello") { message_received.store(true); }
  19901. });
  19902. sse.set_reconnect_interval(100);
  19903. sse.set_max_reconnect_attempts(1);
  19904. // Start async
  19905. sse.start_async();
  19906. // Wait for message to be processed
  19907. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19908. sse.stop();
  19909. EXPECT_TRUE(open_called.load());
  19910. EXPECT_TRUE(message_received.load());
  19911. }
  19912. // Test: on_message callback
  19913. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  19914. // Endpoint that sends multiple events then closes
  19915. server_->Get("/multi-event", [](const Request &, Response &res) {
  19916. res.set_chunked_content_provider(
  19917. "text/event-stream", [](size_t offset, DataSink &sink) {
  19918. if (offset == 0) {
  19919. std::string events = "data: message1\n\ndata: message2\n\n";
  19920. sink.write(events.data(), events.size());
  19921. }
  19922. return false;
  19923. });
  19924. });
  19925. Client client("localhost", get_port());
  19926. sse::SSEClient sse(client, "/multi-event");
  19927. std::vector<std::string> received_messages;
  19928. std::mutex messages_mutex;
  19929. sse.on_message([&](const sse::SSEMessage &msg) {
  19930. std::lock_guard<std::mutex> lock(messages_mutex);
  19931. received_messages.push_back(msg.data);
  19932. });
  19933. sse.set_reconnect_interval(100);
  19934. sse.set_max_reconnect_attempts(1);
  19935. sse.start_async();
  19936. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19937. sse.stop();
  19938. std::lock_guard<std::mutex> lock(messages_mutex);
  19939. EXPECT_GE(received_messages.size(), 2u);
  19940. if (received_messages.size() >= 2) {
  19941. EXPECT_EQ(received_messages[0], "message1");
  19942. EXPECT_EQ(received_messages[1], "message2");
  19943. }
  19944. }
  19945. // Test: on_event for specific types
  19946. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  19947. Client client("localhost", get_port());
  19948. sse::SSEClient sse(client, "/custom-events");
  19949. std::atomic<bool> update_received{false};
  19950. std::atomic<bool> delete_received{false};
  19951. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  19952. if (msg.data == "updated") { update_received.store(true); }
  19953. });
  19954. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  19955. if (msg.data == "deleted") { delete_received.store(true); }
  19956. });
  19957. sse.set_max_reconnect_attempts(1);
  19958. sse.start_async();
  19959. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  19960. sse.stop();
  19961. EXPECT_TRUE(update_received.load());
  19962. EXPECT_TRUE(delete_received.load());
  19963. }
  19964. // Test: on_error callback on connection failure
  19965. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  19966. // Connect to a non-existent port
  19967. Client client("localhost", 59999);
  19968. sse::SSEClient sse(client, "/events");
  19969. std::atomic<bool> error_called{false};
  19970. Error received_error = Error::Success;
  19971. sse.on_error([&](Error err) {
  19972. error_called.store(true);
  19973. received_error = err;
  19974. });
  19975. sse.set_reconnect_interval(50);
  19976. sse.set_max_reconnect_attempts(1);
  19977. sse.start_async();
  19978. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19979. sse.stop();
  19980. EXPECT_TRUE(error_called.load());
  19981. EXPECT_NE(received_error, Error::Success);
  19982. }
  19983. // Test: Last-Event-ID header sent on reconnect
  19984. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  19985. // Endpoint that sends event with ID
  19986. server_->Get("/event-with-id", [](const Request &, Response &res) {
  19987. res.set_chunked_content_provider(
  19988. "text/event-stream", [](size_t offset, DataSink &sink) {
  19989. if (offset == 0) {
  19990. std::string event = "id: evt-123\ndata: test\n\n";
  19991. sink.write(event.data(), event.size());
  19992. }
  19993. return false;
  19994. });
  19995. });
  19996. Client client("localhost", get_port());
  19997. sse::SSEClient sse(client, "/event-with-id");
  19998. std::atomic<bool> id_received{false};
  19999. sse.on_message([&](const sse::SSEMessage &msg) {
  20000. if (!msg.id.empty()) { id_received.store(true); }
  20001. });
  20002. sse.set_reconnect_interval(100);
  20003. sse.set_max_reconnect_attempts(1);
  20004. sse.start_async();
  20005. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20006. sse.stop();
  20007. EXPECT_TRUE(id_received.load());
  20008. EXPECT_EQ(sse.last_event_id(), "evt-123");
  20009. }
  20010. // Test: Manual stop
  20011. TEST_F(SSEIntegrationTest, ManualStop) {
  20012. // Endpoint that sends one event and stays open briefly
  20013. std::atomic<bool> handler_running{true};
  20014. server_->Get("/stay-open", [&handler_running](const Request &,
  20015. Response &res) {
  20016. res.set_chunked_content_provider(
  20017. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  20018. if (offset == 0) {
  20019. std::string event = "data: connected\n\n";
  20020. sink.write(event.data(), event.size());
  20021. }
  20022. // Keep connection open while handler_running is true
  20023. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  20024. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20025. }
  20026. return false;
  20027. });
  20028. });
  20029. Client client("localhost", get_port());
  20030. sse::SSEClient sse(client, "/stay-open");
  20031. std::atomic<bool> connected{false};
  20032. sse.on_open([&connected]() { connected.store(true); });
  20033. sse.set_reconnect_interval(100);
  20034. sse.set_max_reconnect_attempts(1);
  20035. sse.start_async();
  20036. // Wait for connection to establish
  20037. for (int i = 0; i < 20 && !connected.load(); ++i) {
  20038. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20039. }
  20040. EXPECT_TRUE(connected.load());
  20041. EXPECT_TRUE(sse.is_connected());
  20042. // Signal handler to stop
  20043. handler_running.store(false);
  20044. // Stop SSE client
  20045. sse.stop();
  20046. EXPECT_FALSE(sse.is_connected());
  20047. }
  20048. // Test: SSEClient with custom headers
  20049. TEST_F(SSEIntegrationTest, CustomHeaders) {
  20050. // Setup a server endpoint that checks for custom header
  20051. std::atomic<bool> header_received{false};
  20052. server_->Get("/header-check", [&](const Request &req, Response &res) {
  20053. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  20054. header_received.store(true);
  20055. }
  20056. res.set_chunked_content_provider("text/event-stream",
  20057. [](size_t, DataSink &) { return false; });
  20058. });
  20059. Client client("localhost", get_port());
  20060. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20061. sse::SSEClient sse(client, "/header-check", headers);
  20062. sse.set_max_reconnect_attempts(1);
  20063. sse.start_async();
  20064. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20065. sse.stop();
  20066. EXPECT_TRUE(header_received.load());
  20067. }
  20068. // Test: Reconnect interval configuration
  20069. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  20070. Client client("localhost", get_port());
  20071. sse::SSEClient sse(client, "/events");
  20072. auto &result = sse.set_reconnect_interval(500);
  20073. // Builder pattern should return reference to self
  20074. EXPECT_EQ(&result, &sse);
  20075. }
  20076. // Test: Max reconnect attempts
  20077. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  20078. // Connect to non-existent port to force reconnects
  20079. Client client("localhost", 59998);
  20080. sse::SSEClient sse(client, "/events");
  20081. std::atomic<int> error_count{0};
  20082. sse.on_error([&](Error) { error_count.fetch_add(1); });
  20083. sse.set_reconnect_interval(50);
  20084. sse.set_max_reconnect_attempts(2);
  20085. auto start = std::chrono::steady_clock::now();
  20086. sse.start(); // Blocking call
  20087. auto end = std::chrono::steady_clock::now();
  20088. // Should have stopped after 2 failed attempts
  20089. EXPECT_GE(error_count.load(), 2);
  20090. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  20091. auto duration =
  20092. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  20093. #ifdef _WIN32
  20094. // Windows is much slower for socket connection failures
  20095. EXPECT_LT(duration.count(), 7000);
  20096. #else
  20097. EXPECT_LT(duration.count(), 1000);
  20098. #endif
  20099. }
  20100. // Test: Multi-line data in integration
  20101. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  20102. // Endpoint with multi-line data
  20103. server_->Get("/multiline-data", [](const Request &, Response &res) {
  20104. res.set_chunked_content_provider(
  20105. "text/event-stream", [](size_t offset, DataSink &sink) {
  20106. if (offset == 0) {
  20107. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  20108. sink.write(event.data(), event.size());
  20109. }
  20110. return false;
  20111. });
  20112. });
  20113. Client client("localhost", get_port());
  20114. sse::SSEClient sse(client, "/multiline-data");
  20115. std::string received_data;
  20116. std::mutex data_mutex;
  20117. sse.on_message([&](const sse::SSEMessage &msg) {
  20118. std::lock_guard<std::mutex> lock(data_mutex);
  20119. received_data = msg.data;
  20120. });
  20121. sse.set_reconnect_interval(100);
  20122. sse.set_max_reconnect_attempts(1);
  20123. sse.start_async();
  20124. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20125. sse.stop();
  20126. std::lock_guard<std::mutex> lock(data_mutex);
  20127. EXPECT_EQ(received_data, "line1\nline2\nline3");
  20128. }
  20129. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  20130. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  20131. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  20132. DataSink &sink) {
  20133. if (offset == 0) {
  20134. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  20135. sink.write(events.data(), events.size());
  20136. }
  20137. return false;
  20138. });
  20139. });
  20140. Client client("localhost", get_port());
  20141. sse::SSEClient sse(client, "/empty-data-lines");
  20142. std::mutex mutex;
  20143. std::condition_variable cv;
  20144. std::vector<std::string> received;
  20145. sse.on_message([&](const sse::SSEMessage &msg) {
  20146. std::lock_guard<std::mutex> lock(mutex);
  20147. received.push_back(msg.data);
  20148. cv.notify_all();
  20149. });
  20150. sse.set_max_reconnect_attempts(1);
  20151. sse.start_async();
  20152. {
  20153. std::unique_lock<std::mutex> lock(mutex);
  20154. cv.wait_for(lock, std::chrono::seconds(2),
  20155. [&] { return received.size() >= 3; });
  20156. }
  20157. sse.stop();
  20158. ASSERT_GE(received.size(), 3u);
  20159. EXPECT_EQ(received[0], "");
  20160. EXPECT_EQ(received[1], "\nhello");
  20161. EXPECT_EQ(received[2], "");
  20162. }
  20163. // Test: Auto-reconnect after server disconnection
  20164. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  20165. std::atomic<int> connection_count{0};
  20166. std::atomic<int> message_count{0};
  20167. // Endpoint that sends one event and closes, forcing reconnect
  20168. server_->Get("/reconnect-test",
  20169. [&connection_count](const Request &, Response &res) {
  20170. connection_count.fetch_add(1);
  20171. res.set_chunked_content_provider(
  20172. "text/event-stream", [](size_t offset, DataSink &sink) {
  20173. if (offset == 0) {
  20174. std::string event = "data: hello\n\n";
  20175. sink.write(event.data(), event.size());
  20176. }
  20177. return false; // Close connection after sending
  20178. });
  20179. });
  20180. Client client("localhost", get_port());
  20181. sse::SSEClient sse(client, "/reconnect-test");
  20182. sse.on_message([&message_count](const sse::SSEMessage &) {
  20183. message_count.fetch_add(1);
  20184. });
  20185. sse.set_reconnect_interval(100);
  20186. sse.set_max_reconnect_attempts(3);
  20187. sse.start_async();
  20188. // Wait long enough for multiple reconnects
  20189. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20190. sse.stop();
  20191. // Should have connected multiple times (initial + reconnects)
  20192. EXPECT_GE(connection_count.load(), 2);
  20193. // Should have received messages from multiple connections
  20194. EXPECT_GE(message_count.load(), 2);
  20195. }
  20196. // Test: A retry field that is not all ASCII digits is ignored
  20197. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  20198. std::atomic<int> connection_count{0};
  20199. server_->Get("/bad-retry",
  20200. [&connection_count](const Request &, Response &res) {
  20201. connection_count.fetch_add(1);
  20202. res.set_chunked_content_provider(
  20203. "text/event-stream", [](size_t offset, DataSink &sink) {
  20204. if (offset == 0) {
  20205. std::string event = "retry: -1\ndata: hello\n\n";
  20206. sink.write(event.data(), event.size());
  20207. }
  20208. return false;
  20209. });
  20210. });
  20211. Client client("localhost", get_port());
  20212. sse::SSEClient sse(client, "/bad-retry");
  20213. sse.set_reconnect_interval(10000);
  20214. sse.start_async();
  20215. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20216. sse.stop();
  20217. EXPECT_EQ(connection_count.load(), 1);
  20218. }
  20219. // Test: A retry field of all ASCII digits sets the reconnection time
  20220. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  20221. std::mutex mutex;
  20222. std::condition_variable cv;
  20223. std::vector<std::chrono::steady_clock::time_point> connected_at;
  20224. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  20225. {
  20226. std::lock_guard<std::mutex> lock(mutex);
  20227. connected_at.push_back(std::chrono::steady_clock::now());
  20228. cv.notify_all();
  20229. }
  20230. res.set_chunked_content_provider(
  20231. "text/event-stream", [](size_t offset, DataSink &sink) {
  20232. if (offset == 0) {
  20233. std::string event = "retry: 0\ndata: hello\n\n";
  20234. sink.write(event.data(), event.size());
  20235. }
  20236. return false;
  20237. });
  20238. });
  20239. Client client("localhost", get_port());
  20240. sse::SSEClient sse(client, "/zero-retry");
  20241. sse.set_reconnect_interval(10000);
  20242. sse.start_async();
  20243. {
  20244. std::unique_lock<std::mutex> lock(mutex);
  20245. cv.wait_for(lock, std::chrono::seconds(5),
  20246. [&] { return connected_at.size() >= 2; });
  20247. }
  20248. sse.stop();
  20249. // The server-supplied interval is applied, but never below 100ms, so
  20250. // "retry: 0" does not cause a busy reconnect loop
  20251. std::lock_guard<std::mutex> lock(mutex);
  20252. ASSERT_GE(connected_at.size(), 2u);
  20253. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  20254. connected_at[1] - connected_at[0])
  20255. .count();
  20256. EXPECT_GE(interval_ms, 100);
  20257. }
  20258. // Test: Last-Event-ID sent on reconnect
  20259. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  20260. std::atomic<int> connection_count{0};
  20261. std::vector<std::string> received_last_event_ids;
  20262. std::mutex id_mutex;
  20263. // Endpoint that checks Last-Event-ID header and sends event with ID
  20264. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  20265. int conn = connection_count.fetch_add(1);
  20266. // Capture the Last-Event-ID header from each connection
  20267. {
  20268. std::lock_guard<std::mutex> lock(id_mutex);
  20269. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  20270. }
  20271. res.set_chunked_content_provider(
  20272. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  20273. if (offset == 0) {
  20274. std::string event =
  20275. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  20276. sink.write(event.data(), event.size());
  20277. }
  20278. return false;
  20279. });
  20280. });
  20281. Client client("localhost", get_port());
  20282. sse::SSEClient sse(client, "/reconnect-with-id");
  20283. sse.set_reconnect_interval(100);
  20284. sse.set_max_reconnect_attempts(3);
  20285. sse.start_async();
  20286. // Wait for at least 2 connections
  20287. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20288. sse.stop();
  20289. // Verify behavior
  20290. std::lock_guard<std::mutex> lock(id_mutex);
  20291. EXPECT_GE(received_last_event_ids.size(), 2u);
  20292. // First connection should have no Last-Event-ID
  20293. if (!received_last_event_ids.empty()) {
  20294. EXPECT_EQ(received_last_event_ids[0], "");
  20295. }
  20296. // Second connection should have Last-Event-ID from first connection
  20297. if (received_last_event_ids.size() >= 2) {
  20298. EXPECT_EQ(received_last_event_ids[1], "event-0");
  20299. }
  20300. }
  20301. // Test: set_headers updates headers used on reconnect
  20302. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  20303. std::vector<std::string> received_tokens;
  20304. std::mutex token_mutex;
  20305. // Endpoint that captures Authorization header
  20306. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  20307. {
  20308. std::lock_guard<std::mutex> lock(token_mutex);
  20309. received_tokens.push_back(req.get_header_value("Authorization"));
  20310. }
  20311. res.set_chunked_content_provider(
  20312. "text/event-stream", [](size_t offset, DataSink &sink) {
  20313. if (offset == 0) {
  20314. std::string event = "data: hello\n\n";
  20315. sink.write(event.data(), event.size());
  20316. }
  20317. return false; // Close connection to trigger reconnect
  20318. });
  20319. });
  20320. Client client("localhost", get_port());
  20321. Headers headers = {{"Authorization", "Bearer old-token"}};
  20322. sse::SSEClient sse(client, "/auth-check", headers);
  20323. // Update headers on each successful connection
  20324. sse.on_open(
  20325. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  20326. sse.set_reconnect_interval(100);
  20327. sse.set_max_reconnect_attempts(3);
  20328. sse.start_async();
  20329. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20330. sse.stop();
  20331. std::lock_guard<std::mutex> lock(token_mutex);
  20332. ASSERT_GE(received_tokens.size(), 2u);
  20333. // First connection uses original header
  20334. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  20335. // Second connection uses updated header from set_headers
  20336. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20337. }
  20338. // Test: 401 allows reconnection (so on_error can refresh headers)
  20339. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20340. std::atomic<int> connection_count{0};
  20341. // Endpoint: returns 401 on first attempt, 200 on second
  20342. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20343. int conn = connection_count.fetch_add(1);
  20344. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20345. res.status = StatusCode::Unauthorized_401;
  20346. res.set_content("Unauthorized", "text/plain");
  20347. return;
  20348. }
  20349. res.set_chunked_content_provider(
  20350. "text/event-stream", [](size_t offset, DataSink &sink) {
  20351. if (offset == 0) {
  20352. std::string event = "data: authenticated\n\n";
  20353. sink.write(event.data(), event.size());
  20354. }
  20355. return false;
  20356. });
  20357. });
  20358. Client client("localhost", get_port());
  20359. Headers headers = {{"Authorization", "Bearer expired"}};
  20360. sse::SSEClient sse(client, "/auth-retry", headers);
  20361. std::atomic<bool> message_received{false};
  20362. // Refresh token on error
  20363. sse.on_error(
  20364. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20365. sse.on_message([&](const sse::SSEMessage &msg) {
  20366. if (msg.data == "authenticated") { message_received.store(true); }
  20367. });
  20368. sse.set_reconnect_interval(100);
  20369. sse.set_max_reconnect_attempts(3);
  20370. sse.start_async();
  20371. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20372. sse.stop();
  20373. // Should have reconnected after 401 and succeeded with new token
  20374. EXPECT_GE(connection_count.load(), 2);
  20375. EXPECT_TRUE(message_received.load());
  20376. }
  20377. TEST(Issue2318Test, EmptyHostString) {
  20378. {
  20379. httplib::Client cli_empty("", PORT);
  20380. auto res = cli_empty.Get("/");
  20381. ASSERT_FALSE(res);
  20382. EXPECT_EQ(httplib::Error::Connection, res.error());
  20383. }
  20384. {
  20385. httplib::Client cli(" ", PORT);
  20386. auto res = cli.Get("/");
  20387. ASSERT_FALSE(res);
  20388. EXPECT_EQ(httplib::Error::Connection, res.error());
  20389. }
  20390. }
  20391. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20392. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20393. Server svr;
  20394. // Set a small payload limit (1KB)
  20395. svr.set_payload_max_length(1024);
  20396. svr.Post("/test", [&](const Request &req, Response &res) {
  20397. res.set_content("Body size: " + std::to_string(req.body.size()),
  20398. "text/plain");
  20399. });
  20400. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20401. auto se = detail::scope_exit([&] {
  20402. svr.stop();
  20403. listen_thread.join();
  20404. });
  20405. svr.wait_until_ready();
  20406. // Create data that compresses well but exceeds limit when decompressed
  20407. // 8KB of repeated null bytes compresses to a very small size
  20408. std::string original_data(8 * 1024, '\0');
  20409. // Compress the data using gzip
  20410. std::string compressed_data;
  20411. detail::gzip_compressor compressor;
  20412. compressor.compress(original_data.data(), original_data.size(), true,
  20413. [&](const char *data, size_t size) {
  20414. compressed_data.append(data, size);
  20415. return true;
  20416. });
  20417. // Verify compression worked (compressed should be much smaller)
  20418. ASSERT_LT(compressed_data.size(), original_data.size());
  20419. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20420. // Send compressed data with Content-Encoding: gzip
  20421. Client cli(HOST, PORT);
  20422. Headers headers = {{"Content-Encoding", "gzip"}};
  20423. auto res =
  20424. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20425. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20427. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20428. }
  20429. #endif
  20430. // ============================================================================
  20431. // OpenSSL-Specific Tests
  20432. // ============================================================================
  20433. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20434. X509 *readCertificate(const std::string &strFileName) {
  20435. std::ifstream inStream(strFileName);
  20436. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20437. std::istreambuf_iterator<char>());
  20438. if (strCertPEM.empty()) return (nullptr);
  20439. BIO *pbCert = BIO_new(BIO_s_mem());
  20440. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20441. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20442. BIO_free(pbCert);
  20443. return (pCert);
  20444. }
  20445. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20446. std::ifstream inStream(strFileName);
  20447. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20448. std::istreambuf_iterator<char>());
  20449. if (strPrivateKeyPEM.empty()) return (nullptr);
  20450. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20451. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20452. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20453. BIO_free(pbPrivKey);
  20454. return (pPrivateKey);
  20455. }
  20456. TEST(BindServerTest, UpdateCerts) {
  20457. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20458. int port = svr.bind_to_any_port("0.0.0.0");
  20459. ASSERT_TRUE(svr.is_valid());
  20460. ASSERT_TRUE(port > 0);
  20461. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20462. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20463. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20464. ASSERT_TRUE(cert != nullptr);
  20465. ASSERT_TRUE(ca_cert != nullptr);
  20466. ASSERT_TRUE(key != nullptr);
  20467. X509_STORE *cert_store = X509_STORE_new();
  20468. X509_STORE_add_cert(cert_store, ca_cert);
  20469. // svr.update_certs(cert, key, cert_store); // deprecated
  20470. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20471. CLIENT_CA_CERT_FILE);
  20472. ASSERT_TRUE(svr.is_valid());
  20473. svr.stop();
  20474. X509_STORE_free(cert_store);
  20475. X509_free(cert);
  20476. X509_free(ca_cert);
  20477. EVP_PKEY_free(key);
  20478. }
  20479. // Test that update_certs() updates client CA list correctly
  20480. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  20481. // Start with file-based constructor
  20482. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20483. ASSERT_TRUE(svr.is_valid());
  20484. // Initially no client CA list should be set
  20485. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20486. ASSERT_TRUE(ssl_ctx != nullptr);
  20487. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  20488. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  20489. EXPECT_EQ(0, count_before);
  20490. // Now update with client CA (PEM string)
  20491. std::string cert_pem, key_pem, ca_pem;
  20492. read_file(SERVER_CERT_FILE, cert_pem);
  20493. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  20494. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  20495. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  20496. ASSERT_TRUE(svr.is_valid());
  20497. // Now client CA list should be set
  20498. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  20499. ASSERT_TRUE(ca_list_after != nullptr);
  20500. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  20501. }
  20502. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  20503. // Test that the file-path SSLServer constructor properly sets the client CA
  20504. // list that is sent to clients during the TLS handshake (CertificateRequest)
  20505. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20506. ASSERT_TRUE(svr.is_valid());
  20507. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20508. ASSERT_TRUE(ssl_ctx != nullptr);
  20509. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  20510. ASSERT_TRUE(ca_list != nullptr);
  20511. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  20512. }
  20513. #endif
  20514. // ============================================================================
  20515. // MbedTLS-Specific Tests
  20516. // ============================================================================
  20517. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  20518. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  20519. using namespace httplib::tls;
  20520. // Track if callback was invoked
  20521. bool callback_invoked = false;
  20522. // The callback receives void* ctx which is actually MbedTlsContext*
  20523. // We can access the mbedtls_ssl_config via the context
  20524. auto setup_callback = [&callback_invoked](void *ctx) {
  20525. callback_invoked = true;
  20526. // Cast to MbedTlsContext* to access the ssl config
  20527. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  20528. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  20529. // Use static variables to hold certificate data (simplified for test)
  20530. static mbedtls_x509_crt own_cert;
  20531. static mbedtls_pk_context own_key;
  20532. static mbedtls_x509_crt ca_chain;
  20533. static bool initialized = false;
  20534. if (!initialized) {
  20535. mbedtls_x509_crt_init(&own_cert);
  20536. mbedtls_pk_init(&own_key);
  20537. mbedtls_x509_crt_init(&ca_chain);
  20538. // Load server certificate
  20539. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  20540. return false;
  20541. }
  20542. // Load server private key.
  20543. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  20544. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  20545. #if MBEDTLS_VERSION_MAJOR == 3
  20546. ,
  20547. mbedtls_ctr_drbg_random, nullptr
  20548. #endif
  20549. ) != 0) {
  20550. return false;
  20551. }
  20552. // Load CA chain for client verification
  20553. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  20554. return false;
  20555. }
  20556. initialized = true;
  20557. }
  20558. // Configure the SSL config
  20559. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  20560. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  20561. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  20562. // Set minimum TLS version using mbedTLS native API
  20563. #if MBEDTLS_VERSION_MAJOR >= 3
  20564. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  20565. #else
  20566. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  20567. MBEDTLS_SSL_MINOR_VERSION_3);
  20568. #endif
  20569. return true;
  20570. };
  20571. SSLServer svr(setup_callback);
  20572. ASSERT_TRUE(svr.is_valid());
  20573. ASSERT_TRUE(callback_invoked);
  20574. svr.Get("/test", [&](const Request &req, Response &res) {
  20575. res.set_content("test", "text/plain");
  20576. auto cert = req.peer_cert();
  20577. ASSERT_TRUE(static_cast<bool>(cert));
  20578. auto common_name = cert.subject_cn();
  20579. EXPECT_EQ("Common Name", common_name);
  20580. });
  20581. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20582. auto se = detail::scope_exit([&] {
  20583. svr.stop();
  20584. t.join();
  20585. ASSERT_FALSE(svr.is_running());
  20586. });
  20587. svr.wait_until_ready();
  20588. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  20589. cli.enable_server_certificate_verification(false);
  20590. cli.set_connection_timeout(30);
  20591. auto res = cli.Get("/test");
  20592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20593. ASSERT_EQ(StatusCode::OK_200, res->status);
  20594. }
  20595. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  20596. // context (owning mbedtls_ssl_config) before shutting down a still-open
  20597. // keep-alive SSL session, which reads through that config in
  20598. // mbedtls_ssl_close_notify.
  20599. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  20600. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20601. ASSERT_TRUE(svr.is_valid());
  20602. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  20603. res.set_content("test", "text/plain");
  20604. });
  20605. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20606. auto se = detail::scope_exit([&] {
  20607. svr.stop();
  20608. t.join();
  20609. ASSERT_FALSE(svr.is_running());
  20610. });
  20611. svr.wait_until_ready();
  20612. {
  20613. SSLClient cli(HOST, PORT);
  20614. cli.enable_server_certificate_verification(false);
  20615. cli.set_keep_alive(true);
  20616. auto res = cli.Get("/test");
  20617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20618. ASSERT_EQ(StatusCode::OK_200, res->status);
  20619. // cli is destructed here with the keep-alive SSL session still open.
  20620. }
  20621. }
  20622. #endif
  20623. // WebSocket Tests
  20624. TEST(WebSocketTest, RSVBitsMustBeZero) {
  20625. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  20626. // defining the meaning of these bits has been negotiated.
  20627. auto make_frame = [](uint8_t first_byte) {
  20628. std::string frame;
  20629. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  20630. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  20631. frame += "Hello";
  20632. return frame;
  20633. };
  20634. // RSV1 set (0x40)
  20635. {
  20636. detail::BufferStream strm;
  20637. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  20638. ws::Opcode opcode;
  20639. std::string payload;
  20640. bool fin;
  20641. EXPECT_EQ(
  20642. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20643. ws::impl::FrameRead::Fail);
  20644. }
  20645. // RSV2 set (0x20)
  20646. {
  20647. detail::BufferStream strm;
  20648. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  20649. ws::Opcode opcode;
  20650. std::string payload;
  20651. bool fin;
  20652. EXPECT_EQ(
  20653. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20654. ws::impl::FrameRead::Fail);
  20655. }
  20656. // RSV3 set (0x10)
  20657. {
  20658. detail::BufferStream strm;
  20659. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  20660. ws::Opcode opcode;
  20661. std::string payload;
  20662. bool fin;
  20663. EXPECT_EQ(
  20664. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20665. ws::impl::FrameRead::Fail);
  20666. }
  20667. // No RSV bits set - should succeed
  20668. {
  20669. detail::BufferStream strm;
  20670. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  20671. ws::Opcode opcode;
  20672. std::string payload;
  20673. bool fin;
  20674. EXPECT_EQ(
  20675. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20676. ws::impl::FrameRead::Ok);
  20677. EXPECT_EQ(ws::Opcode::Text, opcode);
  20678. EXPECT_EQ("Hello", payload);
  20679. EXPECT_TRUE(fin);
  20680. }
  20681. }
  20682. TEST(WebSocketTest, ControlFrameValidation) {
  20683. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  20684. // payload length <= 125.
  20685. // Ping with FIN=0 - must be rejected
  20686. {
  20687. detail::BufferStream strm;
  20688. std::string frame;
  20689. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  20690. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20691. strm.write(frame.data(), frame.size());
  20692. ws::Opcode opcode;
  20693. std::string payload;
  20694. bool fin;
  20695. EXPECT_EQ(
  20696. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20697. ws::impl::FrameRead::Fail);
  20698. }
  20699. // Close with FIN=0 - must be rejected
  20700. {
  20701. detail::BufferStream strm;
  20702. std::string frame;
  20703. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  20704. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20705. strm.write(frame.data(), frame.size());
  20706. ws::Opcode opcode;
  20707. std::string payload;
  20708. bool fin;
  20709. EXPECT_EQ(
  20710. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20711. ws::impl::FrameRead::Fail);
  20712. }
  20713. // Ping with payload_len=126 (extended length) - must be rejected
  20714. {
  20715. detail::BufferStream strm;
  20716. std::string frame;
  20717. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20718. frame += static_cast<char>(126); // payload_len=126 (>125)
  20719. frame += static_cast<char>(0x00); // extended length high byte
  20720. frame += static_cast<char>(126); // extended length low byte
  20721. frame += std::string(126, 'x');
  20722. strm.write(frame.data(), frame.size());
  20723. ws::Opcode opcode;
  20724. std::string payload;
  20725. bool fin;
  20726. EXPECT_EQ(
  20727. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20728. ws::impl::FrameRead::Fail);
  20729. }
  20730. // Ping with FIN=1 and payload_len=125 - should succeed
  20731. {
  20732. detail::BufferStream strm;
  20733. std::string frame;
  20734. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20735. frame += static_cast<char>(125); // payload_len=125
  20736. frame += std::string(125, 'x');
  20737. strm.write(frame.data(), frame.size());
  20738. ws::Opcode opcode;
  20739. std::string payload;
  20740. bool fin;
  20741. EXPECT_EQ(
  20742. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20743. ws::impl::FrameRead::Ok);
  20744. EXPECT_EQ(ws::Opcode::Ping, opcode);
  20745. EXPECT_EQ(125u, payload.size());
  20746. EXPECT_TRUE(fin);
  20747. }
  20748. }
  20749. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  20750. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  20751. // length MUST be 0.
  20752. // MSB set - must be rejected
  20753. {
  20754. detail::BufferStream strm;
  20755. std::string frame;
  20756. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20757. frame += static_cast<char>(127); // 64-bit extended length
  20758. frame += static_cast<char>(0x80); // MSB set (invalid)
  20759. frame += std::string(7, '\0'); // remaining 7 bytes of length
  20760. strm.write(frame.data(), frame.size());
  20761. ws::Opcode opcode;
  20762. std::string payload;
  20763. bool fin;
  20764. EXPECT_EQ(
  20765. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20766. ws::impl::FrameRead::Fail);
  20767. }
  20768. // MSB clear - should pass length parsing (will be rejected by max_len,
  20769. // but that's a different check; use a small length to verify)
  20770. {
  20771. detail::BufferStream strm;
  20772. std::string frame;
  20773. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20774. frame += static_cast<char>(127); // 64-bit extended length
  20775. frame += std::string(7, '\0'); // high bytes = 0
  20776. frame += static_cast<char>(0x03); // length = 3
  20777. frame += "abc";
  20778. strm.write(frame.data(), frame.size());
  20779. ws::Opcode opcode;
  20780. std::string payload;
  20781. bool fin;
  20782. EXPECT_EQ(
  20783. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20784. ws::impl::FrameRead::Ok);
  20785. EXPECT_EQ(ws::Opcode::Text, opcode);
  20786. EXPECT_EQ("abc", payload);
  20787. }
  20788. }
  20789. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  20790. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  20791. // Valid UTF-8
  20792. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  20793. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  20794. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  20795. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  20796. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  20797. // Invalid UTF-8
  20798. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  20799. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  20800. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  20801. EXPECT_FALSE(
  20802. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  20803. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  20804. }
  20805. TEST(WebSocketTest, ConnectAndDisconnect) {
  20806. Server svr;
  20807. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20808. std::string msg;
  20809. while (ws.read(msg)) {}
  20810. });
  20811. auto port = svr.bind_to_any_port(HOST);
  20812. std::thread t([&]() { svr.listen_after_bind(); });
  20813. svr.wait_until_ready();
  20814. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20815. auto res = client.connect();
  20816. ASSERT_TRUE(res);
  20817. EXPECT_EQ(Error::Success, res.error());
  20818. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  20819. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  20820. EXPECT_TRUE(client.is_open());
  20821. client.close();
  20822. EXPECT_FALSE(client.is_open());
  20823. svr.stop();
  20824. t.join();
  20825. }
  20826. TEST(WebSocketTest, ValidURL) {
  20827. ws::WebSocketClient ws1("ws://localhost:8080/path");
  20828. EXPECT_TRUE(ws1.is_valid());
  20829. ws::WebSocketClient ws2("ws://example.com/path");
  20830. EXPECT_TRUE(ws2.is_valid());
  20831. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  20832. EXPECT_TRUE(ws3.is_valid());
  20833. #ifdef CPPHTTPLIB_SSL_ENABLED
  20834. ws::WebSocketClient wss1("wss://example.com/path");
  20835. EXPECT_TRUE(wss1.is_valid());
  20836. ws::WebSocketClient wss2("wss://example.com:443/path");
  20837. EXPECT_TRUE(wss2.is_valid());
  20838. #endif
  20839. }
  20840. TEST(WebSocketTest, InvalidURL) {
  20841. // No scheme
  20842. ws::WebSocketClient ws1("localhost:8080/path");
  20843. EXPECT_FALSE(ws1.is_valid());
  20844. // No path
  20845. ws::WebSocketClient ws2("ws://localhost:8080");
  20846. EXPECT_FALSE(ws2.is_valid());
  20847. // Empty string
  20848. ws::WebSocketClient ws3("");
  20849. EXPECT_FALSE(ws3.is_valid());
  20850. // Missing host
  20851. ws::WebSocketClient ws4("ws://:8080/path");
  20852. EXPECT_FALSE(ws4.is_valid());
  20853. // Port number overflow — should not crash
  20854. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  20855. EXPECT_FALSE(ws5.is_valid());
  20856. // Port out of range
  20857. ws::WebSocketClient ws6("ws://localhost:99999/path");
  20858. EXPECT_FALSE(ws6.is_valid());
  20859. }
  20860. TEST(WebSocketTest, UnsupportedScheme) {
  20861. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  20862. ws::WebSocketClient ws1("http://localhost:8080/path");
  20863. EXPECT_FALSE(ws1.is_valid());
  20864. ws::WebSocketClient ws2("https://localhost:8080/path");
  20865. EXPECT_FALSE(ws2.is_valid());
  20866. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  20867. EXPECT_FALSE(ws3.is_valid());
  20868. #else
  20869. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  20870. std::invalid_argument);
  20871. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  20872. std::invalid_argument);
  20873. #endif
  20874. }
  20875. TEST(WebSocketTest, ConnectWhenInvalid) {
  20876. ws::WebSocketClient ws("not a valid url");
  20877. EXPECT_FALSE(ws.is_valid());
  20878. auto res = ws.connect();
  20879. EXPECT_FALSE(res);
  20880. EXPECT_EQ(Error::Connection, res.error());
  20881. EXPECT_EQ(-1, res.status());
  20882. }
  20883. TEST(WebSocketTest, ConnectRefusedReportsError) {
  20884. // Grab a port that is free, then close it again so nothing listens there
  20885. Server svr;
  20886. auto port = svr.bind_to_any_port(HOST);
  20887. svr.stop();
  20888. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20889. auto res = client.connect();
  20890. ASSERT_FALSE(res);
  20891. EXPECT_EQ(Error::Connection, res.error());
  20892. EXPECT_EQ(-1, res.status());
  20893. }
  20894. TEST(WebSocketTest, DefaultPort) {
  20895. ws::WebSocketClient ws1("ws://example.com/path");
  20896. EXPECT_TRUE(ws1.is_valid());
  20897. // ws:// defaults to port 80 (verified by successful parse)
  20898. #ifdef CPPHTTPLIB_SSL_ENABLED
  20899. ws::WebSocketClient ws2("wss://example.com/path");
  20900. EXPECT_TRUE(ws2.is_valid());
  20901. // wss:// defaults to port 443 (verified by successful parse)
  20902. #endif
  20903. }
  20904. TEST(WebSocketTest, IPv6LiteralAddress) {
  20905. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  20906. EXPECT_TRUE(ws1.is_valid());
  20907. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  20908. EXPECT_TRUE(ws2.is_valid());
  20909. }
  20910. TEST(WebSocketTest, ComplexPath) {
  20911. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  20912. EXPECT_TRUE(ws1.is_valid());
  20913. ws::WebSocketClient ws2("ws://localhost:8080/");
  20914. EXPECT_TRUE(ws2.is_valid());
  20915. }
  20916. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  20917. Server svr;
  20918. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20919. std::string msg;
  20920. while (ws.read(msg)) {}
  20921. });
  20922. auto port = svr.bind_to_any_port(HOST);
  20923. std::thread t([&]() { svr.listen_after_bind(); });
  20924. svr.wait_until_ready();
  20925. auto another_host = "example.com";
  20926. auto wrong_ip = "192.0.2.1";
  20927. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20928. client.set_hostname_addr_map({{another_host, wrong_ip}});
  20929. ASSERT_TRUE(client.connect());
  20930. EXPECT_TRUE(client.is_open());
  20931. client.close();
  20932. svr.stop();
  20933. t.join();
  20934. }
  20935. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  20936. Server svr;
  20937. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20938. std::string msg;
  20939. while (ws.read(msg)) {}
  20940. });
  20941. auto port = svr.bind_to_any_port(HOST);
  20942. std::thread t([&]() { svr.listen_after_bind(); });
  20943. svr.wait_until_ready();
  20944. auto wrong_ip = "192.0.2.1";
  20945. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20946. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  20947. client.set_connection_timeout(1);
  20948. client.set_read_timeout(1);
  20949. client.set_write_timeout(1);
  20950. EXPECT_FALSE(client.connect());
  20951. EXPECT_FALSE(client.is_open());
  20952. svr.stop();
  20953. t.join();
  20954. }
  20955. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  20956. // A mapped value that is not an IP literal must be resolved. HOST resolves
  20957. // from the hosts file, so this test needs no external DNS. "target.invalid"
  20958. // (RFC 6761) is only a map key and the Host header value.
  20959. auto host = "target.invalid";
  20960. Server svr;
  20961. std::string received_host;
  20962. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20963. received_host = req.get_header_value("Host");
  20964. std::string msg;
  20965. while (ws.read(msg)) {}
  20966. });
  20967. auto port = svr.bind_to_any_port(HOST);
  20968. std::thread t([&]() { svr.listen_after_bind(); });
  20969. // ASSERT_* below returns from the test body, which would leave t joinable
  20970. // and make ~thread call std::terminate.
  20971. auto se = detail::scope_exit([&] {
  20972. svr.stop();
  20973. if (t.joinable()) { t.join(); }
  20974. });
  20975. svr.wait_until_ready();
  20976. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  20977. std::to_string(port) + "/ws");
  20978. client.set_hostname_addr_map({{host, HOST}});
  20979. ASSERT_TRUE(client.connect());
  20980. EXPECT_TRUE(client.is_open());
  20981. client.close();
  20982. svr.stop();
  20983. t.join();
  20984. // The mapping only redirects the connection; the identity stays host_.
  20985. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  20986. }
  20987. class WebSocketIntegrationTest : public ::testing::Test {
  20988. protected:
  20989. void SetUp() override {
  20990. server_ = httplib::detail::make_unique<Server>();
  20991. setup_server();
  20992. start_server();
  20993. }
  20994. void TearDown() override {
  20995. server_->stop();
  20996. if (server_thread_.joinable()) { server_thread_.join(); }
  20997. }
  20998. void setup_server() {
  20999. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21000. std::string msg;
  21001. ws::ReadResult ret;
  21002. while ((ret = ws.read(msg))) {
  21003. if (ret == ws::Binary) {
  21004. ws.send(msg.data(), msg.size());
  21005. } else {
  21006. ws.send(msg);
  21007. }
  21008. }
  21009. });
  21010. server_->WebSocket("/ws-echo-string",
  21011. [](const Request &, ws::WebSocket &ws) {
  21012. std::string msg;
  21013. while (ws.read(msg)) {
  21014. ws.send("echo: " + msg);
  21015. }
  21016. });
  21017. server_->WebSocket(
  21018. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  21019. // Echo back request metadata
  21020. ws.send("path:" + req.path);
  21021. ws.send("header:" + req.get_header_value("X-Test-Header"));
  21022. std::string msg;
  21023. while (ws.read(msg)) {}
  21024. });
  21025. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  21026. std::string msg;
  21027. ws.read(msg); // wait for a message
  21028. ws.close();
  21029. });
  21030. server_->WebSocket("/ws-close-status",
  21031. [](const Request &, ws::WebSocket &ws) {
  21032. std::string msg;
  21033. ws.read(msg); // wait for a message
  21034. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  21035. });
  21036. server_->WebSocket(
  21037. "/ws-subprotocol",
  21038. [](const Request &, ws::WebSocket &ws) {
  21039. std::string msg;
  21040. while (ws.read(msg)) {
  21041. ws.send(msg);
  21042. }
  21043. },
  21044. [](const std::vector<std::string> &protocols) -> std::string {
  21045. for (const auto &p : protocols) {
  21046. if (p == "graphql-ws") { return p; }
  21047. }
  21048. return "";
  21049. });
  21050. server_->WebSocket(
  21051. "/ws-subprotocol-unoffered",
  21052. [](const Request &, ws::WebSocket &ws) {
  21053. std::string msg;
  21054. while (ws.read(msg)) {
  21055. ws.send(msg);
  21056. }
  21057. },
  21058. [](const std::vector<std::string> &) -> std::string {
  21059. return "admin";
  21060. });
  21061. }
  21062. void start_server() {
  21063. port_ = server_->bind_to_any_port(HOST);
  21064. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21065. server_->wait_until_ready();
  21066. }
  21067. std::unique_ptr<Server> server_;
  21068. std::thread server_thread_;
  21069. int port_ = 0;
  21070. };
  21071. TEST_F(WebSocketIntegrationTest, TextEcho) {
  21072. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21073. "/ws-echo");
  21074. ASSERT_TRUE(client.connect());
  21075. ASSERT_TRUE(client.is_open());
  21076. ASSERT_TRUE(client.send("Hello WebSocket"));
  21077. std::string msg;
  21078. EXPECT_EQ(ws::Text, client.read(msg));
  21079. EXPECT_EQ("Hello WebSocket", msg);
  21080. client.close();
  21081. }
  21082. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  21083. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21084. "/ws-echo");
  21085. ASSERT_TRUE(client.connect());
  21086. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  21087. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  21088. std::string msg;
  21089. EXPECT_EQ(ws::Binary, client.read(msg));
  21090. EXPECT_EQ(binary_data, msg);
  21091. client.close();
  21092. }
  21093. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  21094. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21095. "/ws-echo");
  21096. ASSERT_TRUE(client.connect());
  21097. for (int i = 0; i < 10; i++) {
  21098. auto text = "message " + std::to_string(i);
  21099. ASSERT_TRUE(client.send(text));
  21100. std::string msg;
  21101. ASSERT_TRUE(client.read(msg));
  21102. EXPECT_EQ(text, msg);
  21103. }
  21104. client.close();
  21105. }
  21106. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  21107. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21108. "/ws-close");
  21109. ASSERT_TRUE(client.connect());
  21110. // Send a message to trigger the server to close
  21111. ASSERT_TRUE(client.send("trigger close"));
  21112. // The server will close, so read should return false
  21113. std::string msg;
  21114. EXPECT_FALSE(client.read(msg));
  21115. EXPECT_FALSE(client.is_open());
  21116. }
  21117. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  21118. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21119. "/ws-echo");
  21120. ASSERT_TRUE(client.connect());
  21121. // 128KB message
  21122. std::string large_data(128 * 1024, 'X');
  21123. ASSERT_TRUE(client.send(large_data));
  21124. std::string msg;
  21125. ASSERT_TRUE(client.read(msg));
  21126. EXPECT_EQ(large_data, msg);
  21127. client.close();
  21128. }
  21129. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  21130. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21131. "/ws-echo");
  21132. ASSERT_TRUE(client.connect());
  21133. const int num_threads = 4;
  21134. std::vector<std::thread> threads;
  21135. std::atomic<int> send_count{0};
  21136. for (int t = 0; t < num_threads; t++) {
  21137. threads.emplace_back([&client, &send_count, t]() {
  21138. for (int i = 0; i < 5; i++) {
  21139. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  21140. if (client.send(text)) { send_count++; }
  21141. }
  21142. });
  21143. }
  21144. for (auto &th : threads) {
  21145. th.join();
  21146. }
  21147. int received = 0;
  21148. std::string msg;
  21149. while (received < send_count.load()) {
  21150. if (!client.read(msg)) { break; }
  21151. received++;
  21152. }
  21153. EXPECT_EQ(send_count.load(), received);
  21154. client.close();
  21155. }
  21156. TEST_F(WebSocketIntegrationTest, ReadString) {
  21157. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21158. "/ws-echo-string");
  21159. ASSERT_TRUE(client.connect());
  21160. ASSERT_TRUE(client.send("hello"));
  21161. std::string msg;
  21162. ASSERT_TRUE(client.read(msg));
  21163. EXPECT_EQ("echo: hello", msg);
  21164. ASSERT_TRUE(client.send("world"));
  21165. ASSERT_TRUE(client.read(msg));
  21166. EXPECT_EQ("echo: world", msg);
  21167. client.close();
  21168. }
  21169. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  21170. Headers headers = {{"X-Test-Header", "test-value"}};
  21171. ws::WebSocketClient client(
  21172. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  21173. ASSERT_TRUE(client.connect());
  21174. std::string msg;
  21175. ASSERT_TRUE(client.read(msg));
  21176. EXPECT_EQ("path:/ws-request-info", msg);
  21177. ASSERT_TRUE(client.read(msg));
  21178. EXPECT_EQ("header:test-value", msg);
  21179. client.close();
  21180. }
  21181. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  21182. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21183. "/ws-echo");
  21184. client.set_read_timeout(1, 0); // 1 second
  21185. ASSERT_TRUE(client.connect());
  21186. // Don't send anything — server echo handler waits for a message, so read()
  21187. // should time out. The connection survives it: nothing was consumed.
  21188. std::string msg;
  21189. EXPECT_EQ(client.read(msg), ws::Timeout);
  21190. EXPECT_TRUE(client.is_open());
  21191. // And it is still usable afterwards.
  21192. EXPECT_TRUE(client.send("after timeout"));
  21193. EXPECT_EQ(client.read(msg), ws::Text);
  21194. EXPECT_EQ(msg, "after timeout");
  21195. }
  21196. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  21197. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21198. "/ws-echo");
  21199. client.set_read_timeout(1, 0);
  21200. ASSERT_TRUE(client.connect());
  21201. ASSERT_TRUE(client.send("first"));
  21202. std::string msg;
  21203. ASSERT_EQ(client.read(msg), ws::Text);
  21204. ASSERT_EQ(msg, "first");
  21205. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  21206. // not be used with a read timeout: it would reprocess the previous message.
  21207. EXPECT_EQ(client.read(msg), ws::Timeout);
  21208. EXPECT_EQ(msg, "first");
  21209. }
  21210. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  21211. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21212. "/ws-echo");
  21213. ASSERT_TRUE(client.connect());
  21214. // Setting it once the connection is open reaches the live stream, not just
  21215. // the seed for the next connect().
  21216. client.set_read_timeout(1, 0);
  21217. std::string msg;
  21218. EXPECT_EQ(client.read(msg), ws::Timeout);
  21219. EXPECT_TRUE(client.is_open());
  21220. }
  21221. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  21222. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21223. "/ws-echo");
  21224. client.set_read_timeout(5, 0);
  21225. ASSERT_TRUE(client.connect());
  21226. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21227. // The server should reject it and close the connection.
  21228. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  21229. client.send(oversized);
  21230. // The server's read() should have failed due to payload limit,
  21231. // so our read() should return false (connection closed).
  21232. std::string msg;
  21233. EXPECT_FALSE(client.read(msg));
  21234. }
  21235. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  21236. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21237. "/ws-echo");
  21238. client.set_read_timeout(10, 0);
  21239. ASSERT_TRUE(client.connect());
  21240. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21241. // This should succeed.
  21242. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  21243. ASSERT_TRUE(client.send(at_limit));
  21244. std::string msg;
  21245. ASSERT_TRUE(client.read(msg));
  21246. EXPECT_EQ(at_limit.size(), msg.size());
  21247. client.close();
  21248. }
  21249. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  21250. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21251. "/nonexistent");
  21252. auto res = client.connect();
  21253. EXPECT_FALSE(res);
  21254. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21255. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  21256. EXPECT_FALSE(client.is_open());
  21257. }
  21258. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  21259. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21260. "/ws-echo");
  21261. ASSERT_TRUE(client.connect());
  21262. ASSERT_TRUE(client.send(""));
  21263. std::string msg;
  21264. EXPECT_EQ(ws::Text, client.read(msg));
  21265. EXPECT_EQ("", msg);
  21266. client.close();
  21267. }
  21268. TEST_F(WebSocketIntegrationTest, Reconnect) {
  21269. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21270. "/ws-echo");
  21271. // First connection
  21272. ASSERT_TRUE(client.connect());
  21273. ASSERT_TRUE(client.send("first"));
  21274. std::string msg;
  21275. ASSERT_TRUE(client.read(msg));
  21276. EXPECT_EQ("first", msg);
  21277. client.close();
  21278. EXPECT_FALSE(client.is_open());
  21279. // Reconnect using the same client object
  21280. ASSERT_TRUE(client.connect());
  21281. ASSERT_TRUE(client.is_open());
  21282. ASSERT_TRUE(client.send("second"));
  21283. ASSERT_TRUE(client.read(msg));
  21284. EXPECT_EQ("second", msg);
  21285. client.close();
  21286. }
  21287. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  21288. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21289. "/ws-close-status");
  21290. ASSERT_TRUE(client.connect());
  21291. // Trigger the server to close with GoingAway status
  21292. ASSERT_TRUE(client.send("trigger"));
  21293. // read() should return false after receiving the close frame
  21294. std::string msg;
  21295. EXPECT_FALSE(client.read(msg));
  21296. EXPECT_FALSE(client.is_open());
  21297. }
  21298. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  21299. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21300. "/ws-echo");
  21301. ASSERT_TRUE(client.connect());
  21302. client.close(ws::CloseStatus::GoingAway, "client leaving");
  21303. EXPECT_FALSE(client.is_open());
  21304. }
  21305. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  21306. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  21307. ws::WebSocketClient client(
  21308. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21309. ASSERT_TRUE(client.connect());
  21310. // Server should have selected graphql-ws
  21311. EXPECT_EQ("graphql-ws", client.subprotocol());
  21312. client.close();
  21313. }
  21314. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  21315. Headers headers;
  21316. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  21317. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  21318. ws::WebSocketClient client(
  21319. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21320. ASSERT_TRUE(client.connect());
  21321. // The offer on the second field line counts too, so graphql-ws is selected
  21322. EXPECT_EQ("graphql-ws", client.subprotocol());
  21323. client.close();
  21324. }
  21325. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  21326. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  21327. ws::WebSocketClient client(
  21328. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21329. ASSERT_TRUE(client.connect());
  21330. // Server should not have selected any subprotocol
  21331. EXPECT_TRUE(client.subprotocol().empty());
  21332. client.close();
  21333. }
  21334. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  21335. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21336. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21337. "/ws-subprotocol-unoffered",
  21338. headers);
  21339. ASSERT_TRUE(client.connect());
  21340. EXPECT_TRUE(client.subprotocol().empty());
  21341. client.close();
  21342. }
  21343. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21344. // Connect without requesting any subprotocol
  21345. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21346. "/ws-subprotocol");
  21347. ASSERT_TRUE(client.connect());
  21348. EXPECT_TRUE(client.subprotocol().empty());
  21349. client.close();
  21350. }
  21351. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21352. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21353. "/ws-echo");
  21354. client.set_tcp_nodelay(true);
  21355. client.set_connection_timeout(3, 0);
  21356. bool socket_options_called = false;
  21357. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21358. ASSERT_TRUE(client.connect());
  21359. ASSERT_TRUE(client.is_open());
  21360. EXPECT_TRUE(socket_options_called);
  21361. ASSERT_TRUE(client.send("hello"));
  21362. std::string msg;
  21363. auto result = client.read(msg);
  21364. EXPECT_EQ(result, ws::ReadResult::Text);
  21365. EXPECT_EQ(msg, "hello");
  21366. client.close();
  21367. }
  21368. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21369. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21370. "/ws-echo");
  21371. client.set_connection_timeout(std::chrono::seconds(3));
  21372. client.set_write_timeout(std::chrono::seconds(3));
  21373. // A sub-second remainder exercises the seconds/microseconds split.
  21374. client.set_read_timeout(std::chrono::milliseconds(1500));
  21375. ASSERT_TRUE(client.connect());
  21376. auto start = std::chrono::steady_clock::now();
  21377. std::string msg;
  21378. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21379. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21380. std::chrono::steady_clock::now() - start)
  21381. .count();
  21382. // Above 1s so that dropping the microseconds half of the split fails here.
  21383. // Ignoring the setter altogether would not reach this line at all: a client
  21384. // waits forever by default.
  21385. EXPECT_GE(elapsed, 1400);
  21386. EXPECT_LT(elapsed, 30000);
  21387. }
  21388. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21389. Server svr;
  21390. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21391. if (!req.has_header("Authorization")) {
  21392. res.status = StatusCode::Unauthorized_401;
  21393. res.set_content("Unauthorized", "text/plain");
  21394. return Server::HandlerResponse::Handled;
  21395. }
  21396. return Server::HandlerResponse::Unhandled;
  21397. });
  21398. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21399. std::string msg;
  21400. while (ws.read(msg)) {
  21401. ws.send(msg);
  21402. }
  21403. });
  21404. auto port = svr.bind_to_any_port("localhost");
  21405. std::thread t([&]() { svr.listen_after_bind(); });
  21406. svr.wait_until_ready();
  21407. // Without Authorization header - should be rejected before upgrade
  21408. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21409. EXPECT_FALSE(client1.connect());
  21410. // The rejection is framed like any other HTTP response
  21411. {
  21412. Client cli("localhost", port);
  21413. Headers headers = {{"Upgrade", "websocket"},
  21414. {"Connection", "Upgrade"},
  21415. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21416. {"Sec-WebSocket-Version", "13"}};
  21417. auto res = cli.Get("/ws", headers);
  21418. ASSERT_TRUE(res);
  21419. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21420. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21421. EXPECT_EQ("Unauthorized", res->body);
  21422. }
  21423. // With Authorization header - should succeed
  21424. Headers headers = {{"Authorization", "Bearer token123"}};
  21425. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21426. headers);
  21427. ASSERT_TRUE(client2.connect());
  21428. ASSERT_TRUE(client2.send("hello"));
  21429. std::string msg;
  21430. ASSERT_TRUE(client2.read(msg));
  21431. EXPECT_EQ("hello", msg);
  21432. client2.close();
  21433. svr.stop();
  21434. t.join();
  21435. }
  21436. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21437. Server svr;
  21438. std::atomic<int> pre_request_calls{0};
  21439. std::atomic<bool> route_matched{false};
  21440. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21441. pre_request_calls++;
  21442. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21443. if (req.get_header_value("Authorization") != "Bearer token123") {
  21444. res.status = StatusCode::Unauthorized_401;
  21445. res.set_content("Unauthorized", "text/plain");
  21446. return Server::HandlerResponse::Handled;
  21447. }
  21448. return Server::HandlerResponse::Unhandled;
  21449. });
  21450. std::atomic<bool> handler_called{false};
  21451. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21452. handler_called = true;
  21453. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21454. });
  21455. auto port = svr.bind_to_any_port("localhost");
  21456. std::thread t([&]() { svr.listen_after_bind(); });
  21457. svr.wait_until_ready();
  21458. // Without Authorization header - should be rejected before upgrade
  21459. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21460. "/ws/1");
  21461. EXPECT_FALSE(client1.connect());
  21462. EXPECT_FALSE(handler_called);
  21463. EXPECT_EQ(1, pre_request_calls);
  21464. EXPECT_TRUE(route_matched);
  21465. // The rejection is an ordinary HTTP response, not a protocol switch
  21466. {
  21467. Client cli("localhost", port);
  21468. Headers headers = {{"Upgrade", "websocket"},
  21469. {"Connection", "Upgrade"},
  21470. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21471. {"Sec-WebSocket-Version", "13"}};
  21472. auto res = cli.Get("/ws/1", headers);
  21473. ASSERT_TRUE(res);
  21474. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21475. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21476. EXPECT_EQ("Unauthorized", res->body);
  21477. }
  21478. EXPECT_FALSE(handler_called);
  21479. // With Authorization header - should succeed
  21480. Headers headers = {{"Authorization", "Bearer token123"}};
  21481. ws::WebSocketClient client2(
  21482. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  21483. ASSERT_TRUE(client2.connect());
  21484. std::string msg;
  21485. ASSERT_TRUE(client2.read(msg));
  21486. EXPECT_EQ("/ws/:id 2", msg);
  21487. EXPECT_TRUE(handler_called);
  21488. client2.close();
  21489. svr.stop();
  21490. t.join();
  21491. }
  21492. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  21493. Server svr;
  21494. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21495. // A read timeout is how a handler gets control back. Without it, a handler
  21496. // parked in read() can never write on the connection it is reading.
  21497. ws.set_read_timeout(std::chrono::milliseconds(100));
  21498. std::string msg;
  21499. while (ws.is_open()) {
  21500. auto r = ws.read(msg);
  21501. if (r == httplib::ws::Timeout) {
  21502. ws.send("tick");
  21503. continue;
  21504. }
  21505. if (r == httplib::ws::Fail) { break; }
  21506. ws.send(msg);
  21507. }
  21508. });
  21509. auto port = svr.bind_to_any_port("localhost");
  21510. std::thread t([&]() { svr.listen_after_bind(); });
  21511. svr.wait_until_ready();
  21512. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21513. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  21514. ASSERT_TRUE(client.connect());
  21515. // The client sends nothing, so anything it receives came out of the
  21516. // handler's timeout path.
  21517. std::string msg;
  21518. ASSERT_EQ(client.read(msg), ws::Text);
  21519. EXPECT_EQ("tick", msg);
  21520. client.close();
  21521. svr.stop();
  21522. t.join();
  21523. }
  21524. // Stream::read may return fewer bytes than asked for. This is that contract at
  21525. // its worst -- one byte per call -- which is what a frame header straddling a
  21526. // read buffer's boundary looks like to the frame parser.
  21527. class WsByteAtATimeStream : public Stream {
  21528. public:
  21529. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  21530. bool is_readable() const override { return true; }
  21531. bool wait_readable() const override { return true; }
  21532. bool wait_writable() const override { return true; }
  21533. ssize_t read(char *ptr, size_t size) override {
  21534. if (size == 0 || pos_ >= data_.size()) { return 0; }
  21535. *ptr = data_[pos_++];
  21536. return 1;
  21537. }
  21538. ssize_t write(const char *, size_t size) override {
  21539. return static_cast<ssize_t>(size);
  21540. }
  21541. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  21542. ip = "127.0.0.1";
  21543. port = 0;
  21544. }
  21545. void get_local_ip_and_port(std::string &ip, int &port) const override {
  21546. ip = "127.0.0.1";
  21547. port = 0;
  21548. }
  21549. socket_t socket() const override { return INVALID_SOCKET; }
  21550. time_t duration() const override { return 0; }
  21551. private:
  21552. std::string data_;
  21553. size_t pos_ = 0;
  21554. };
  21555. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  21556. // The payload uses the 16-bit extended length, so the header, the length
  21557. // and the mask key are all multi-byte fields here. Each used to be read
  21558. // with a single read() call, which fails as soon as one is split. The
  21559. // payload is also a little over one read chunk, so it is read in two.
  21560. std::string body;
  21561. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  21562. body += static_cast<char>(i % 251);
  21563. }
  21564. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  21565. std::string frame;
  21566. frame += static_cast<char>(0x81); // FIN + Text
  21567. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  21568. frame += static_cast<char>(body.size() >> 8);
  21569. frame += static_cast<char>(body.size() & 0xff);
  21570. for (size_t i = 0; i < 4; i++) {
  21571. frame += static_cast<char>(mask[i]);
  21572. }
  21573. for (size_t i = 0; i < body.size(); i++) {
  21574. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  21575. }
  21576. WsByteAtATimeStream strm(frame);
  21577. ws::Opcode opcode;
  21578. std::string payload;
  21579. bool fin = false;
  21580. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  21581. /*expect_masked=*/true, body.size()),
  21582. ws::impl::FrameRead::Ok);
  21583. EXPECT_TRUE(fin);
  21584. EXPECT_EQ(opcode, ws::Opcode::Text);
  21585. EXPECT_EQ(payload, body);
  21586. }
  21587. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  21588. // The header announces the largest payload allowed, and only 3 bytes of it
  21589. // ever arrive.
  21590. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  21591. std::string frame;
  21592. frame += static_cast<char>(0x82); // FIN + Binary
  21593. frame += static_cast<char>(127); // 64-bit length follows
  21594. for (int shift = 56; shift >= 0; shift -= 8) {
  21595. frame += static_cast<char>((len >> shift) & 0xff);
  21596. }
  21597. frame += "abc";
  21598. detail::BufferStream strm;
  21599. strm.write(frame.data(), frame.size());
  21600. ws::Opcode opcode;
  21601. std::string payload;
  21602. bool fin;
  21603. EXPECT_EQ(
  21604. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  21605. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  21606. ws::impl::FrameRead::Fail);
  21607. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  21608. }
  21609. TEST(WebSocketTest, QueryStringInHandshake) {
  21610. Server svr;
  21611. std::mutex mtx;
  21612. std::string received_target;
  21613. std::string received_token;
  21614. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21615. {
  21616. std::lock_guard<std::mutex> lock(mtx);
  21617. received_target = req.target;
  21618. if (req.has_param("token")) {
  21619. received_token = req.get_param_value("token");
  21620. }
  21621. }
  21622. std::string msg;
  21623. while (ws.read(msg)) {
  21624. ws.send(msg);
  21625. }
  21626. });
  21627. auto port = svr.bind_to_any_port("localhost");
  21628. std::thread t([&]() { svr.listen_after_bind(); });
  21629. svr.wait_until_ready();
  21630. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  21631. "/ws?token=ABC&session=123");
  21632. ASSERT_TRUE(client.connect());
  21633. // Round-trip ensures the handler has run and captured the request.
  21634. ASSERT_TRUE(client.send("hello"));
  21635. std::string msg;
  21636. ASSERT_TRUE(client.read(msg));
  21637. EXPECT_EQ("hello", msg);
  21638. client.close();
  21639. {
  21640. std::lock_guard<std::mutex> lock(mtx);
  21641. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  21642. EXPECT_EQ("ABC", received_token);
  21643. }
  21644. svr.stop();
  21645. t.join();
  21646. }
  21647. // Run a handshake against a throwaway server and hand the request the server
  21648. // received back to the caller, so tests can assert on the headers the client
  21649. // actually put on the wire.
  21650. static void capture_websocket_handshake_request(
  21651. const Headers &client_headers,
  21652. std::function<void(const Request &, int port)> verify) {
  21653. Server svr;
  21654. std::mutex mtx;
  21655. Request received;
  21656. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21657. {
  21658. std::lock_guard<std::mutex> lock(mtx);
  21659. received = req;
  21660. }
  21661. std::string msg;
  21662. while (ws.read(msg)) {
  21663. ws.send(msg);
  21664. }
  21665. });
  21666. auto port = svr.bind_to_any_port("localhost");
  21667. std::thread t([&]() { svr.listen_after_bind(); });
  21668. auto se = detail::scope_exit([&] {
  21669. svr.stop();
  21670. t.join();
  21671. });
  21672. svr.wait_until_ready();
  21673. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  21674. client_headers);
  21675. ASSERT_TRUE(client.connect());
  21676. ASSERT_TRUE(client.send("hello"));
  21677. std::string msg;
  21678. ASSERT_TRUE(client.read(msg));
  21679. client.close();
  21680. {
  21681. std::lock_guard<std::mutex> lock(mtx);
  21682. verify(received, port);
  21683. }
  21684. }
  21685. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  21686. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  21687. // Non-default port must be present in the Host header. Default ports
  21688. // (80/443) are omitted; that logic is covered by
  21689. // MakeHostAndPortStringTest.
  21690. EXPECT_EQ("localhost:" + std::to_string(port),
  21691. req.get_header_value("Host"));
  21692. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  21693. req.get_header_value("User-Agent"));
  21694. EXPECT_FALSE(req.has_header("Accept"));
  21695. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  21696. EXPECT_FALSE(req.has_header("Content-Length"));
  21697. });
  21698. }
  21699. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  21700. capture_websocket_handshake_request(
  21701. {{"Host", "example.com"},
  21702. {"User-Agent", "custom-agent"},
  21703. {"X-Custom", "value"}},
  21704. [](const Request &req, int) {
  21705. EXPECT_EQ("example.com", req.get_header_value("Host"));
  21706. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  21707. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  21708. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  21709. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  21710. });
  21711. }
  21712. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  21713. capture_websocket_handshake_request(
  21714. {{"Upgrade", "bogus"},
  21715. {"Connection", "close"},
  21716. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  21717. {"Sec-WebSocket-Version", "8"}},
  21718. [](const Request &req, int) {
  21719. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  21720. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  21721. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  21722. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  21723. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  21724. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  21725. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  21726. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  21727. req.get_header_value("Sec-WebSocket-Key"));
  21728. });
  21729. }
  21730. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  21731. // A header the client refuses to send must abort the handshake before any
  21732. // part of it reaches the wire; a lone request line would otherwise sit in
  21733. // the peer's buffer as a truncated request.
  21734. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21735. ASSERT_NE(INVALID_SOCKET, srv);
  21736. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  21737. sockaddr_in addr{};
  21738. addr.sin_family = AF_INET;
  21739. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  21740. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21741. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  21742. ASSERT_EQ(0, ::listen(srv, 1));
  21743. sockaddr_in bound{};
  21744. socklen_t bound_len = sizeof(bound);
  21745. ASSERT_EQ(
  21746. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  21747. auto port = ntohs(bound.sin_port);
  21748. ssize_t received = -1;
  21749. std::thread t([&] {
  21750. // Bound every blocking call so a regression fails the test with a bad
  21751. // value instead of hanging the suite.
  21752. fd_set rfds;
  21753. FD_ZERO(&rfds);
  21754. FD_SET(srv, &rfds);
  21755. timeval tv{5, 0};
  21756. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  21757. 0) {
  21758. return;
  21759. }
  21760. sockaddr_in cli_addr{};
  21761. socklen_t cli_len = sizeof(cli_addr);
  21762. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21763. if (cli == INVALID_SOCKET) { return; }
  21764. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  21765. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21766. char buf[4096];
  21767. received = ::recv(cli, buf, sizeof(buf), 0);
  21768. });
  21769. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  21770. // connect() has already shut the socket down by the time it returns false,
  21771. // so the peer sees EOF without waiting for the client to be destroyed.
  21772. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  21773. {{"X-Bad", "a\r\nInjected: 1"}});
  21774. EXPECT_FALSE(client.connect());
  21775. t.join();
  21776. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  21777. EXPECT_EQ(0, received);
  21778. }
  21779. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  21780. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  21781. // contains "upgrade" as a substring is a different token and must not
  21782. // start a WebSocket handshake.
  21783. auto make_request = [](const std::vector<std::string> &connection_values) {
  21784. Request req;
  21785. req.method = "GET";
  21786. req.headers.emplace("Upgrade", "websocket");
  21787. for (const auto &value : connection_values) {
  21788. req.headers.emplace("Connection", value);
  21789. }
  21790. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21791. req.headers.emplace("Sec-WebSocket-Version", "13");
  21792. return req;
  21793. };
  21794. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  21795. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  21796. EXPECT_TRUE(
  21797. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  21798. EXPECT_TRUE(
  21799. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  21800. EXPECT_TRUE(
  21801. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  21802. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  21803. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  21804. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  21805. EXPECT_FALSE(
  21806. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  21807. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  21808. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21809. }
  21810. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  21811. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  21812. // asks recipients to match each protocol-name case-insensitively, and RFC
  21813. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  21814. // client naming websocket alongside another protocol, or on a second field
  21815. // line, is offering websocket; a value that merely contains "websocket" as a
  21816. // substring is a different protocol name and is not.
  21817. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  21818. Request req;
  21819. req.method = "GET";
  21820. for (const auto &value : upgrade_values) {
  21821. req.headers.emplace("Upgrade", value);
  21822. }
  21823. req.headers.emplace("Connection", "Upgrade");
  21824. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21825. req.headers.emplace("Sec-WebSocket-Version", "13");
  21826. return req;
  21827. };
  21828. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  21829. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  21830. EXPECT_TRUE(
  21831. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  21832. EXPECT_TRUE(
  21833. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  21834. EXPECT_TRUE(
  21835. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  21836. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  21837. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  21838. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  21839. EXPECT_FALSE(
  21840. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  21841. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  21842. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21843. }
  21844. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  21845. Server svr;
  21846. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  21847. auto port = svr.bind_to_any_port("localhost");
  21848. std::thread t([&]() { svr.listen_after_bind(); });
  21849. auto se = detail::scope_exit([&] {
  21850. svr.stop();
  21851. t.join();
  21852. });
  21853. svr.wait_until_ready();
  21854. Headers headers = {{"Upgrade", "websocket"},
  21855. {"Connection", "notupgrade"},
  21856. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21857. {"Sec-WebSocket-Version", "13"}};
  21858. Client cli("localhost", port);
  21859. auto res = cli.Get("/ws", headers);
  21860. // The route exists only as a WebSocket route, so a request that fails the
  21861. // handshake check falls through to ordinary routing.
  21862. ASSERT_TRUE(res);
  21863. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  21864. }
  21865. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  21866. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  21867. // Connection value is the only thing left for the client to reject.
  21868. Server svr;
  21869. svr.Get("/ws", [](const Request &req, Response &res) {
  21870. res.status = StatusCode::SwitchingProtocol_101;
  21871. res.set_header("Upgrade", "websocket");
  21872. res.set_header("Connection", "notupgrade");
  21873. res.set_header("Sec-WebSocket-Accept",
  21874. detail::websocket_accept_key(
  21875. req.get_header_value("Sec-WebSocket-Key")));
  21876. });
  21877. auto port = svr.bind_to_any_port("localhost");
  21878. std::thread t([&]() { svr.listen_after_bind(); });
  21879. auto se = detail::scope_exit([&] {
  21880. svr.stop();
  21881. t.join();
  21882. });
  21883. svr.wait_until_ready();
  21884. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21885. auto res = client.connect();
  21886. EXPECT_FALSE(res);
  21887. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21888. EXPECT_FALSE(client.is_open());
  21889. }
  21890. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  21891. Server svr;
  21892. svr.Get("/ws", [](const Request &req, Response &res) {
  21893. res.status = StatusCode::SwitchingProtocol_101;
  21894. res.set_header("Upgrade", "websocket");
  21895. res.set_header("Connection", "Upgrade");
  21896. res.set_header("Sec-WebSocket-Accept",
  21897. detail::websocket_accept_key(
  21898. req.get_header_value("Sec-WebSocket-Key")));
  21899. res.set_header("Sec-WebSocket-Protocol", "admin");
  21900. });
  21901. auto port = svr.bind_to_any_port("localhost");
  21902. std::thread t([&]() { svr.listen_after_bind(); });
  21903. auto se = detail::scope_exit([&] {
  21904. svr.stop();
  21905. t.join();
  21906. });
  21907. svr.wait_until_ready();
  21908. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  21909. // Server selects a subprotocol the client never offered
  21910. {
  21911. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21912. ws::WebSocketClient client(url, headers);
  21913. auto res = client.connect();
  21914. EXPECT_FALSE(res);
  21915. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21916. EXPECT_FALSE(client.is_open());
  21917. EXPECT_TRUE(client.subprotocol().empty());
  21918. }
  21919. // Client offered none but the server named one anyway
  21920. {
  21921. ws::WebSocketClient client(url);
  21922. auto res = client.connect();
  21923. EXPECT_FALSE(res);
  21924. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21925. EXPECT_FALSE(client.is_open());
  21926. EXPECT_TRUE(client.subprotocol().empty());
  21927. }
  21928. }
  21929. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  21930. // The socket path doubles as the URL host, so it must not contain '/'.
  21931. const char *shard = getenv("GTEST_SHARD_INDEX");
  21932. const std::string sock_path =
  21933. shard ? std::string("httplib-ws-") + shard + ".sock"
  21934. : std::string("httplib-ws.sock");
  21935. std::remove(sock_path.c_str());
  21936. Server svr;
  21937. std::mutex mtx;
  21938. std::string received_host;
  21939. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21940. {
  21941. std::lock_guard<std::mutex> lock(mtx);
  21942. received_host = req.get_header_value("Host");
  21943. }
  21944. std::string msg;
  21945. while (ws.read(msg)) {
  21946. ws.send(msg);
  21947. }
  21948. });
  21949. svr.set_address_family(AF_UNIX);
  21950. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  21951. auto se = detail::scope_exit([&] {
  21952. svr.stop();
  21953. t.join();
  21954. std::remove(sock_path.c_str());
  21955. });
  21956. svr.wait_until_ready();
  21957. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  21958. client.set_address_family(AF_UNIX);
  21959. ASSERT_TRUE(client.connect());
  21960. ASSERT_TRUE(client.send("hello"));
  21961. std::string msg;
  21962. ASSERT_TRUE(client.read(msg));
  21963. client.close();
  21964. {
  21965. std::lock_guard<std::mutex> lock(mtx);
  21966. // There is no host:port for a Unix socket, so the same "localhost"
  21967. // placeholder the HTTP client uses is expected.
  21968. EXPECT_EQ("localhost", received_host);
  21969. }
  21970. }
  21971. // Two threads must never parse WebSocket frames from the same stream.
  21972. // close() used to read the peer's Close reply with its own frame read, so it
  21973. // raced a reader thread that was in the middle of a payload: the payload loop
  21974. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  21975. // so bytes taken by close() were replaced with bytes from further along the
  21976. // stream. The message kept its length and silently changed content.
  21977. //
  21978. // The raw peer below sends a frame header plus part of the payload, waits for
  21979. // the handler to call close(), and only then sends the rest. Whichever thread
  21980. // would win the race for those bytes, the message must arrive intact, because
  21981. // close() must not touch the stream while read() owns it.
  21982. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  21983. #ifndef _WIN32
  21984. signal(SIGPIPE, SIG_IGN);
  21985. #endif
  21986. const size_t payload_len = 120; // fits the 7-bit length field
  21987. const size_t prefix_len = 8;
  21988. const int attempts = 8;
  21989. std::string expected(payload_len, '\0');
  21990. for (size_t i = 0; i < payload_len; i++) {
  21991. expected[i] = static_cast<char>('a' + i % 26);
  21992. }
  21993. std::atomic<bool> peer_stalled{false};
  21994. std::atomic<bool> handler_done{false};
  21995. std::mutex received_mutex;
  21996. std::vector<std::string> received;
  21997. // Bound every wait, so a regression fails the test instead of hanging the
  21998. // suite.
  21999. auto wait_for = [](const std::atomic<bool> &flag) {
  22000. for (int i = 0; i < 500 && !flag; i++) {
  22001. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22002. }
  22003. };
  22004. Server svr;
  22005. svr.set_websocket_ping_interval(0);
  22006. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22007. std::thread reader([&]() {
  22008. std::string msg;
  22009. while (ws.read(msg)) {
  22010. std::lock_guard<std::mutex> guard(received_mutex);
  22011. received.push_back(msg);
  22012. }
  22013. });
  22014. // Wait until the peer stalls mid-payload, so the reader thread is parked
  22015. // inside read_websocket_frame() when close() runs.
  22016. wait_for(peer_stalled);
  22017. ws.close();
  22018. reader.join();
  22019. handler_done = true;
  22020. });
  22021. auto port = svr.bind_to_any_port("127.0.0.1");
  22022. std::thread t([&]() { svr.listen_after_bind(); });
  22023. auto se = detail::scope_exit([&] {
  22024. svr.stop();
  22025. t.join();
  22026. });
  22027. svr.wait_until_ready();
  22028. auto send_bytes = [](socket_t s, const std::string &data) {
  22029. #ifdef _WIN32
  22030. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  22031. #else
  22032. auto n = ::send(s, data.data(), data.size(), 0);
  22033. #endif
  22034. return n == static_cast<decltype(n)>(data.size());
  22035. };
  22036. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  22037. // Every length used here fits the 7-bit length field.
  22038. auto masked_header = [](uint8_t first_byte, size_t len) {
  22039. std::string h;
  22040. h += static_cast<char>(first_byte);
  22041. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  22042. h.append(4, '\0'); // mask key
  22043. return h;
  22044. };
  22045. for (int attempt = 0; attempt < attempts; attempt++) {
  22046. peer_stalled = false;
  22047. handler_done = false;
  22048. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22049. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  22050. auto se_sock = detail::scope_exit([&] {
  22051. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  22052. });
  22053. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22054. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  22055. sockaddr_in addr{};
  22056. addr.sin_family = AF_INET;
  22057. addr.sin_port = htons(static_cast<uint16_t>(port));
  22058. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22059. ASSERT_EQ(
  22060. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  22061. << "attempt " << attempt;
  22062. ASSERT_TRUE(send_bytes(sock,
  22063. "GET /ws HTTP/1.1\r\n"
  22064. "Host: 127.0.0.1\r\n"
  22065. "Upgrade: websocket\r\n"
  22066. "Connection: Upgrade\r\n"
  22067. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22068. "Sec-WebSocket-Version: 13\r\n"
  22069. "\r\n"))
  22070. << "attempt " << attempt;
  22071. std::string response;
  22072. while (response.find("\r\n\r\n") == std::string::npos) {
  22073. char buf[512];
  22074. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  22075. if (n <= 0) { break; }
  22076. response.append(buf, static_cast<size_t>(n));
  22077. }
  22078. ASSERT_NE(std::string::npos, response.find(" 101 "))
  22079. << "attempt " << attempt;
  22080. // Send the header of a Binary message but only the first prefix_len bytes
  22081. // of its payload, leaving the reader thread stalled inside the payload.
  22082. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  22083. expected.substr(0, prefix_len)))
  22084. << "attempt " << attempt;
  22085. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22086. peer_stalled = true;
  22087. // Let close() send its Close frame and park in its own read before the
  22088. // rest of the payload arrives, so both threads are waiting for it.
  22089. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22090. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  22091. close_frame += static_cast<char>(0x03); // status 1000
  22092. close_frame += static_cast<char>(0xE8);
  22093. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  22094. << "attempt " << attempt;
  22095. // Closing the peer releases the reader thread even on the buggy path,
  22096. // where it waits for bytes another thread already consumed.
  22097. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22098. detail::close_socket(sock);
  22099. sock = INVALID_SOCKET;
  22100. wait_for(handler_done);
  22101. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  22102. }
  22103. std::lock_guard<std::mutex> guard(received_mutex);
  22104. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  22105. << "a message in flight when close() ran was dropped";
  22106. for (size_t i = 0; i < received.size(); i++) {
  22107. EXPECT_EQ(expected, received[i]) << "message " << i;
  22108. }
  22109. }
  22110. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22111. class WebSocketSSLIntegrationTest : public ::testing::Test {
  22112. protected:
  22113. void SetUp() override {
  22114. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  22115. SERVER_PRIVATE_KEY_FILE);
  22116. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22117. std::string msg;
  22118. ws::ReadResult ret;
  22119. while ((ret = ws.read(msg))) {
  22120. if (ret == ws::Binary) {
  22121. ws.send(msg.data(), msg.size());
  22122. } else {
  22123. ws.send(msg);
  22124. }
  22125. }
  22126. });
  22127. port_ = server_->bind_to_any_port(HOST);
  22128. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22129. server_->wait_until_ready();
  22130. }
  22131. void TearDown() override {
  22132. server_->stop();
  22133. if (server_thread_.joinable()) { server_thread_.join(); }
  22134. }
  22135. std::unique_ptr<SSLServer> server_;
  22136. std::thread server_thread_;
  22137. int port_ = 0;
  22138. };
  22139. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  22140. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22141. "/ws-echo");
  22142. client.enable_server_certificate_verification(false);
  22143. ASSERT_TRUE(client.connect());
  22144. ASSERT_TRUE(client.is_open());
  22145. ASSERT_TRUE(client.send("Hello WSS"));
  22146. std::string msg;
  22147. EXPECT_EQ(ws::Text, client.read(msg));
  22148. EXPECT_EQ("Hello WSS", msg);
  22149. client.close();
  22150. }
  22151. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  22152. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  22153. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  22154. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  22155. // client (without calling close() first) is the only path that runs
  22156. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  22157. // bug exactly.
  22158. //
  22159. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  22160. // when linked against an instrumented libssl; run under Valgrind to catch it
  22161. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  22162. // suite (the freed session otherwise stalls on the close handshake) — this test
  22163. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  22164. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  22165. {
  22166. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22167. "/ws-echo");
  22168. client.enable_server_certificate_verification(false);
  22169. client.set_read_timeout(2, 0);
  22170. client.set_write_timeout(2, 0);
  22171. ASSERT_TRUE(client.connect());
  22172. ASSERT_TRUE(client.is_open());
  22173. ASSERT_TRUE(client.send("still open"));
  22174. // Intentionally do NOT call client.close(): leaving scope runs
  22175. // shutdown_and_close() with the WebSocket still open, which must send the
  22176. // close frame while the TLS session is still alive.
  22177. }
  22178. }
  22179. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  22180. // shutdown_and_close() at the start of connect(), reproducing the same
  22181. // use-after-free within the test body rather than at scope exit. The second
  22182. // connect must succeed and echo, proving the close handshake ran over a live
  22183. // session. See the note above about memory-tool requirements.
  22184. TEST_F(WebSocketSSLIntegrationTest,
  22185. ReconnectWhileOpenSendsCloseOverLiveSession) {
  22186. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22187. "/ws-echo");
  22188. client.enable_server_certificate_verification(false);
  22189. client.set_read_timeout(2, 0);
  22190. client.set_write_timeout(2, 0);
  22191. ASSERT_TRUE(client.connect());
  22192. ASSERT_TRUE(client.is_open());
  22193. ASSERT_TRUE(client.send("still open"));
  22194. // Reconnect without closing first: connect() calls shutdown_and_close() on
  22195. // the still-open connection, which must not touch a freed TLS session.
  22196. ASSERT_TRUE(client.connect());
  22197. ASSERT_TRUE(client.is_open());
  22198. ASSERT_TRUE(client.send("after reconnect"));
  22199. std::string msg;
  22200. EXPECT_EQ(ws::Text, client.read(msg));
  22201. EXPECT_EQ("after reconnect", msg);
  22202. client.close();
  22203. }
  22204. #endif
  22205. #ifdef CPPHTTPLIB_SSL_ENABLED
  22206. class WebSocketSSLCATest : public ::testing::Test {
  22207. protected:
  22208. void SetUp() override {
  22209. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  22210. SERVER_PRIVATE_KEY_FILE);
  22211. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22212. std::string msg;
  22213. while (ws.read(msg)) {
  22214. ws.send(msg);
  22215. }
  22216. });
  22217. port_ = server_->bind_to_any_port("127.0.0.1");
  22218. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22219. server_->wait_until_ready();
  22220. }
  22221. void TearDown() override {
  22222. server_->stop();
  22223. if (server_thread_.joinable()) { server_thread_.join(); }
  22224. }
  22225. std::string url() const {
  22226. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  22227. }
  22228. std::unique_ptr<SSLServer> server_;
  22229. std::thread server_thread_;
  22230. int port_ = 0;
  22231. };
  22232. // A custom CA loaded as PEM verifies the server with full certificate
  22233. // verification enabled
  22234. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  22235. ws::WebSocketClient client(url());
  22236. std::string cert;
  22237. read_file(SERVER_CERT2_FILE, cert);
  22238. client.load_ca_cert_store(cert.c_str(), cert.size());
  22239. ASSERT_TRUE(client.connect());
  22240. ASSERT_TRUE(client.send("hello"));
  22241. std::string msg;
  22242. EXPECT_EQ(ws::Text, client.read(msg));
  22243. EXPECT_EQ("hello", msg);
  22244. client.close();
  22245. }
  22246. // A custom CA that does not cover the server must fail verification (the
  22247. // custom CA is exclusive; system certs are not loaded alongside it)
  22248. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  22249. ws::WebSocketClient client(url());
  22250. std::string cert;
  22251. read_file(CLIENT_CA_CERT_FILE, cert);
  22252. client.load_ca_cert_store(cert.c_str(), cert.size());
  22253. auto res = client.connect();
  22254. ASSERT_FALSE(res);
  22255. EXPECT_EQ(Error::SSLServerVerification, res.error());
  22256. EXPECT_EQ(-1, res.status());
  22257. EXPECT_NE(0u, res.ssl_backend_error());
  22258. }
  22259. // The same CA as a file path rather than PEM in memory
  22260. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  22261. ws::WebSocketClient client(url());
  22262. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22263. ASSERT_TRUE(client.connect());
  22264. ASSERT_TRUE(client.send("hello"));
  22265. std::string msg;
  22266. EXPECT_EQ(ws::Text, client.read(msg));
  22267. EXPECT_EQ("hello", msg);
  22268. client.close();
  22269. }
  22270. // ...and a CA file that does not cover the server still fails, so it is the
  22271. // path above that decides the outcome
  22272. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  22273. ws::WebSocketClient client(url());
  22274. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22275. ASSERT_FALSE(client.connect());
  22276. }
  22277. // Regression test: reconnecting with a native custom CA store used to reuse
  22278. // a store handle the previous TLS context had already freed (use-after-free
  22279. // under the OpenSSL backend). The context now lives as long as the client.
  22280. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  22281. ws::WebSocketClient client(url());
  22282. std::string cert;
  22283. read_file(SERVER_CERT2_FILE, cert);
  22284. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  22285. ASSERT_TRUE(client.connect());
  22286. client.close();
  22287. ASSERT_TRUE(client.connect());
  22288. ASSERT_TRUE(client.send("again"));
  22289. std::string msg;
  22290. EXPECT_EQ(ws::Text, client.read(msg));
  22291. EXPECT_EQ("again", msg);
  22292. client.close();
  22293. }
  22294. // Regression test: a certificate with a trusted chain but no identity match
  22295. // for the server IP must be rejected. The Mbed TLS backend used to skip
  22296. // verification entirely for IP hosts, so this connection succeeded there.
  22297. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  22298. // chain verification while the identity check must still fail.
  22299. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  22300. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22301. ASSERT_TRUE(svr.is_valid());
  22302. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22303. std::string msg;
  22304. while (ws.read(msg)) {
  22305. ws.send(msg);
  22306. }
  22307. });
  22308. auto port = svr.bind_to_any_port("127.0.0.1");
  22309. auto t = std::thread([&]() { svr.listen_after_bind(); });
  22310. auto se = detail::scope_exit([&] {
  22311. svr.stop();
  22312. t.join();
  22313. });
  22314. svr.wait_until_ready();
  22315. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  22316. "/echo");
  22317. std::string cert;
  22318. read_file(SERVER_CERT_FILE, cert);
  22319. client.load_ca_cert_store(cert.c_str(), cert.size());
  22320. ASSERT_FALSE(client.connect());
  22321. }
  22322. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  22323. // SNI, so nothing binds the host name to the TLS session. These bind the
  22324. // server to "localhost" instead, the only shape that exercises the SNI and
  22325. // hostname-verification path with certificate verification left enabled.
  22326. class WebSocketSSLDnsHostTest : public ::testing::Test {
  22327. protected:
  22328. void Start(const char *cert_file) {
  22329. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  22330. SERVER_PRIVATE_KEY_FILE);
  22331. ASSERT_TRUE(server_->is_valid());
  22332. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22333. std::string msg;
  22334. while (ws.read(msg)) {
  22335. ws.send(msg);
  22336. }
  22337. });
  22338. port_ = server_->bind_to_any_port("localhost");
  22339. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22340. server_->wait_until_ready();
  22341. }
  22342. void TearDown() override {
  22343. if (server_) { server_->stop(); }
  22344. if (server_thread_.joinable()) { server_thread_.join(); }
  22345. }
  22346. std::string url() const {
  22347. return "wss://localhost:" + std::to_string(port_) + "/echo";
  22348. }
  22349. std::unique_ptr<SSLServer> server_;
  22350. std::thread server_thread_;
  22351. int port_ = 0;
  22352. };
  22353. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  22354. // out and the connection is usable
  22355. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  22356. Start(SERVER_CERT2_FILE);
  22357. ws::WebSocketClient client(url());
  22358. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22359. ASSERT_TRUE(client.connect());
  22360. ASSERT_TRUE(client.send("hello"));
  22361. std::string msg;
  22362. EXPECT_EQ(ws::Text, client.read(msg));
  22363. EXPECT_EQ("hello", msg);
  22364. client.close();
  22365. }
  22366. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  22367. // while the identity check must still reject "localhost"
  22368. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  22369. Start(SERVER_CERT_FILE);
  22370. ws::WebSocketClient client(url());
  22371. client.set_ca_cert_path(SERVER_CERT_FILE);
  22372. auto res = client.connect();
  22373. ASSERT_FALSE(res);
  22374. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  22375. EXPECT_EQ(-1, res.status());
  22376. }
  22377. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  22378. // disabled: the chain is still checked, only the identity check is skipped
  22379. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  22380. Start(SERVER_CERT_FILE);
  22381. ws::WebSocketClient client(url());
  22382. client.set_ca_cert_path(SERVER_CERT_FILE);
  22383. client.enable_server_hostname_verification(false);
  22384. ASSERT_TRUE(client.connect());
  22385. ASSERT_TRUE(client.send("hello"));
  22386. std::string msg;
  22387. EXPECT_EQ(ws::Text, client.read(msg));
  22388. EXPECT_EQ("hello", msg);
  22389. client.close();
  22390. }
  22391. // A CA that did not sign the server certificate fails the chain, even though
  22392. // the name would match
  22393. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  22394. Start(SERVER_CERT2_FILE);
  22395. ws::WebSocketClient client(url());
  22396. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22397. ASSERT_FALSE(client.connect());
  22398. }
  22399. // With verification disabled, neither the chain nor the name is checked
  22400. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  22401. Start(SERVER_CERT_FILE);
  22402. ws::WebSocketClient client(url());
  22403. client.enable_server_certificate_verification(false);
  22404. ASSERT_TRUE(client.connect());
  22405. ASSERT_TRUE(client.send("hello"));
  22406. std::string msg;
  22407. EXPECT_EQ(ws::Text, client.read(msg));
  22408. EXPECT_EQ("hello", msg);
  22409. client.close();
  22410. }
  22411. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  22412. protected:
  22413. void SetUp() override {
  22414. server_ = httplib::detail::make_unique<SSLServer>(
  22415. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22416. ASSERT_TRUE(server_->is_valid());
  22417. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22418. std::string msg;
  22419. while (ws.read(msg)) {
  22420. ws.send(msg);
  22421. }
  22422. });
  22423. port_ = server_->bind_to_any_port("localhost");
  22424. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22425. server_->wait_until_ready();
  22426. }
  22427. void TearDown() override {
  22428. server_->stop();
  22429. if (server_thread_.joinable()) { server_thread_.join(); }
  22430. }
  22431. std::string url() const {
  22432. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22433. }
  22434. void ConnectWithClientCert(const std::string &client_cert_file,
  22435. const std::string &client_private_key_file,
  22436. const char *private_key_password) {
  22437. std::string cert_pem, key_pem;
  22438. read_file(client_cert_file, cert_pem);
  22439. read_file(client_private_key_file, key_pem);
  22440. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  22441. key_pem.c_str(), key_pem.size(),
  22442. private_key_password};
  22443. ws::WebSocketClient client(url(), pem);
  22444. ASSERT_TRUE(client.is_valid());
  22445. client.enable_server_certificate_verification(false);
  22446. ASSERT_TRUE(client.connect());
  22447. ASSERT_TRUE(client.send("hello"));
  22448. std::string msg;
  22449. EXPECT_EQ(ws::Text, client.read(msg));
  22450. EXPECT_EQ("hello", msg);
  22451. client.close();
  22452. }
  22453. std::unique_ptr<SSLServer> server_;
  22454. std::thread server_thread_;
  22455. int port_ = 0;
  22456. };
  22457. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  22458. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  22459. }
  22460. // Control for the tests above: the fixture's server really does require a
  22461. // client certificate, so it is the PEM the constructor installed that decides
  22462. // the outcome.
  22463. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  22464. ws::WebSocketClient client(url());
  22465. ASSERT_TRUE(client.is_valid());
  22466. client.enable_server_certificate_verification(false);
  22467. EXPECT_FALSE(client.connect());
  22468. }
  22469. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  22470. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  22471. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  22472. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  22473. }
  22474. #endif
  22475. #if !defined(_WIN32)
  22476. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  22477. auto secret_dir = std::string("./symlink_test_secret");
  22478. auto served_dir = std::string("./symlink_test_served");
  22479. auto secret_file = secret_dir + "/secret.txt";
  22480. auto symlink_path = served_dir + "/escape";
  22481. // Setup: create directories and files
  22482. mkdir(secret_dir.c_str(), 0755);
  22483. mkdir(served_dir.c_str(), 0755);
  22484. {
  22485. std::ofstream ofs(secret_file);
  22486. ofs << "SECRET_DATA";
  22487. }
  22488. // Create symlink using absolute path so it resolves correctly
  22489. #ifdef PATH_MAX
  22490. char abs_secret[PATH_MAX];
  22491. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  22492. #else
  22493. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  22494. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  22495. ASSERT_NE(nullptr, abs_secret);
  22496. #endif
  22497. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  22498. auto se = detail::scope_exit([&] {
  22499. unlink(symlink_path.c_str());
  22500. unlink(secret_file.c_str());
  22501. rmdir(served_dir.c_str());
  22502. rmdir(secret_dir.c_str());
  22503. });
  22504. Server svr;
  22505. svr.set_mount_point("/", served_dir);
  22506. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  22507. auto se2 = detail::scope_exit([&] {
  22508. svr.stop();
  22509. listen_thread.join();
  22510. });
  22511. svr.wait_until_ready();
  22512. Client cli("localhost", PORT);
  22513. // Symlink pointing outside base dir should be blocked
  22514. auto res = cli.Get("/escape/secret.txt");
  22515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22516. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  22517. }
  22518. #endif
  22519. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  22520. // "GET /smuggled" request), reads the first response, and only then sends the
  22521. // embedded request as the body. Returns how many times /smuggled ran.
  22522. //
  22523. // The body is sent AFTER receiving the first response (as in the original
  22524. // PoC) so that the stream_line_reader cannot buffer it together with the
  22525. // headers of the first request.
  22526. static int count_smuggled_requests(const std::string &outer_head,
  22527. std::string &first_response) {
  22528. Server svr;
  22529. svr.set_mount_point("/", "./www");
  22530. std::atomic<int> smuggled_count(0);
  22531. svr.Get("/smuggled", [&](const Request &, Response &res) {
  22532. smuggled_count++;
  22533. res.set_content("oops", "text/plain");
  22534. });
  22535. svr.Post("/post", [&](const Request &req, Response &res) {
  22536. res.set_content(req.body, "text/plain");
  22537. });
  22538. auto port = svr.bind_to_any_port("localhost");
  22539. thread t = thread([&] { svr.listen_after_bind(); });
  22540. auto se = detail::scope_exit([&] {
  22541. svr.stop();
  22542. t.join();
  22543. });
  22544. svr.wait_until_ready();
  22545. auto error = Error::Success;
  22546. auto sock = detail::create_client_socket(
  22547. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  22548. /*connection_timeout_sec=*/2, 0,
  22549. /*read_timeout_sec=*/2, 0,
  22550. /*write_timeout_sec=*/2, 0, std::string(), error);
  22551. EXPECT_NE(INVALID_SOCKET, sock);
  22552. if (sock == INVALID_SOCKET) { return -1; }
  22553. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22554. // The "smuggled" request will be sent as the body of the outer request
  22555. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  22556. "Host: localhost\r\n"
  22557. "Connection: close\r\n"
  22558. "\r\n";
  22559. auto head = outer_head;
  22560. auto len = std::to_string(smuggled.size());
  22561. for (auto pos = head.find("{len}"); pos != std::string::npos;
  22562. pos = head.find("{len}", pos + len.size())) {
  22563. head.replace(pos, 5, len);
  22564. }
  22565. // Step 1: Send only the outer request headers (no body yet)
  22566. auto sent = send(sock, head.data(), head.size(), 0);
  22567. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  22568. // Step 2: Read the first response
  22569. char buf[4096];
  22570. for (;;) {
  22571. auto n = recv(sock, buf, sizeof(buf), 0);
  22572. if (n <= 0) break;
  22573. first_response.append(buf, static_cast<size_t>(n));
  22574. // Stop once we have a complete response (headers + body)
  22575. auto hdr_end = first_response.find("\r\n\r\n");
  22576. if (hdr_end != std::string::npos) {
  22577. // Check for Content-Length to know when the body is complete
  22578. auto cl_pos = first_response.find("Content-Length:");
  22579. if (cl_pos != std::string::npos) {
  22580. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  22581. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  22582. auto cl = std::stoul(
  22583. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  22584. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  22585. } else {
  22586. break; // No Content-Length, assume headers-only response
  22587. }
  22588. }
  22589. }
  22590. // Step 3: Now send the body, which looks like a new HTTP request. On a
  22591. // vulnerable server the keep-alive loop reads this as a second request. The
  22592. // server may already have closed the connection, so the result is ignored.
  22593. send(sock, smuggled.data(), smuggled.size(), 0);
  22594. // Half-close so that a server which drained the body sees EOF and closes,
  22595. // instead of the read below waiting for the read timeout.
  22596. #ifdef _WIN32
  22597. ::shutdown(sock, SD_SEND);
  22598. #else
  22599. ::shutdown(sock, SHUT_WR);
  22600. #endif
  22601. // Step 4: Read until the server closes the connection
  22602. for (;;) {
  22603. auto n = recv(sock, buf, sizeof(buf), 0);
  22604. if (n <= 0) break;
  22605. }
  22606. return smuggled_count.load();
  22607. }
  22608. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  22609. // A GET request with Content-Length to a static file handler must have its
  22610. // body drained before the keep-alive connection is reused. Otherwise the
  22611. // unread body bytes are interpreted as the next HTTP request.
  22612. std::string first_response;
  22613. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22614. "Host: localhost\r\n"
  22615. "Content-Length: {len}\r\n"
  22616. "\r\n",
  22617. first_response));
  22618. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  22619. }
  22620. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  22621. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  22622. // be answered with 400 and the connection closed. Treating it as "no body"
  22623. // leaves the body to be parsed as the next request.
  22624. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  22625. const char *targets[] = {
  22626. "GET /file", // handler that never reads the body
  22627. "GET /not-found", // no handler matches (404)
  22628. "POST /post", // handler that reads the body
  22629. };
  22630. for (auto target : targets) {
  22631. for (auto value : values) {
  22632. std::string first_response;
  22633. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  22634. " HTTP/1.1\r\n"
  22635. "Host: localhost\r\n"
  22636. "Content-Length: " +
  22637. value + "\r\n\r\n",
  22638. first_response))
  22639. << target << " with Content-Length: " << value;
  22640. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  22641. << target << " with Content-Length: " << value;
  22642. }
  22643. }
  22644. }
  22645. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  22646. // A 400 for an unparseable request line leaves the rest of the message
  22647. // unread, so the connection must be closed rather than reused.
  22648. std::string first_response;
  22649. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  22650. "Host: localhost\r\n"
  22651. "Content-Length: {len}\r\n"
  22652. "\r\n",
  22653. first_response));
  22654. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22655. }
  22656. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  22657. // Same as above for a header block that fails to parse.
  22658. std::string first_response;
  22659. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22660. "Host: localhost\r\n"
  22661. "Bad Header\r\n"
  22662. "Content-Length: {len}\r\n"
  22663. "\r\n",
  22664. first_response));
  22665. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22666. }
  22667. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  22668. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  22669. // server must not read another request on that connection, even when the
  22670. // request had no body to drain.
  22671. std::string first_response;
  22672. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  22673. "Host: localhost\r\n"
  22674. "\r\n",
  22675. first_response));
  22676. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  22677. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  22678. }
  22679. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  22680. // A content reader that stops early leaves the stream inside the body.
  22681. // Draining the whole Content-Length from there, or reading the body again,
  22682. // reads into the next request, and whatever follows is parsed as a request
  22683. // of its own.
  22684. Server svr;
  22685. std::atomic<int> smuggled_count(0);
  22686. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  22687. svr.Post("/upload", [](const Request &req, Response &res,
  22688. const ContentReader &content_reader) {
  22689. // Stop at the last chunk, so the whole body has been read however it
  22690. // arrives.
  22691. auto length = req.get_header_value_u64("Content-Length");
  22692. size_t total = 0;
  22693. auto consumed = content_reader([&](const char *, size_t n) {
  22694. total += n;
  22695. return total < length;
  22696. });
  22697. EXPECT_FALSE(consumed);
  22698. if (req.has_param("retry")) {
  22699. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  22700. }
  22701. // Replace the 400 the aborted read set, which would close the connection.
  22702. res.set_redirect("/done");
  22703. });
  22704. auto port = svr.bind_to_any_port(HOST);
  22705. thread t = thread([&] { svr.listen_after_bind(); });
  22706. auto se = detail::scope_exit([&] {
  22707. svr.stop();
  22708. t.join();
  22709. });
  22710. svr.wait_until_ready();
  22711. // A front end sees the second request as a POST whose body is the GET. The
  22712. // first body is as long as the POST's headers, so draining it again reads
  22713. // exactly those and leaves the GET to be parsed next.
  22714. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  22715. "Host: localhost\r\n"
  22716. "\r\n";
  22717. std::string second_head = "POST /post HTTP/1.1\r\n"
  22718. "Host: localhost\r\n"
  22719. "Content-Length: " +
  22720. std::to_string(inner.size()) +
  22721. "\r\n"
  22722. "\r\n";
  22723. for (auto target : {"/upload", "/upload?retry"}) {
  22724. smuggled_count = 0;
  22725. std::string request = "POST " + std::string(target) +
  22726. " HTTP/1.1\r\n"
  22727. "Host: localhost\r\n"
  22728. "Content-Length: " +
  22729. std::to_string(second_head.size()) +
  22730. "\r\n"
  22731. "\r\n" +
  22732. std::string(second_head.size(), 'A') + second_head +
  22733. inner;
  22734. std::string response;
  22735. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  22736. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  22737. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  22738. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  22739. EXPECT_EQ(0, smuggled_count.load()) << target;
  22740. }
  22741. }
  22742. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  22743. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  22744. // must be rejected with 400 Bad Request.
  22745. Server svr;
  22746. svr.Post("/test", [&](const Request &, Response &res) {
  22747. res.set_content("ok", "text/plain");
  22748. });
  22749. thread t = thread([&] { svr.listen(HOST, PORT); });
  22750. auto se = detail::scope_exit([&] {
  22751. svr.stop();
  22752. t.join();
  22753. ASSERT_FALSE(svr.is_running());
  22754. });
  22755. svr.wait_until_ready();
  22756. // Exact "chunked"
  22757. {
  22758. auto req = "POST /test HTTP/1.1\r\n"
  22759. "Host: localhost\r\n"
  22760. "Content-Length: 5\r\n"
  22761. "Transfer-Encoding: chunked\r\n"
  22762. "Connection: close\r\n"
  22763. "\r\n"
  22764. "hello";
  22765. std::string response;
  22766. ASSERT_TRUE(send_request(1, req, &response));
  22767. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22768. response.substr(0, response.find("\r\n")));
  22769. }
  22770. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  22771. {
  22772. auto req = "POST /test HTTP/1.1\r\n"
  22773. "Host: localhost\r\n"
  22774. "Content-Length: 5\r\n"
  22775. "Transfer-Encoding: gzip, chunked\r\n"
  22776. "Connection: close\r\n"
  22777. "\r\n"
  22778. "hello";
  22779. std::string response;
  22780. ASSERT_TRUE(send_request(1, req, &response));
  22781. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22782. response.substr(0, response.find("\r\n")));
  22783. }
  22784. }
  22785. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  22786. Server svr;
  22787. svr.Post("/test", [&](const Request &, Response &res) {
  22788. res.set_content("ok", "text/plain");
  22789. });
  22790. thread t = thread([&] { svr.listen(HOST, PORT); });
  22791. auto se = detail::scope_exit([&] {
  22792. svr.stop();
  22793. t.join();
  22794. ASSERT_FALSE(svr.is_running());
  22795. });
  22796. svr.wait_until_ready();
  22797. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  22798. // length cannot be determined, so the server must answer 400 and close
  22799. // rather than treat the request as bodyless and leave the body in the
  22800. // socket for the next request to pick up.
  22801. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  22802. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  22803. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  22804. std::string response;
  22805. ASSERT_TRUE(send_request(1, req, &response));
  22806. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22807. response.substr(0, response.find("\r\n")))
  22808. << transfer_encoding;
  22809. }
  22810. // RFC 9110 5.3: the codings may also be split across several
  22811. // Transfer-Encoding lines, which combine in the order they were received.
  22812. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  22813. // just like the single-line "chunked, gzip" above.
  22814. {
  22815. auto req = "POST /test HTTP/1.1\r\n"
  22816. "Host: localhost\r\n"
  22817. "Transfer-Encoding: chunked\r\n"
  22818. "Transfer-Encoding: gzip\r\n"
  22819. "\r\n"
  22820. "0\r\n\r\n";
  22821. std::string response;
  22822. ASSERT_TRUE(send_request(1, req, &response));
  22823. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22824. response.substr(0, response.find("\r\n")));
  22825. }
  22826. // A sequence ending in chunked stays valid.
  22827. auto req = "POST /test HTTP/1.1\r\n"
  22828. "Host: localhost\r\n"
  22829. "Transfer-Encoding: gzip, chunked\r\n"
  22830. "Connection: close\r\n"
  22831. "\r\n"
  22832. "0\r\n\r\n";
  22833. std::string response;
  22834. ASSERT_TRUE(send_request(1, req, &response));
  22835. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  22836. // ...including when it is spread over several lines.
  22837. auto split_req = "POST /test HTTP/1.1\r\n"
  22838. "Host: localhost\r\n"
  22839. "Transfer-Encoding: gzip\r\n"
  22840. "Transfer-Encoding: chunked\r\n"
  22841. "Connection: close\r\n"
  22842. "\r\n"
  22843. "0\r\n\r\n";
  22844. std::string split_response;
  22845. ASSERT_TRUE(send_request(1, split_req, &split_response));
  22846. EXPECT_EQ("HTTP/1.1 200 OK",
  22847. split_response.substr(0, split_response.find("\r\n")));
  22848. }
  22849. // Regression for issue #2450: a DELETE without Content-Length on a
  22850. // keep-alive connection must not let the post-response drain consume the
  22851. // next request's bytes.
  22852. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  22853. Server svr;
  22854. std::atomic<int> delete_count(0);
  22855. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  22856. delete_count++;
  22857. res.status = StatusCode::NoContent_204;
  22858. });
  22859. auto port = svr.bind_to_any_port(HOST);
  22860. thread t = thread([&] { svr.listen_after_bind(); });
  22861. auto se = detail::scope_exit([&] {
  22862. svr.stop();
  22863. t.join();
  22864. });
  22865. svr.wait_until_ready();
  22866. auto error = Error::Success;
  22867. auto sock = detail::create_client_socket(
  22868. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22869. /*connection_timeout_sec=*/2, 0,
  22870. /*read_timeout_sec=*/2, 0,
  22871. /*write_timeout_sec=*/2, 0, std::string(), error);
  22872. ASSERT_NE(INVALID_SOCKET, sock);
  22873. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22874. auto send_request_and_read_response = [&](const std::string &req,
  22875. std::string &out) -> bool {
  22876. auto sent = send(sock, req.data(), req.size(), 0);
  22877. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  22878. char buf[4096];
  22879. for (;;) {
  22880. auto n = recv(sock, buf, sizeof(buf), 0);
  22881. if (n <= 0) { return !out.empty(); }
  22882. out.append(buf, static_cast<size_t>(n));
  22883. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  22884. }
  22885. };
  22886. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  22887. "Host: localhost\r\n"
  22888. "\r\n";
  22889. std::string resp1;
  22890. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  22891. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  22892. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  22893. "Host: localhost\r\n"
  22894. "Connection: close\r\n"
  22895. "\r\n";
  22896. std::string resp2;
  22897. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  22898. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  22899. EXPECT_EQ(2, delete_count.load());
  22900. }
  22901. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  22902. Server svr;
  22903. svr.Post("/ingest", [&](const Request &, Response &res,
  22904. const ContentReader &content_reader) {
  22905. auto consumed = content_reader([](const char *, size_t) { return false; });
  22906. EXPECT_FALSE(consumed);
  22907. res.status = StatusCode::Conflict_409;
  22908. res.set_header("Connection", "close");
  22909. });
  22910. auto port = svr.bind_to_any_port(HOST);
  22911. thread t = thread([&] { svr.listen_after_bind(); });
  22912. auto se = detail::scope_exit([&] {
  22913. svr.stop();
  22914. t.join();
  22915. });
  22916. svr.wait_until_ready();
  22917. auto error = Error::Success;
  22918. auto sock = detail::create_client_socket(
  22919. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22920. /*connection_timeout_sec=*/2, 0,
  22921. /*read_timeout_sec=*/1, 0,
  22922. /*write_timeout_sec=*/2, 0, std::string(), error);
  22923. ASSERT_NE(INVALID_SOCKET, sock);
  22924. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22925. std::string request = "POST /ingest HTTP/1.1\r\n"
  22926. "Host: localhost\r\n"
  22927. "Transfer-Encoding: chunked\r\n"
  22928. "\r\n"
  22929. "4\r\n"
  22930. "data\r\n";
  22931. auto sent = send(sock, request.data(), request.size(), 0);
  22932. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  22933. std::string response;
  22934. ssize_t received = 0;
  22935. do {
  22936. char buf[4096];
  22937. received = recv(sock, buf, sizeof(buf), 0);
  22938. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  22939. } while (received > 0);
  22940. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  22941. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  22942. EXPECT_EQ(0, received);
  22943. }
  22944. namespace no_proxy_test {
  22945. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  22946. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  22947. // calling listen().
  22948. class ScopedServer {
  22949. public:
  22950. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  22951. ~ScopedServer() {
  22952. svr_.stop();
  22953. if (th_.joinable()) { th_.join(); }
  22954. }
  22955. Server &svr() { return svr_; }
  22956. int port() const { return port_; }
  22957. void listen() {
  22958. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22959. svr_.wait_until_ready();
  22960. }
  22961. private:
  22962. Server svr_;
  22963. std::thread th_;
  22964. int port_ = 0;
  22965. };
  22966. class ProxyAndTargetServers {
  22967. public:
  22968. ProxyAndTargetServers() {
  22969. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  22970. proxy_hits_++;
  22971. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22972. res.set_content("via-proxy", "text/plain");
  22973. });
  22974. target_.Get(".*", [this](const Request &req, Response &res) {
  22975. target_hits_++;
  22976. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22977. res.set_content("direct", "text/plain");
  22978. });
  22979. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  22980. target_port_ = target_.bind_to_any_port("127.0.0.1");
  22981. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  22982. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  22983. proxy_mock_.wait_until_ready();
  22984. target_.wait_until_ready();
  22985. }
  22986. ~ProxyAndTargetServers() {
  22987. proxy_mock_.stop();
  22988. target_.stop();
  22989. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  22990. if (target_thread_.joinable()) { target_thread_.join(); }
  22991. }
  22992. Server &proxy_mock() { return proxy_mock_; }
  22993. Server &target() { return target_; }
  22994. int proxy_port() const { return proxy_port_; }
  22995. int target_port() const { return target_port_; }
  22996. int proxy_hits() const { return proxy_hits_.load(); }
  22997. int target_hits() const { return target_hits_.load(); }
  22998. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  22999. void reset_counters() {
  23000. proxy_hits_ = 0;
  23001. target_hits_ = 0;
  23002. last_had_proxy_authz_ = false;
  23003. }
  23004. private:
  23005. Server proxy_mock_;
  23006. Server target_;
  23007. std::thread proxy_thread_;
  23008. std::thread target_thread_;
  23009. int proxy_port_ = 0;
  23010. int target_port_ = 0;
  23011. std::atomic<int> proxy_hits_{0};
  23012. std::atomic<int> target_hits_{0};
  23013. std::atomic<bool> last_had_proxy_authz_{false};
  23014. };
  23015. inline std::unique_ptr<Client> make_client(const std::string &host,
  23016. ProxyAndTargetServers &s) {
  23017. auto cli = detail::make_unique<Client>(host, s.target_port());
  23018. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  23019. cli->set_proxy("127.0.0.1", s.proxy_port());
  23020. return cli;
  23021. }
  23022. } // namespace no_proxy_test
  23023. using no_proxy_test::make_client;
  23024. using no_proxy_test::ProxyAndTargetServers;
  23025. TEST(NoProxyTest, ExactHostnameBypasses) {
  23026. ProxyAndTargetServers s;
  23027. auto cli = make_client("example.com", s);
  23028. cli->set_no_proxy({"example.com"});
  23029. auto res = cli->Get("/");
  23030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23031. EXPECT_EQ(0, s.proxy_hits());
  23032. EXPECT_EQ(1, s.target_hits());
  23033. }
  23034. TEST(NoProxyTest, SubdomainBypasses) {
  23035. ProxyAndTargetServers s;
  23036. auto cli = make_client("foo.example.com", s);
  23037. cli->set_no_proxy({"example.com"});
  23038. auto res = cli->Get("/");
  23039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23040. EXPECT_EQ(0, s.proxy_hits());
  23041. EXPECT_EQ(1, s.target_hits());
  23042. }
  23043. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  23044. // Regression guard: "evilexample.com" must not be considered a subdomain
  23045. // of "example.com". Without the dot-boundary rule, a naive endsWith
  23046. // check would let traffic bypass the proxy and leak credentials direct
  23047. // to the attacker host.
  23048. ProxyAndTargetServers s;
  23049. auto cli = make_client("evilexample.com", s);
  23050. cli->set_no_proxy({"example.com"});
  23051. auto res = cli->Get("/");
  23052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23053. EXPECT_GE(s.proxy_hits(), 1);
  23054. EXPECT_EQ(0, s.target_hits());
  23055. }
  23056. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  23057. ProxyAndTargetServers s;
  23058. auto cli = make_client("example.com.evil.com", s);
  23059. cli->set_no_proxy({"example.com"});
  23060. auto res = cli->Get("/");
  23061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23062. EXPECT_GE(s.proxy_hits(), 1);
  23063. EXPECT_EQ(0, s.target_hits());
  23064. }
  23065. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  23066. ProxyAndTargetServers s;
  23067. auto cli = make_client("example.com", s);
  23068. cli->set_no_proxy({".example.com"});
  23069. auto res = cli->Get("/");
  23070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23071. EXPECT_EQ(0, s.proxy_hits());
  23072. EXPECT_EQ(1, s.target_hits());
  23073. }
  23074. TEST(NoProxyTest, CaseInsensitiveHostname) {
  23075. ProxyAndTargetServers s;
  23076. auto cli = make_client("Example.COM", s);
  23077. cli->set_no_proxy({"EXAMPLE.com"});
  23078. auto res = cli->Get("/");
  23079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23080. EXPECT_EQ(0, s.proxy_hits());
  23081. EXPECT_EQ(1, s.target_hits());
  23082. }
  23083. TEST(NoProxyTest, TrailingDotIsNormalized) {
  23084. ProxyAndTargetServers s;
  23085. auto cli = make_client("example.com.", s);
  23086. cli->set_no_proxy({"example.com"});
  23087. auto res = cli->Get("/");
  23088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23089. EXPECT_EQ(0, s.proxy_hits());
  23090. EXPECT_EQ(1, s.target_hits());
  23091. }
  23092. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  23093. // Trailing dots must be normalized on BOTH sides — host and entry.
  23094. // An implementation that only strips the host-side trailing dot would
  23095. // fail to match host "example.com" against entry "example.com." because
  23096. // a literal substring search would compare 11 chars against 12.
  23097. ProxyAndTargetServers s;
  23098. auto cli = make_client("example.com", s);
  23099. cli->set_no_proxy({"example.com."});
  23100. auto res = cli->Get("/");
  23101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23102. EXPECT_EQ(0, s.proxy_hits());
  23103. EXPECT_EQ(1, s.target_hits());
  23104. }
  23105. TEST(NoProxyTest, WildcardBypassesEverything) {
  23106. ProxyAndTargetServers s;
  23107. auto cli = make_client("anything.invalid.test", s);
  23108. cli->set_no_proxy({"*"});
  23109. auto res = cli->Get("/");
  23110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23111. EXPECT_EQ(0, s.proxy_hits());
  23112. EXPECT_EQ(1, s.target_hits());
  23113. }
  23114. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  23115. ProxyAndTargetServers s;
  23116. Client cli("127.0.0.1", s.target_port());
  23117. cli.set_proxy("127.0.0.1", s.proxy_port());
  23118. cli.set_no_proxy({"127.0.0.1"});
  23119. auto res = cli.Get("/");
  23120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23121. EXPECT_EQ(0, s.proxy_hits());
  23122. EXPECT_EQ(1, s.target_hits());
  23123. }
  23124. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  23125. ProxyAndTargetServers s;
  23126. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  23127. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  23128. cli.set_proxy("127.0.0.1", s.proxy_port());
  23129. cli.set_no_proxy({"::1"});
  23130. auto res = cli.Get("/");
  23131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23132. EXPECT_EQ(0, s.proxy_hits());
  23133. EXPECT_EQ(1, s.target_hits());
  23134. }
  23135. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  23136. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  23137. // must still be recognized as IPv6 for CIDR matching. Implementations
  23138. // that detect IPv6 only when the host begins with '[' would parse the
  23139. // host as a hostname and miss the match.
  23140. ProxyAndTargetServers s;
  23141. Client cli("fe80::1", s.target_port());
  23142. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23143. cli.set_proxy("127.0.0.1", s.proxy_port());
  23144. cli.set_no_proxy({"fe80::/10"});
  23145. auto res = cli.Get("/");
  23146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23147. EXPECT_EQ(0, s.proxy_hits());
  23148. EXPECT_EQ(1, s.target_hits());
  23149. }
  23150. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  23151. ProxyAndTargetServers s;
  23152. Client cli("::1", s.target_port());
  23153. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  23154. cli.set_proxy("127.0.0.1", s.proxy_port());
  23155. cli.set_no_proxy({"[::1]"});
  23156. auto res = cli.Get("/");
  23157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23158. EXPECT_EQ(0, s.proxy_hits());
  23159. EXPECT_EQ(1, s.target_hits());
  23160. }
  23161. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  23162. ProxyAndTargetServers s;
  23163. Client cli("fe80::1", s.target_port());
  23164. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23165. cli.set_proxy("127.0.0.1", s.proxy_port());
  23166. cli.set_no_proxy({"[fe80::]/10"});
  23167. auto res = cli.Get("/");
  23168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23169. EXPECT_EQ(0, s.proxy_hits());
  23170. EXPECT_EQ(1, s.target_hits());
  23171. }
  23172. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  23173. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  23174. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  23175. // tricks via address-family conversion.
  23176. ProxyAndTargetServers s;
  23177. Client cli("::ffff:127.0.0.1", s.target_port());
  23178. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  23179. cli.set_proxy("127.0.0.1", s.proxy_port());
  23180. cli.set_no_proxy({"127.0.0.1"});
  23181. auto res = cli.Get("/");
  23182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23183. EXPECT_GE(s.proxy_hits(), 1);
  23184. EXPECT_EQ(0, s.target_hits());
  23185. }
  23186. TEST(NoProxyTest, IPv4CidrMatch) {
  23187. ProxyAndTargetServers s;
  23188. Client cli("127.0.0.1", s.target_port());
  23189. cli.set_proxy("127.0.0.1", s.proxy_port());
  23190. cli.set_no_proxy({"127.0.0.0/8"});
  23191. auto res = cli.Get("/");
  23192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23193. EXPECT_EQ(0, s.proxy_hits());
  23194. EXPECT_EQ(1, s.target_hits());
  23195. }
  23196. TEST(NoProxyTest, IPv4CidrNonMatch) {
  23197. ProxyAndTargetServers s;
  23198. Client cli("127.0.0.1", s.target_port());
  23199. cli.set_proxy("127.0.0.1", s.proxy_port());
  23200. cli.set_no_proxy({"10.0.0.0/8"});
  23201. auto res = cli.Get("/");
  23202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23203. EXPECT_GE(s.proxy_hits(), 1);
  23204. EXPECT_EQ(0, s.target_hits());
  23205. }
  23206. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  23207. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  23208. // IPv4 target matches.
  23209. ProxyAndTargetServers s;
  23210. Client cli("127.0.0.1", s.target_port());
  23211. cli.set_proxy("127.0.0.1", s.proxy_port());
  23212. cli.set_no_proxy({"0.0.0.0/0"});
  23213. auto res = cli.Get("/");
  23214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23215. EXPECT_EQ(0, s.proxy_hits());
  23216. EXPECT_EQ(1, s.target_hits());
  23217. }
  23218. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  23219. ProxyAndTargetServers s;
  23220. Client cli("127.0.0.1", s.target_port());
  23221. cli.set_proxy("127.0.0.1", s.proxy_port());
  23222. cli.set_no_proxy({"127.0.0.1"});
  23223. auto res = cli.Get("/");
  23224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23225. EXPECT_EQ(0, s.proxy_hits());
  23226. EXPECT_EQ(1, s.target_hits());
  23227. }
  23228. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  23229. ProxyAndTargetServers s;
  23230. Client cli("127.0.0.1", s.target_port());
  23231. cli.set_proxy("127.0.0.1", s.proxy_port());
  23232. cli.set_no_proxy({"127.0.0.0/33"});
  23233. auto res = cli.Get("/");
  23234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23235. EXPECT_GE(s.proxy_hits(), 1);
  23236. EXPECT_EQ(0, s.target_hits());
  23237. }
  23238. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  23239. // Empty prefix after the slash must be rejected, not silently treated as /32.
  23240. ProxyAndTargetServers s;
  23241. Client cli("127.0.0.1", s.target_port());
  23242. cli.set_proxy("127.0.0.1", s.proxy_port());
  23243. cli.set_no_proxy({"127.0.0.1/"});
  23244. auto res = cli.Get("/");
  23245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23246. EXPECT_GE(s.proxy_hits(), 1);
  23247. EXPECT_EQ(0, s.target_hits());
  23248. }
  23249. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  23250. ProxyAndTargetServers s;
  23251. auto cli = make_client("internal.corp", s);
  23252. cli->set_proxy_basic_auth("u", "p");
  23253. cli->set_no_proxy({"internal.corp"});
  23254. auto res = cli->Get("/");
  23255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23256. EXPECT_EQ(1, s.target_hits());
  23257. EXPECT_EQ(0, s.proxy_hits());
  23258. EXPECT_FALSE(s.last_had_proxy_authz())
  23259. << "Proxy-Authorization must not be sent direct to the target";
  23260. }
  23261. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  23262. ProxyAndTargetServers s;
  23263. auto cli = make_client("public.example", s);
  23264. cli->set_proxy_basic_auth("u", "p");
  23265. cli->set_no_proxy({"internal.corp"}); // does not match
  23266. auto res = cli->Get("/");
  23267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23268. EXPECT_GE(s.proxy_hits(), 1);
  23269. EXPECT_TRUE(s.last_had_proxy_authz());
  23270. }
  23271. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  23272. std::atomic<int> hits{0};
  23273. std::atomic<int> hits_with_authz{0};
  23274. no_proxy_test::ScopedServer proxy_mock;
  23275. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23276. hits++;
  23277. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  23278. if (req.target.find("/redir") != std::string::npos) {
  23279. res.set_redirect("http://other.example/landed");
  23280. } else {
  23281. res.set_content("via-proxy", "text/plain");
  23282. }
  23283. });
  23284. proxy_mock.listen();
  23285. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  23286. hits = 0;
  23287. hits_with_authz = 0;
  23288. Client cli("public.example", 80);
  23289. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23290. cli.set_proxy_basic_auth(c.first, c.second);
  23291. cli.set_follow_location(true);
  23292. // The redirect to another host goes through the proxy as well
  23293. auto res = cli.Get("/redir");
  23294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23295. EXPECT_EQ(2, hits.load());
  23296. EXPECT_EQ(2, hits_with_authz.load());
  23297. }
  23298. }
  23299. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  23300. ProxyAndTargetServers s;
  23301. auto cli = make_client("anything.test", s);
  23302. auto res = cli->Get("/");
  23303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23304. EXPECT_GE(s.proxy_hits(), 1);
  23305. EXPECT_EQ(0, s.target_hits());
  23306. }
  23307. TEST(NoProxyTest, PortSpecificEntryRejected) {
  23308. ProxyAndTargetServers s;
  23309. auto cli = make_client("example.com", s);
  23310. cli->set_no_proxy({"example.com:8080"});
  23311. auto res = cli->Get("/");
  23312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23313. EXPECT_GE(s.proxy_hits(), 1);
  23314. EXPECT_EQ(0, s.target_hits());
  23315. }
  23316. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  23317. ProxyAndTargetServers s;
  23318. auto cli = make_client("anything.test", s);
  23319. cli->set_no_proxy({"", " ", "\t"});
  23320. auto res = cli->Get("/");
  23321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23322. EXPECT_GE(s.proxy_hits(), 1);
  23323. EXPECT_EQ(0, s.target_hits());
  23324. }
  23325. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  23326. // An entry with leading/trailing whitespace must still match — env-style
  23327. // values are commonly pasted with stray spaces and an implementation
  23328. // that feeds the raw token directly to inet_pton would fail to match
  23329. // valid CIDRs because of the spaces.
  23330. ProxyAndTargetServers s;
  23331. Client cli("127.0.0.1", s.target_port());
  23332. cli.set_proxy("127.0.0.1", s.proxy_port());
  23333. cli.set_no_proxy({" 127.0.0.0/8 "});
  23334. auto res = cli.Get("/");
  23335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23336. EXPECT_EQ(0, s.proxy_hits());
  23337. EXPECT_EQ(1, s.target_hits());
  23338. }
  23339. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  23340. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  23341. // go direct and must NOT carry Proxy-Authorization.
  23342. std::atomic<int> proxy_hits{0};
  23343. std::atomic<int> target_hits{0};
  23344. std::atomic<bool> target_saw_authz{false};
  23345. no_proxy_test::ScopedServer proxy_mock, target;
  23346. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23347. proxy_hits++;
  23348. res.status = 302;
  23349. res.set_header("Location", "http://127.0.0.1:" +
  23350. std::to_string(target.port()) + "/landed");
  23351. });
  23352. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23353. target_hits++;
  23354. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  23355. res.set_content("direct", "text/plain");
  23356. });
  23357. proxy_mock.listen();
  23358. target.listen();
  23359. Client cli("public.example", target.port());
  23360. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23361. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23362. cli.set_proxy_basic_auth("u", "p");
  23363. cli.set_no_proxy({"127.0.0.1"});
  23364. cli.set_follow_location(true);
  23365. auto res = cli.Get("/redir");
  23366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23367. EXPECT_GE(proxy_hits.load(), 1);
  23368. EXPECT_GE(target_hits.load(), 1);
  23369. EXPECT_FALSE(target_saw_authz.load());
  23370. }
  23371. #ifdef CPPHTTPLIB_SSL_ENABLED
  23372. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  23373. // Direct origin replying 407 must not trigger the digest retry; otherwise
  23374. // proxy creds would be sent to the (possibly hostile) origin.
  23375. std::atomic<int> target_hits{0};
  23376. std::atomic<bool> target_saw_proxy_authz{false};
  23377. no_proxy_test::ScopedServer target;
  23378. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23379. target_hits++;
  23380. if (req.has_header("Proxy-Authorization")) {
  23381. target_saw_proxy_authz = true;
  23382. }
  23383. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23384. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  23385. "nonce=\"abc\", algorithm=MD5");
  23386. });
  23387. target.listen();
  23388. // The proxy address is set to the target's port: the bypass MUST kick in;
  23389. // if it doesn't, the test still routes "via proxy" to the same server and
  23390. // the Proxy-Authorization assertion below catches the leak.
  23391. Client cli("evil.example", target.port());
  23392. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  23393. cli.set_proxy("127.0.0.1", target.port());
  23394. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23395. cli.set_no_proxy({"evil.example"});
  23396. auto res = cli.Get("/x");
  23397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23398. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23399. EXPECT_EQ(1, target_hits.load());
  23400. EXPECT_FALSE(target_saw_proxy_authz.load());
  23401. }
  23402. #endif
  23403. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  23404. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  23405. std::atomic<int> proxy_hits{0};
  23406. std::atomic<int> bypass_hits{0};
  23407. std::atomic<bool> proxy_saw_c_url{false};
  23408. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  23409. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23410. proxy_hits++;
  23411. if (req.path.find("/start") != std::string::npos) {
  23412. res.status = 302;
  23413. res.set_header("Location", "http://127.0.0.1:" +
  23414. std::to_string(bypass_server.port()) +
  23415. "/middle");
  23416. return;
  23417. }
  23418. if (req.path.find("/end") != std::string::npos) {
  23419. proxy_saw_c_url = true;
  23420. res.set_content("c-via-proxy", "text/plain");
  23421. return;
  23422. }
  23423. res.set_content("unexpected", "text/plain");
  23424. });
  23425. // public.example's "advertised" port is arbitrary (the request never lands
  23426. // there — it goes through the proxy), but use a dynamic value to stay
  23427. // friendly with sharded parallel runs.
  23428. int public_port = bypass_server.port();
  23429. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  23430. bypass_hits++;
  23431. res.status = 302;
  23432. res.set_header("Location", "http://public.example:" +
  23433. std::to_string(public_port) + "/end");
  23434. });
  23435. proxy_mock.listen();
  23436. bypass_server.listen();
  23437. Client cli("public.example", public_port);
  23438. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23439. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23440. cli.set_no_proxy({"127.0.0.1"});
  23441. cli.set_follow_location(true);
  23442. auto res = cli.Get("/start");
  23443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23444. EXPECT_EQ(StatusCode::OK_200, res->status);
  23445. EXPECT_EQ("c-via-proxy", res->body);
  23446. EXPECT_GE(proxy_hits.load(), 2);
  23447. EXPECT_GE(bypass_hits.load(), 1);
  23448. EXPECT_TRUE(proxy_saw_c_url.load());
  23449. }
  23450. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  23451. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  23452. // request reconnects to the correct endpoint.
  23453. std::atomic<int> proxy_hits{0};
  23454. std::atomic<int> target_hits{0};
  23455. no_proxy_test::ScopedServer proxy_mock, target;
  23456. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23457. proxy_hits++;
  23458. res.set_content("via-proxy", "text/plain");
  23459. });
  23460. target.svr().Get(".*", [&](const Request &, Response &res) {
  23461. target_hits++;
  23462. res.set_content("direct", "text/plain");
  23463. });
  23464. proxy_mock.listen();
  23465. target.listen();
  23466. Client cli("public.example", target.port());
  23467. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23468. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23469. cli.set_keep_alive(true);
  23470. auto res1 = cli.Get("/a");
  23471. ASSERT_TRUE(res1);
  23472. EXPECT_EQ("via-proxy", res1->body);
  23473. EXPECT_EQ(1, proxy_hits.load());
  23474. EXPECT_EQ(0, target_hits.load());
  23475. cli.set_no_proxy({"public.example"});
  23476. auto res2 = cli.Get("/b");
  23477. ASSERT_TRUE(res2);
  23478. EXPECT_EQ("direct", res2->body);
  23479. EXPECT_EQ(1, proxy_hits.load());
  23480. EXPECT_EQ(1, target_hits.load());
  23481. }
  23482. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  23483. namespace proxy_tunnel_test {
  23484. // SSLServer counterpart to no_proxy_test::ScopedServer.
  23485. class ScopedSSLServer {
  23486. public:
  23487. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  23488. port_ = svr_.bind_to_any_port("127.0.0.1");
  23489. }
  23490. ~ScopedSSLServer() {
  23491. svr_.stop();
  23492. if (th_.joinable()) { th_.join(); }
  23493. }
  23494. SSLServer &svr() { return svr_; }
  23495. int port() const { return port_; }
  23496. void listen() {
  23497. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23498. svr_.wait_until_ready();
  23499. }
  23500. private:
  23501. SSLServer svr_;
  23502. std::thread th_;
  23503. int port_ = 0;
  23504. };
  23505. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  23506. class ScopedConnectProxy {
  23507. public:
  23508. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  23509. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  23510. if (listen_fd_ < 0) { return; }
  23511. int yes = 1;
  23512. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  23513. sockaddr_in a{};
  23514. a.sin_family = AF_INET;
  23515. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23516. a.sin_port = 0;
  23517. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  23518. return;
  23519. }
  23520. socklen_t alen = sizeof(a);
  23521. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  23522. 0) {
  23523. return;
  23524. }
  23525. port_ = ntohs(a.sin_port);
  23526. if (::listen(listen_fd_, 1) != 0) { return; }
  23527. th_ = std::thread([this] { run(); });
  23528. }
  23529. ~ScopedConnectProxy() {
  23530. stop_ = true;
  23531. if (listen_fd_ >= 0) {
  23532. ::shutdown(listen_fd_, SHUT_RDWR);
  23533. ::close(listen_fd_);
  23534. }
  23535. if (th_.joinable()) { th_.join(); }
  23536. }
  23537. int port() const { return port_; }
  23538. int connect_hits() const { return connect_hits_.load(); }
  23539. // Head of the last CONNECT request, as the proxy saw it on the wire.
  23540. std::string connect_request() const {
  23541. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23542. return connect_request_;
  23543. }
  23544. private:
  23545. void run() {
  23546. while (!stop_.load()) {
  23547. fd_set rfds;
  23548. FD_ZERO(&rfds);
  23549. FD_SET(listen_fd_, &rfds);
  23550. timeval tv{0, 100 * 1000};
  23551. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  23552. if (sel <= 0) { continue; }
  23553. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  23554. if (client_fd < 0) { continue; }
  23555. std::string req;
  23556. char buf[2048];
  23557. while (req.find("\r\n\r\n") == std::string::npos) {
  23558. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  23559. if (n <= 0) { break; }
  23560. req.append(buf, static_cast<size_t>(n));
  23561. }
  23562. if (req.compare(0, 7, "CONNECT") != 0) {
  23563. ::close(client_fd);
  23564. continue;
  23565. }
  23566. connect_hits_++;
  23567. {
  23568. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23569. connect_request_ = req;
  23570. }
  23571. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  23572. ::send(client_fd, ok, std::strlen(ok), 0);
  23573. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  23574. sockaddr_in o{};
  23575. o.sin_family = AF_INET;
  23576. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23577. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  23578. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  23579. 0) {
  23580. ::close(client_fd);
  23581. ::close(origin_fd);
  23582. continue;
  23583. }
  23584. auto forward = [](int from, int to) {
  23585. char b[8192];
  23586. for (;;) {
  23587. ssize_t n = ::recv(from, b, sizeof(b), 0);
  23588. if (n <= 0) { break; }
  23589. ssize_t off = 0;
  23590. while (off < n) {
  23591. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  23592. if (s <= 0) {
  23593. off = n;
  23594. break;
  23595. }
  23596. off += s;
  23597. }
  23598. }
  23599. ::shutdown(to, SHUT_WR);
  23600. };
  23601. std::thread t1([&] { forward(client_fd, origin_fd); });
  23602. std::thread t2([&] { forward(origin_fd, client_fd); });
  23603. t1.join();
  23604. t2.join();
  23605. ::close(client_fd);
  23606. ::close(origin_fd);
  23607. }
  23608. }
  23609. int forward_port_ = -1;
  23610. int listen_fd_ = -1;
  23611. int port_ = 0;
  23612. std::thread th_;
  23613. std::atomic<bool> stop_{false};
  23614. std::atomic<int> connect_hits_{0};
  23615. mutable std::mutex connect_request_mutex_;
  23616. std::string connect_request_;
  23617. };
  23618. // Sends one request through the CONNECT proxy to the TLS origin with a
  23619. // credential configured for each hop, and checks that each credential reaches
  23620. // only the hop it was configured for: the proxy's on the CONNECT request, the
  23621. // origin's (every header in origin_headers) on the tunnelled request.
  23622. void CredentialsStayWithTheirHop(
  23623. const std::function<void(SSLClient &)> &set_credentials,
  23624. const std::string &scheme,
  23625. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  23626. std::atomic<int> origin_hits{0};
  23627. std::atomic<bool> origin_saw_proxy_authz{false};
  23628. std::atomic<bool> origin_saw_headers{false};
  23629. ScopedSSLServer origin;
  23630. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23631. origin_hits++;
  23632. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  23633. origin_saw_headers =
  23634. std::all_of(origin_headers.begin(), origin_headers.end(),
  23635. [&](const std::string &h) { return req.has_header(h); });
  23636. res.set_content("ok", "text/plain");
  23637. });
  23638. origin.listen();
  23639. ScopedConnectProxy proxy(origin.port());
  23640. ASSERT_NE(0, proxy.port());
  23641. // Pinned to 127.0.0.1 for the same reason as the test below.
  23642. SSLClient cli("127.0.0.1", origin.port());
  23643. cli.enable_server_certificate_verification(false);
  23644. cli.set_proxy("127.0.0.1", proxy.port());
  23645. set_credentials(cli);
  23646. auto res = cli.Get("/x");
  23647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23648. EXPECT_EQ(StatusCode::OK_200, res->status);
  23649. EXPECT_EQ(1, origin_hits.load());
  23650. EXPECT_EQ(1, proxy.connect_hits());
  23651. EXPECT_TRUE(origin_saw_headers.load());
  23652. EXPECT_FALSE(origin_saw_proxy_authz.load())
  23653. << "Proxy-Authorization must not be sent inside the tunnel";
  23654. auto connect_req = proxy.connect_request();
  23655. EXPECT_NE(std::string::npos,
  23656. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  23657. for (const auto &h : origin_headers) {
  23658. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  23659. << h << " must not be sent to the proxy on CONNECT";
  23660. }
  23661. }
  23662. } // namespace proxy_tunnel_test
  23663. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  23664. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23665. [](SSLClient &cli) {
  23666. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23667. cli.set_basic_auth("origin-user", "origin-pass");
  23668. },
  23669. "Basic");
  23670. }
  23671. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  23672. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23673. [](SSLClient &cli) {
  23674. cli.set_proxy_bearer_token_auth("proxy-token");
  23675. cli.set_bearer_token_auth("origin-token");
  23676. },
  23677. "Bearer");
  23678. }
  23679. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  23680. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23681. [](SSLClient &cli) {
  23682. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23683. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  23684. {"Cookie", "sid=origin-session"},
  23685. {"X-Api-Key", "origin-key"}});
  23686. },
  23687. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  23688. }
  23689. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  23690. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  23691. // retry; otherwise proxy creds would be sent to the origin.
  23692. std::atomic<int> origin_hits{0};
  23693. std::atomic<bool> origin_saw_proxy_authz{false};
  23694. proxy_tunnel_test::ScopedSSLServer origin;
  23695. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23696. origin_hits++;
  23697. if (req.has_header("Proxy-Authorization")) {
  23698. origin_saw_proxy_authz = true;
  23699. }
  23700. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23701. res.set_header("Proxy-Authenticate",
  23702. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  23703. "algorithm=MD5");
  23704. });
  23705. origin.listen();
  23706. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  23707. ASSERT_NE(0, proxy.port());
  23708. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  23709. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  23710. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  23711. // and answer with its own status, making this test flaky.
  23712. SSLClient cli("127.0.0.1", origin.port());
  23713. cli.enable_server_certificate_verification(false);
  23714. cli.set_proxy("127.0.0.1", proxy.port());
  23715. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23716. auto res = cli.Get("/x");
  23717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23718. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23719. EXPECT_EQ(1, origin_hits.load());
  23720. EXPECT_FALSE(origin_saw_proxy_authz.load());
  23721. EXPECT_EQ(1, proxy.connect_hits());
  23722. }
  23723. #endif