test.cc 883 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280
  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 declaration: in split builds split.py strips `inline` and moves the
  474. // definition into httplib.cc, so detail::base64_encode is not visible from the
  475. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  476. // in both header-only and split builds.
  477. namespace httplib {
  478. namespace detail {
  479. std::string base64_encode(const std::string &in);
  480. } // namespace detail
  481. } // namespace httplib
  482. TEST(Base64EncodeTest, KnownAnswers) {
  483. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  484. // where the accumulator's top bit is already set before the next shift.
  485. EXPECT_EQ("", detail::base64_encode(""));
  486. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  487. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  488. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  489. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  490. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  491. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  492. // High bytes keep the top bit set across several rounds.
  493. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  494. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  495. }
  496. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  497. string unescapedCharacters = "-_.!~*'()";
  498. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  499. }
  500. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  501. string reservedCharacters = ";,/?:@&=+$";
  502. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  503. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  504. }
  505. TEST(ClientQueryOrder, PreserveOrder) {
  506. // This test reproduces Issue #2259: client may reorder query parameters
  507. // when sending a GET request. The expected behavior is that the client
  508. // preserves the original query string order when the caller supplied it
  509. // as part of the path.
  510. Server svr;
  511. svr.Get("/", [&](const Request &req, Response &res) {
  512. // Echo back the raw target so the test can assert ordering
  513. res.set_content(req.target, "text/plain");
  514. });
  515. std::thread t{[&] { svr.listen(HOST, PORT); }};
  516. auto se = detail::scope_exit([&] {
  517. svr.stop();
  518. t.join();
  519. ASSERT_FALSE(svr.is_running());
  520. });
  521. svr.wait_until_ready();
  522. Client cli(HOST, PORT);
  523. ASSERT_TRUE(cli.is_valid());
  524. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  525. auto res = cli.Get(original);
  526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  527. // Expect the echoed target to exactly match the original path (order
  528. // preserved)
  529. EXPECT_EQ(res->body, original);
  530. }
  531. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  532. string chineseCharacters = U8("中国語");
  533. string russianCharacters = U8("дом");
  534. string brazilianCharacters = U8("óculos");
  535. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  536. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  537. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  538. "%D0%B4%D0%BE%D0%BC");
  539. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  540. }
  541. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  542. string unescapedCharacters = "-_.!~*'()";
  543. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  544. }
  545. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  546. string reservedCharacters = ";,/?:@&=+$";
  547. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  548. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  549. }
  550. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  551. string chineseCharacters = U8("中国語");
  552. string russianCharacters = U8("дом");
  553. string brazilianCharacters = U8("óculos");
  554. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  555. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  556. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  557. "%D0%B4%D0%BE%D0%BC");
  558. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  559. }
  560. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  561. // Issue #2082 use case: encoding path component with ampersand
  562. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  563. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  564. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  565. }
  566. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  567. string unescapedCharacters = "-_.!~*'()";
  568. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  569. }
  570. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  571. string reservedCharacters = ";,/?:@&=+$#";
  572. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  573. }
  574. TEST(EncodeUriTest, TestUTF8Characters) {
  575. string chineseCharacters = U8("中国語");
  576. string russianCharacters = U8("дом");
  577. string brazilianCharacters = U8("óculos");
  578. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  579. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  580. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  581. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  582. }
  583. TEST(EncodeUriTest, TestCompleteUri) {
  584. string uri =
  585. "https://example.com/path/to/resource?query=value&param=test#fragment";
  586. EXPECT_EQ(
  587. httplib::encode_uri(uri),
  588. "https://example.com/path/to/resource?query=value&param=test#fragment");
  589. }
  590. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  591. string uri =
  592. "https://example.com/path with spaces/file name.html?q=hello world";
  593. EXPECT_EQ(httplib::encode_uri(uri),
  594. "https://example.com/path%20with%20spaces/"
  595. "file%20name.html?q=hello%20world");
  596. }
  597. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  598. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  599. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  600. }
  601. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  602. string unescapedCharacters = "-_.!~*'()";
  603. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  604. }
  605. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  606. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  607. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  608. string encodedBrazilian = "%C3%B3culos";
  609. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  610. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  611. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  612. }
  613. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  614. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  615. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  616. "Piri Tommy Villiers - on & on");
  617. }
  618. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  619. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  620. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  621. }
  622. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  623. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  624. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  625. }
  626. TEST(DecodeUriTest, TestUTF8Characters) {
  627. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  628. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  629. string encodedBrazilian = "%C3%B3culos";
  630. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  631. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  632. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  633. }
  634. TEST(DecodeUriTest, TestCompleteUri) {
  635. string encodedUri = "https://example.com/path%20with%20spaces/"
  636. "file%20name.html?q=hello%20world";
  637. EXPECT_EQ(
  638. httplib::decode_uri(encodedUri),
  639. "https://example.com/path with spaces/file name.html?q=hello world");
  640. }
  641. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  642. string original =
  643. "https://example.com/path with spaces/file name.html?q=hello world";
  644. string encoded = httplib::encode_uri(original);
  645. string decoded = httplib::decode_uri(encoded);
  646. EXPECT_EQ(decoded, original);
  647. }
  648. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  649. // decode_uri is the inverse of encode_uri: an escaped reserved character
  650. // stays encoded so it is not promoted into a real delimiter, while
  651. // non-reserved escapes still decode (like JS decodeURI).
  652. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  653. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  654. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  655. "%3F%3A%40%26%3D%2B%24%2C%3B");
  656. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  657. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  658. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  659. "http://example.com/a%2Fb");
  660. // decode_uri_component still decodes the reserved character.
  661. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  662. }
  663. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  664. string original = "Piri Tommy Villiers - on & on";
  665. string encoded = httplib::encode_uri_component(original);
  666. string decoded = httplib::decode_uri_component(encoded);
  667. EXPECT_EQ(decoded, original);
  668. }
  669. TEST(TrimTests, TrimStringTests) {
  670. EXPECT_EQ("abc", detail::trim_copy("abc"));
  671. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  672. EXPECT_TRUE(detail::trim_copy("").empty());
  673. }
  674. TEST(AsciiTest, LocaleIndependentClassification) {
  675. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  676. // which consult the global C locale: std::isalnum(0xC5) can return true
  677. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  678. // helpers must classify every byte by the ASCII grammar alone.
  679. for (int i = 0; i < 256; i++) {
  680. auto c = static_cast<char>(i);
  681. auto is_digit = i >= '0' && i <= '9';
  682. auto is_upper = i >= 'A' && i <= 'Z';
  683. auto is_lower = i >= 'a' && i <= 'z';
  684. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  685. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  686. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  687. << "byte " << i;
  688. }
  689. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  690. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  691. // Non-ASCII bytes must be percent-encoded, never passed through as
  692. // alphanumeric.
  693. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  694. }
  695. TEST(FromCharsTest, Double) {
  696. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  697. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  698. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  699. auto parse = [](const std::string &s, double &v) {
  700. return detail::from_chars(s.data(), s.data() + s.size(), v);
  701. };
  702. double v = -1.0;
  703. // Representative quality values.
  704. EXPECT_EQ(parse("0", v).ec, std::errc{});
  705. EXPECT_DOUBLE_EQ(v, 0.0);
  706. EXPECT_EQ(parse("1", v).ec, std::errc{});
  707. EXPECT_DOUBLE_EQ(v, 1.0);
  708. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  709. EXPECT_DOUBLE_EQ(v, 0.8);
  710. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  711. EXPECT_DOUBLE_EQ(v, 0.001);
  712. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  713. EXPECT_DOUBLE_EQ(v, 1.0);
  714. // A missing integer or fractional part is tolerated.
  715. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  716. EXPECT_DOUBLE_EQ(v, 0.5);
  717. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  718. EXPECT_DOUBLE_EQ(v, 5.0);
  719. // Values outside [0, 1] still parse; the caller range-checks them.
  720. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  721. EXPECT_DOUBLE_EQ(v, 123.456);
  722. // Stops at the first byte that is not part of the number and reports where.
  723. std::string trailing = "0.9, text/html";
  724. auto r = parse(trailing, v);
  725. EXPECT_EQ(r.ec, std::errc{});
  726. EXPECT_DOUBLE_EQ(v, 0.9);
  727. EXPECT_EQ(*r.ptr, ',');
  728. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  729. // outright, and an 'e'/'E' simply ends the number.
  730. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  731. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  732. std::string exp_input = "1.5e3";
  733. r = parse(exp_input, v);
  734. EXPECT_EQ(r.ec, std::errc{});
  735. EXPECT_DOUBLE_EQ(v, 1.5);
  736. EXPECT_EQ(*r.ptr, 'e');
  737. // Invalid inputs.
  738. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  739. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  740. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  741. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  742. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  743. // Pathological but well-formed inputs must stay bounded (no overflow, no
  744. // out-of-bounds table access) and stay within [0, 1] for the caller.
  745. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  746. std::errc{});
  747. EXPECT_DOUBLE_EQ(v, 0.0);
  748. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  749. std::errc{});
  750. EXPECT_GE(v, 0.0);
  751. EXPECT_LE(v, 1.0);
  752. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  753. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  754. }
  755. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  756. // Simple case without quality values
  757. std::vector<std::string> result1;
  758. EXPECT_TRUE(detail::parse_accept_header(
  759. "text/html,application/json,text/plain", result1));
  760. EXPECT_EQ(result1.size(), 3U);
  761. EXPECT_EQ(result1[0], "text/html");
  762. EXPECT_EQ(result1[1], "application/json");
  763. EXPECT_EQ(result1[2], "text/plain");
  764. // With quality values
  765. std::vector<std::string> result2;
  766. EXPECT_TRUE(detail::parse_accept_header(
  767. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  768. EXPECT_EQ(result2.size(), 3U);
  769. EXPECT_EQ(result2[0], "application/json"); // highest q value
  770. EXPECT_EQ(result2[1], "text/html");
  771. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  772. }
  773. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  774. // Mixed with and without quality values
  775. std::vector<std::string> result;
  776. EXPECT_TRUE(detail::parse_accept_header(
  777. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  778. EXPECT_EQ(result.size(), 3U);
  779. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  780. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  781. EXPECT_EQ(result[2], "application/json"); // q=0.5
  782. }
  783. TEST(ParseAcceptHeaderTest, EdgeCases) {
  784. // Empty header
  785. std::vector<std::string> empty_result;
  786. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  787. EXPECT_TRUE(empty_result.empty());
  788. // Single type
  789. std::vector<std::string> single_result;
  790. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  791. EXPECT_EQ(single_result.size(), 1U);
  792. EXPECT_EQ(single_result[0], "application/json");
  793. // Wildcard types
  794. std::vector<std::string> wildcard_result;
  795. EXPECT_TRUE(detail::parse_accept_header(
  796. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  797. EXPECT_EQ(wildcard_result.size(), 3U);
  798. EXPECT_EQ(wildcard_result[0], "application/json");
  799. EXPECT_EQ(wildcard_result[1], "text/*");
  800. EXPECT_EQ(wildcard_result[2], "*/*");
  801. }
  802. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  803. // Common browser Accept header
  804. std::vector<std::string> browser_result;
  805. EXPECT_TRUE(
  806. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  807. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  808. browser_result));
  809. EXPECT_EQ(browser_result.size(), 6U);
  810. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  811. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  812. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  813. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  814. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  815. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  816. // API client header
  817. std::vector<std::string> api_result;
  818. EXPECT_TRUE(detail::parse_accept_header(
  819. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  820. api_result));
  821. EXPECT_EQ(api_result.size(), 3U);
  822. EXPECT_EQ(api_result[0], "application/json");
  823. EXPECT_EQ(api_result[1], "application/xml");
  824. EXPECT_EQ(api_result[2], "text/plain");
  825. }
  826. TEST(ParseAcceptHeaderTest, SpecialCases) {
  827. // Quality value with 3 decimal places
  828. std::vector<std::string> decimal_result;
  829. EXPECT_TRUE(detail::parse_accept_header(
  830. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  831. EXPECT_EQ(decimal_result.size(), 2U);
  832. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  833. EXPECT_EQ(decimal_result[1], "text/html");
  834. // Zero quality (should still be included but with lowest priority)
  835. std::vector<std::string> zero_q_result;
  836. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  837. zero_q_result));
  838. EXPECT_EQ(zero_q_result.size(), 2U);
  839. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  840. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  841. // No spaces around commas
  842. std::vector<std::string> no_space_result;
  843. EXPECT_TRUE(detail::parse_accept_header(
  844. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  845. no_space_result));
  846. EXPECT_EQ(no_space_result.size(), 3U);
  847. EXPECT_EQ(no_space_result[0], "text/html");
  848. EXPECT_EQ(no_space_result[1], "application/json");
  849. EXPECT_EQ(no_space_result[2], "text/plain");
  850. }
  851. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  852. // Quality values always use '.' as the decimal separator, so parsing must
  853. // not depend on the process locale. An embedding application may have
  854. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  855. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  856. std::string saved = cur ? cur : "C";
  857. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  858. "fr_FR.UTF-8"};
  859. bool switched = false;
  860. for (const auto loc : comma_locales) {
  861. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  862. std::localeconv()->decimal_point[0] == ',') {
  863. switched = true;
  864. break;
  865. }
  866. }
  867. if (!switched) {
  868. std::setlocale(LC_NUMERIC, saved.c_str());
  869. GTEST_SKIP() << "no comma-decimal locale available on this host";
  870. }
  871. // The higher-weighted type appears later in the list, so a correct parse
  872. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  873. // sensitive parse reads both weights as 0 and leaves the original order.
  874. std::vector<std::string> result;
  875. EXPECT_TRUE(detail::parse_accept_header(
  876. "application/json;q=0.1,text/html;q=0.9", result));
  877. ASSERT_EQ(result.size(), 2U);
  878. EXPECT_EQ(result[0], "text/html");
  879. EXPECT_EQ(result[1], "application/json");
  880. std::setlocale(LC_NUMERIC, saved.c_str());
  881. }
  882. TEST(ParseAcceptHeaderTest, InvalidCases) {
  883. std::vector<std::string> result;
  884. // Invalid quality value (> 1.0)
  885. EXPECT_FALSE(
  886. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  887. // Invalid quality value (< 0.0)
  888. EXPECT_FALSE(
  889. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  890. // Invalid quality value (not a number)
  891. EXPECT_FALSE(detail::parse_accept_header(
  892. "text/html;q=invalid,application/json", result));
  893. // A valid numeric prefix does not make the entire quality value valid.
  894. EXPECT_FALSE(detail::parse_accept_header(
  895. "text/html;q=0.5junk,application/json", result));
  896. // Empty quality value
  897. EXPECT_FALSE(
  898. detail::parse_accept_header("text/html;q=,application/json", result));
  899. // Invalid media type format (no slash and not wildcard)
  900. EXPECT_FALSE(
  901. detail::parse_accept_header("invalidtype,application/json", result));
  902. // Valid cases should still work
  903. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  904. EXPECT_EQ(result.size(), 1U);
  905. EXPECT_EQ(result[0], "*/*");
  906. EXPECT_TRUE(detail::parse_accept_header("*", result));
  907. EXPECT_EQ(result.size(), 1U);
  908. EXPECT_EQ(result[0], "*");
  909. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  910. EXPECT_EQ(result.size(), 1U);
  911. EXPECT_EQ(result[0], "text/*");
  912. }
  913. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  914. // elements, so a leading, trailing or doubled comma is a legal Accept value
  915. // and must not be answered with 400 Bad Request.
  916. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  917. struct {
  918. const char *value;
  919. std::vector<std::string> expected;
  920. } cases[] = {
  921. {",application/json", {"application/json"}},
  922. {"text/html,", {"text/html"}},
  923. {"text/html,,*/*", {"text/html", "*/*"}},
  924. // An empty element may be spelled with whitespace in it
  925. {"text/html, , application/json", {"text/html", "application/json"}},
  926. // Nothing but empty elements is an empty list, which means the same
  927. // thing as no Accept header at all
  928. {",,,", {}},
  929. // Quality values still apply across ignored empty elements
  930. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  931. };
  932. for (const auto &c : cases) {
  933. std::vector<std::string> result;
  934. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  935. << "value: " << c.value;
  936. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  937. }
  938. // An invalid entry is still rejected when empty elements surround it
  939. std::vector<std::string> result;
  940. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  941. }
  942. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  943. Server svr;
  944. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  945. EXPECT_EQ(req.accept_content_types.size(), 3U);
  946. EXPECT_EQ(req.accept_content_types[0], "application/json");
  947. EXPECT_EQ(req.accept_content_types[1], "text/html");
  948. EXPECT_EQ(req.accept_content_types[2], "*/*");
  949. res.set_content("ok", "text/plain");
  950. });
  951. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  952. EXPECT_TRUE(false);
  953. res.set_content("bad request", "text/plain");
  954. });
  955. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  956. auto se = detail::scope_exit([&] {
  957. svr.stop();
  958. listen_thread.join();
  959. ASSERT_FALSE(svr.is_running());
  960. });
  961. svr.wait_until_ready();
  962. Client cli("localhost", PORT);
  963. {
  964. auto res = cli.Get(
  965. "/accept_ok",
  966. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  968. EXPECT_EQ(StatusCode::OK_200, res->status);
  969. }
  970. {
  971. auto res = cli.Get("/accept_bad_request",
  972. Headers{{"Accept", "text/html;q=abc,application/json"}});
  973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  974. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  975. }
  976. }
  977. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  978. Server svr;
  979. svr.Get("/", [](const Request & /*req*/, Response &res) {
  980. res.set_content("ok", "text/plain");
  981. });
  982. std::atomic<int> start_count{0};
  983. std::atomic<bool> running_when_called{false};
  984. svr.set_start_handler([&]() {
  985. running_when_called = svr.is_running();
  986. start_count++;
  987. });
  988. auto port = svr.bind_to_any_port(HOST);
  989. std::thread t([&]() { svr.listen_after_bind(); });
  990. auto se = detail::scope_exit([&] {
  991. svr.stop();
  992. t.join();
  993. ASSERT_FALSE(svr.is_running());
  994. });
  995. svr.wait_until_ready();
  996. // A successful request proves the accept loop is running, which the start
  997. // handler precedes; so by now the handler must have run exactly once.
  998. Client cli(HOST, port);
  999. cli.set_connection_timeout(std::chrono::seconds(5));
  1000. auto res = cli.Get("/");
  1001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1002. EXPECT_EQ(StatusCode::OK_200, res->status);
  1003. EXPECT_EQ(1, start_count.load());
  1004. EXPECT_TRUE(running_when_called.load());
  1005. }
  1006. TEST(DivideTest, DivideStringTests) {
  1007. auto divide = [](const std::string &str, char d) {
  1008. std::string lhs;
  1009. std::string rhs;
  1010. detail::divide(str, d,
  1011. [&](const char *lhs_data, std::size_t lhs_size,
  1012. const char *rhs_data, std::size_t rhs_size) {
  1013. lhs.assign(lhs_data, lhs_size);
  1014. rhs.assign(rhs_data, rhs_size);
  1015. });
  1016. return std::make_pair(std::move(lhs), std::move(rhs));
  1017. };
  1018. {
  1019. const auto res = divide("", '=');
  1020. EXPECT_EQ(res.first, "");
  1021. EXPECT_EQ(res.second, "");
  1022. }
  1023. {
  1024. const auto res = divide("=", '=');
  1025. EXPECT_EQ(res.first, "");
  1026. EXPECT_EQ(res.second, "");
  1027. }
  1028. {
  1029. const auto res = divide(" ", '=');
  1030. EXPECT_EQ(res.first, " ");
  1031. EXPECT_EQ(res.second, "");
  1032. }
  1033. {
  1034. const auto res = divide("a", '=');
  1035. EXPECT_EQ(res.first, "a");
  1036. EXPECT_EQ(res.second, "");
  1037. }
  1038. {
  1039. const auto res = divide("a=", '=');
  1040. EXPECT_EQ(res.first, "a");
  1041. EXPECT_EQ(res.second, "");
  1042. }
  1043. {
  1044. const auto res = divide("=b", '=');
  1045. EXPECT_EQ(res.first, "");
  1046. EXPECT_EQ(res.second, "b");
  1047. }
  1048. {
  1049. const auto res = divide("a=b", '=');
  1050. EXPECT_EQ(res.first, "a");
  1051. EXPECT_EQ(res.second, "b");
  1052. }
  1053. {
  1054. const auto res = divide("a=b=", '=');
  1055. EXPECT_EQ(res.first, "a");
  1056. EXPECT_EQ(res.second, "b=");
  1057. }
  1058. {
  1059. const auto res = divide("a=b=c", '=');
  1060. EXPECT_EQ(res.first, "a");
  1061. EXPECT_EQ(res.second, "b=c");
  1062. }
  1063. }
  1064. TEST(SplitTest, ParseQueryString) {
  1065. string s = "key1=val1&key2=val2&key3=val3";
  1066. Params dic;
  1067. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1068. [&](const char *b, const char *e) {
  1069. string key, val;
  1070. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1071. if (key.empty()) {
  1072. key.assign(b2, e2);
  1073. } else {
  1074. val.assign(b2, e2);
  1075. }
  1076. });
  1077. dic.emplace(key, val);
  1078. });
  1079. EXPECT_EQ("val1", dic.find("key1")->second);
  1080. EXPECT_EQ("val2", dic.find("key2")->second);
  1081. EXPECT_EQ("val3", dic.find("key3")->second);
  1082. }
  1083. TEST(SplitTest, ParseInvalidQueryTests) {
  1084. {
  1085. string s = " ";
  1086. Params dict;
  1087. detail::parse_query_text(s, dict);
  1088. EXPECT_TRUE(dict.empty());
  1089. }
  1090. {
  1091. string s = " = =";
  1092. Params dict;
  1093. detail::parse_query_text(s, dict);
  1094. EXPECT_TRUE(dict.empty());
  1095. }
  1096. }
  1097. TEST(ParseQueryTest, ParseQueryString) {
  1098. {
  1099. std::string s = "key1=val1&key2=val2&key3=val3";
  1100. Params dic;
  1101. detail::parse_query_text(s, dic);
  1102. EXPECT_EQ("val1", dic.find("key1")->second);
  1103. EXPECT_EQ("val2", dic.find("key2")->second);
  1104. EXPECT_EQ("val3", dic.find("key3")->second);
  1105. }
  1106. {
  1107. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1108. Params dic;
  1109. detail::parse_query_text(s, dic);
  1110. EXPECT_EQ("", dic.find("key1")->second);
  1111. EXPECT_EQ("val1", dic.find("key2")->second);
  1112. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1113. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1114. }
  1115. }
  1116. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1117. Params dic;
  1118. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1119. dic.emplace("key1", "val1");
  1120. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1121. dic.emplace("key2", "val2");
  1122. dic.emplace("key3", "val3");
  1123. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1124. }
  1125. // Joins every entry of a Headers or Params into "key=value " so a whole
  1126. // traversal can be compared in one assertion. Both are instantiations of the
  1127. // same insertion-ordered container, so one helper serves both.
  1128. template <typename Map> static std::string entries_to_string(const Map &m) {
  1129. std::string s;
  1130. for (const auto &entry : m) {
  1131. s += entry.first + "=" + entry.second + " ";
  1132. }
  1133. return s;
  1134. }
  1135. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1136. // Params used to be a std::multimap, which sorted by name and handed the
  1137. // caller's query back alphabetised. A client signing its query string could
  1138. // not reproduce the order it asked for.
  1139. Params dic;
  1140. dic.emplace("zulu", "1");
  1141. dic.emplace("alpha", "2");
  1142. dic.emplace("mike", "3");
  1143. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1144. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1145. }
  1146. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1147. Params dic;
  1148. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1149. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1150. }
  1151. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1152. Request req;
  1153. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1154. req.params);
  1155. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1156. EXPECT_EQ("first", req.get_param_value("tag"));
  1157. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1158. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1159. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1160. EXPECT_EQ("", req.get_param_value("tag", 3));
  1161. }
  1162. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1163. // Params shares its container with Headers, which matches field names
  1164. // case-insensitively. Parameter names must not pick that up.
  1165. Params dic;
  1166. dic.emplace("Key", "upper");
  1167. dic.emplace("key", "lower");
  1168. EXPECT_EQ(2U, dic.size());
  1169. EXPECT_EQ(1U, dic.count("Key"));
  1170. EXPECT_EQ(1U, dic.count("key"));
  1171. EXPECT_EQ("upper", dic.find("Key")->second);
  1172. EXPECT_EQ("lower", dic.find("key")->second);
  1173. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1174. }
  1175. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1176. Server svr;
  1177. std::string order;
  1178. svr.Get("/order", [&](const Request &req, Response &res) {
  1179. order = entries_to_string(req.params);
  1180. res.set_content("ok", "text/plain");
  1181. });
  1182. auto port = svr.bind_to_any_port(HOST);
  1183. thread t = thread([&] { svr.listen_after_bind(); });
  1184. auto se = detail::scope_exit([&] {
  1185. svr.stop();
  1186. t.join();
  1187. ASSERT_FALSE(svr.is_running());
  1188. });
  1189. svr.wait_until_ready();
  1190. Client cli(HOST, port);
  1191. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1192. ASSERT_TRUE(res);
  1193. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1194. }
  1195. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1196. Server svr;
  1197. std::string field_order, file_order;
  1198. svr.Post("/order", [&](const Request &req, Response &res) {
  1199. for (const auto &field : req.form.fields) {
  1200. field_order += field.first + "=" + field.second.content + " ";
  1201. }
  1202. for (const auto &file : req.form.files) {
  1203. file_order += file.first + "=" + file.second.filename + " ";
  1204. }
  1205. res.set_content("ok", "text/plain");
  1206. });
  1207. auto port = svr.bind_to_any_port(HOST);
  1208. thread t = thread([&] { svr.listen_after_bind(); });
  1209. auto se = detail::scope_exit([&] {
  1210. svr.stop();
  1211. t.join();
  1212. ASSERT_FALSE(svr.is_running());
  1213. });
  1214. svr.wait_until_ready();
  1215. UploadFormDataItems items = {
  1216. {"zulu", "1", "", ""},
  1217. {"alpha", "2", "", ""},
  1218. {"mike", "3", "", ""},
  1219. {"zebra", "z", "z.txt", "text/plain"},
  1220. {"apple", "a", "a.txt", "text/plain"},
  1221. };
  1222. Client cli(HOST, port);
  1223. auto res = cli.Post("/order", items);
  1224. ASSERT_TRUE(res);
  1225. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1226. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1227. }
  1228. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1229. Server svr;
  1230. std::vector<std::string> values;
  1231. std::string first, second, out_of_range, order;
  1232. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1233. values = req.form.get_fields("tag");
  1234. first = req.form.get_field("tag", 0);
  1235. second = req.form.get_field("tag", 1);
  1236. out_of_range = req.form.get_field("tag", 2);
  1237. for (const auto &field : req.form.fields) {
  1238. order += field.first + "=" + field.second.content + " ";
  1239. }
  1240. res.set_content("ok", "text/plain");
  1241. });
  1242. auto port = svr.bind_to_any_port(HOST);
  1243. thread t = thread([&] { svr.listen_after_bind(); });
  1244. auto se = detail::scope_exit([&] {
  1245. svr.stop();
  1246. t.join();
  1247. ASSERT_FALSE(svr.is_running());
  1248. });
  1249. svr.wait_until_ready();
  1250. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1251. // not adjacent in the container.
  1252. UploadFormDataItems items = {
  1253. {"tag", "first", "", ""},
  1254. {"other", "x", "", ""},
  1255. {"tag", "second", "", ""},
  1256. };
  1257. Client cli(HOST, port);
  1258. auto res = cli.Post("/repeated", items);
  1259. ASSERT_TRUE(res);
  1260. ASSERT_EQ(2U, values.size());
  1261. EXPECT_EQ("first", values[0]);
  1262. EXPECT_EQ("second", values[1]);
  1263. EXPECT_EQ("first", first);
  1264. EXPECT_EQ("second", second);
  1265. // std::multimap already kept entries sharing a name in insertion order, so
  1266. // everything above passes without this change too. The whole traversal is
  1267. // what tells the two apart: sorting by name would hoist "other" to the front
  1268. // and the two "tag" parts would end up adjacent.
  1269. EXPECT_EQ("tag=first other=x tag=second ", order);
  1270. // Advancing past the last entry of a name used to run off the container;
  1271. // the container's saturating increment makes it return the default instead.
  1272. EXPECT_EQ("", out_of_range);
  1273. }
  1274. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1275. // Server::read_content() keeps a FormFields::iterator alive across the
  1276. // content callbacks that fill the part it points at. The container is
  1277. // vector-backed, so a later emplace can reallocate and invalidate an older
  1278. // iterator; 64 parts grow the vector through seven reallocations, which
  1279. // checks that every part's content still lands in its own entry.
  1280. const size_t part_count = 64;
  1281. // One formula for both the parts sent and the values expected back, so the
  1282. // two cannot drift apart.
  1283. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1284. auto content_of = [](size_t i) {
  1285. return std::string(64, static_cast<char>('a' + (i % 26)));
  1286. };
  1287. Server svr;
  1288. std::vector<std::pair<std::string, std::string>> received;
  1289. svr.Post("/many", [&](const Request &req, Response &res) {
  1290. for (const auto &field : req.form.fields) {
  1291. received.emplace_back(field.first, field.second.content);
  1292. }
  1293. res.set_content("ok", "text/plain");
  1294. });
  1295. auto port = svr.bind_to_any_port(HOST);
  1296. thread t = thread([&] { svr.listen_after_bind(); });
  1297. auto se = detail::scope_exit([&] {
  1298. svr.stop();
  1299. t.join();
  1300. ASSERT_FALSE(svr.is_running());
  1301. });
  1302. svr.wait_until_ready();
  1303. UploadFormDataItems items;
  1304. for (size_t i = 0; i < part_count; i++) {
  1305. items.push_back({name_of(i), content_of(i), "", ""});
  1306. }
  1307. Client cli(HOST, port);
  1308. auto res = cli.Post("/many", items);
  1309. ASSERT_TRUE(res);
  1310. ASSERT_EQ(part_count, received.size());
  1311. for (size_t i = 0; i < part_count; i++) {
  1312. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1313. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1314. }
  1315. }
  1316. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1317. string content_type = "multipart/form-data; boundary=something";
  1318. string boundary;
  1319. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1320. EXPECT_TRUE(ret);
  1321. EXPECT_EQ(boundary, "something");
  1322. }
  1323. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1324. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1325. string boundary;
  1326. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1327. EXPECT_TRUE(ret);
  1328. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1329. }
  1330. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1331. string content_type =
  1332. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1333. string boundary;
  1334. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1335. EXPECT_TRUE(ret);
  1336. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1337. }
  1338. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1339. string content_type =
  1340. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1341. string boundary;
  1342. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1343. EXPECT_TRUE(ret);
  1344. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1345. }
  1346. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1347. const string boundary(70, 'a');
  1348. string content_type = "multipart/form-data; boundary=" + boundary;
  1349. string parsed;
  1350. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1351. EXPECT_TRUE(ret);
  1352. EXPECT_EQ(parsed, boundary);
  1353. }
  1354. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1355. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1356. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1357. string parsed;
  1358. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1359. EXPECT_FALSE(ret);
  1360. }
  1361. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1362. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1363. // is 72 characters on the wire and still valid.
  1364. const string boundary(70, 'a');
  1365. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1366. string parsed;
  1367. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1368. EXPECT_EQ(parsed, boundary);
  1369. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1370. parsed.clear();
  1371. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1372. }
  1373. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1374. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1375. // The parameter parser must not treat that '=' as the key/value separator.
  1376. string content_type =
  1377. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1378. "charset=UTF-8";
  1379. string parsed;
  1380. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1381. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1382. }
  1383. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1384. // A ';' inside the quoted-string is part of the value, not a parameter
  1385. // separator, so it must not truncate the boundary.
  1386. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1387. string parsed;
  1388. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1389. EXPECT_EQ(parsed, "a;b");
  1390. }
  1391. TEST(ParseDispositionParamsTest, QuotedValues) {
  1392. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1393. // ';' and '=' are ordinary characters inside one.
  1394. struct {
  1395. const char *value;
  1396. std::vector<std::pair<const char *, const char *>> expected;
  1397. } cases[] = {
  1398. {"name=\"file1\"; filename=\"a.txt\"",
  1399. {{"name", "file1"}, {"filename", "a.txt"}}},
  1400. // Whitespace around '=' and ';' is still trimmed
  1401. {"name=\"file2\" ;filename = \"a.html\"",
  1402. {{"name", "file2"}, {"filename", "a.html"}}},
  1403. // '=' inside the value used to leave only the text after the last one
  1404. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1405. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1406. {"name=\"x=y\"", {{"name", "x=y"}}},
  1407. // ';' inside the value used to truncate the pair and leave a bogus one
  1408. {"name=\"file3\"; filename=\"a;b.txt\"",
  1409. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1410. // An unquoted value keeps working, and so does filename*
  1411. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1412. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1413. // A parameter with no key is dropped rather than turned into one whose
  1414. // key is the value
  1415. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1416. };
  1417. for (const auto &c : cases) {
  1418. Params params;
  1419. detail::parse_disposition_params(c.value, params);
  1420. for (const auto &kv : c.expected) {
  1421. auto it = params.find(kv.first);
  1422. ASSERT_NE(it, params.end())
  1423. << "value: " << c.value << ", key: " << kv.first;
  1424. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1425. }
  1426. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1427. }
  1428. }
  1429. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1430. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1431. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1432. Server svr;
  1433. std::string field_value, file_name, file_filename;
  1434. bool has_field = false, has_file = false;
  1435. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1436. has_field = req.form.has_field("x=y");
  1437. field_value = req.form.get_field("x=y");
  1438. has_file = req.form.has_file("file1");
  1439. const auto &file = req.form.get_file("file1");
  1440. file_name = file.name;
  1441. file_filename = file.filename;
  1442. res.set_content("ok", "text/plain");
  1443. });
  1444. auto port = svr.bind_to_any_port(HOST);
  1445. thread t = thread([&] { svr.listen_after_bind(); });
  1446. auto se = detail::scope_exit([&] {
  1447. svr.stop();
  1448. t.join();
  1449. ASSERT_FALSE(svr.is_running());
  1450. });
  1451. svr.wait_until_ready();
  1452. UploadFormDataItems items = {
  1453. {"x=y", "field-value", "", ""},
  1454. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1455. };
  1456. Client cli(HOST, port);
  1457. auto res = cli.Post("/quoted", items);
  1458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1459. ASSERT_EQ(StatusCode::OK_200, res->status);
  1460. EXPECT_TRUE(has_field);
  1461. EXPECT_EQ("field-value", field_value);
  1462. EXPECT_TRUE(has_file);
  1463. EXPECT_EQ("file1", file_name);
  1464. EXPECT_EQ("a;b=report.pdf", file_filename);
  1465. }
  1466. TEST(GetHeaderValueTest, DefaultValue) {
  1467. Headers headers = {{"Dummy", "Dummy"}};
  1468. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1469. EXPECT_STREQ("text/plain", val);
  1470. }
  1471. TEST(GetHeaderValueTest, DefaultValueInt) {
  1472. Headers headers = {{"Dummy", "Dummy"}};
  1473. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1474. EXPECT_EQ(100ull, val);
  1475. }
  1476. TEST(GetHeaderValueTest, RegularValue) {
  1477. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1478. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1479. EXPECT_STREQ("text/html", val);
  1480. }
  1481. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1482. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1483. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1484. EXPECT_STREQ("text/html", val);
  1485. }
  1486. TEST(GetHeaderValueTest, SetContent) {
  1487. Response res;
  1488. res.set_content("html", "text/html");
  1489. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1490. res.set_content("text", "text/plain");
  1491. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1492. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1493. }
  1494. TEST(GetHeaderValueTest, RegularValueInt) {
  1495. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1496. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1497. EXPECT_EQ(100ull, val);
  1498. }
  1499. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1500. Headers headers = {{"Content-Length", "x"}};
  1501. auto is_invalid_value = false;
  1502. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1503. is_invalid_value);
  1504. EXPECT_EQ(0ull, val);
  1505. EXPECT_TRUE(is_invalid_value);
  1506. }
  1507. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1508. // An all-digit value that overflows size_t must be reported as invalid, not
  1509. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1510. // a large length to a small one on 32-bit builds, leaving the framing length
  1511. // wrong while is_invalid_value stayed false.
  1512. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1513. auto is_invalid_value = false;
  1514. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1515. is_invalid_value);
  1516. EXPECT_TRUE(is_invalid_value);
  1517. // A well-formed length is unaffected.
  1518. Headers ok = {{"Content-Length", "1234"}};
  1519. is_invalid_value = false;
  1520. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1521. is_invalid_value);
  1522. EXPECT_EQ(1234ull, val);
  1523. EXPECT_FALSE(is_invalid_value);
  1524. }
  1525. TEST(GetHeaderValueTest, Range) {
  1526. {
  1527. Headers headers = {make_range_header({{1, -1}})};
  1528. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1529. EXPECT_STREQ("bytes=1-", val);
  1530. }
  1531. {
  1532. Headers headers = {make_range_header({{-1, 1}})};
  1533. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1534. EXPECT_STREQ("bytes=-1", val);
  1535. }
  1536. {
  1537. Headers headers = {make_range_header({{1, 10}})};
  1538. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1539. EXPECT_STREQ("bytes=1-10", val);
  1540. }
  1541. {
  1542. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1543. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1544. EXPECT_STREQ("bytes=1-10, 100-", val);
  1545. }
  1546. {
  1547. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1548. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1549. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1550. }
  1551. {
  1552. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1553. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1554. EXPECT_STREQ("bytes=0-0, -1", val);
  1555. }
  1556. }
  1557. TEST(BearerTokenAuthTest, SchemeValidation) {
  1558. // A value shorter than "Bearer " must not throw from the fixed-length
  1559. // substr, and a non-Bearer scheme must not be reported as a token.
  1560. struct {
  1561. const char *value;
  1562. const char *expected;
  1563. } cases[] = {
  1564. {"x", ""},
  1565. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1566. {"Bearer abc123", "abc123"},
  1567. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1568. };
  1569. for (const auto &c : cases) {
  1570. Request req;
  1571. req.set_header("Authorization", c.value);
  1572. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1573. }
  1574. }
  1575. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1576. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1577. // to depend on the standard library (libstdc++ handed back duplicates in
  1578. // reverse insertion order, libc++ in insertion order).
  1579. Request req;
  1580. req.set_header("Accept-Encoding", "gzip");
  1581. req.set_header("Accept-Encoding", "deflate");
  1582. req.set_header("Accept-Encoding", "br");
  1583. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1584. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1585. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1586. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1587. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1588. }
  1589. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1590. Request req;
  1591. req.set_header("X-Test", "only");
  1592. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1593. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1594. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1595. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1596. }
  1597. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1598. Headers headers;
  1599. headers.emplace("Host", "example.com");
  1600. headers.emplace("Accept-Encoding", "gzip");
  1601. headers.emplace("User-Agent", "test");
  1602. headers.emplace("Accept-Encoding", "deflate");
  1603. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1604. "Accept-Encoding=deflate ",
  1605. entries_to_string(headers));
  1606. }
  1607. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1608. Headers headers = {{"Content-Type", "text/html"},
  1609. {"CONTENT-TYPE", "text/xml"}};
  1610. EXPECT_EQ(2U, headers.count("content-type"));
  1611. auto it = headers.find("content-type");
  1612. ASSERT_TRUE(it != headers.end());
  1613. EXPECT_EQ("text/html", it->second);
  1614. }
  1615. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1616. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1617. // drop only those fields and leave everything positioned between them.
  1618. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1619. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1620. auto rng = headers.equal_range("a");
  1621. headers.erase(rng.first, rng.second);
  1622. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1623. }
  1624. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1625. Headers headers = {
  1626. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1627. EXPECT_EQ(3U, headers.erase("A"));
  1628. EXPECT_EQ(0U, headers.count("A"));
  1629. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1630. }
  1631. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1632. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1633. headers.emplace_front("Host", "example.com");
  1634. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1635. entries_to_string(headers));
  1636. }
  1637. TEST(ParseHeaderValueTest, Range) {
  1638. {
  1639. Ranges ranges;
  1640. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1641. EXPECT_TRUE(ret);
  1642. EXPECT_EQ(1u, ranges.size());
  1643. EXPECT_EQ(1u, ranges[0].first);
  1644. EXPECT_EQ(-1, ranges[0].second);
  1645. }
  1646. {
  1647. Ranges ranges;
  1648. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1649. EXPECT_TRUE(ret);
  1650. EXPECT_EQ(1u, ranges.size());
  1651. EXPECT_EQ(-1, ranges[0].first);
  1652. EXPECT_EQ(1u, ranges[0].second);
  1653. }
  1654. {
  1655. Ranges ranges;
  1656. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1657. EXPECT_TRUE(ret);
  1658. EXPECT_EQ(1u, ranges.size());
  1659. EXPECT_EQ(1u, ranges[0].first);
  1660. EXPECT_EQ(10u, ranges[0].second);
  1661. }
  1662. {
  1663. Ranges ranges;
  1664. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1665. EXPECT_FALSE(ret);
  1666. }
  1667. {
  1668. Ranges ranges;
  1669. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1670. EXPECT_TRUE(ret);
  1671. EXPECT_EQ(2u, ranges.size());
  1672. EXPECT_EQ(1u, ranges[0].first);
  1673. EXPECT_EQ(10u, ranges[0].second);
  1674. EXPECT_EQ(100u, ranges[1].first);
  1675. EXPECT_EQ(-1, ranges[1].second);
  1676. }
  1677. {
  1678. Ranges ranges;
  1679. auto ret =
  1680. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1681. EXPECT_TRUE(ret);
  1682. EXPECT_EQ(3u, ranges.size());
  1683. EXPECT_EQ(1u, ranges[0].first);
  1684. EXPECT_EQ(10u, ranges[0].second);
  1685. EXPECT_EQ(100u, ranges[1].first);
  1686. EXPECT_EQ(200u, ranges[1].second);
  1687. EXPECT_EQ(300u, ranges[2].first);
  1688. EXPECT_EQ(400u, ranges[2].second);
  1689. }
  1690. {
  1691. Ranges ranges;
  1692. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1693. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1694. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1695. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1696. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1697. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1698. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1699. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1700. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1701. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1702. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1703. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1704. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1705. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1706. EXPECT_FALSE(
  1707. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1708. EXPECT_TRUE(ranges.empty());
  1709. }
  1710. {
  1711. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1712. // remainder of the representation, so it stays accepted.
  1713. Ranges ranges;
  1714. auto ret =
  1715. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1716. EXPECT_TRUE(ret);
  1717. ASSERT_EQ(1u, ranges.size());
  1718. EXPECT_EQ(0, ranges[0].first);
  1719. EXPECT_EQ(-1, ranges[0].second);
  1720. }
  1721. }
  1722. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1723. Request req;
  1724. req.set_header("Accept-Encoding", "gzip");
  1725. Response res;
  1726. res.set_header("Content-Type", "text/plain");
  1727. auto ret = detail::encoding_type(req, res);
  1728. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1729. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1730. #else
  1731. EXPECT_TRUE(ret == detail::EncodingType::None);
  1732. #endif
  1733. }
  1734. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1735. Request req;
  1736. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1737. Response res;
  1738. res.set_header("Content-Type", "text/plain");
  1739. auto ret = detail::encoding_type(req, res);
  1740. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1741. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1742. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1743. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1744. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1745. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1746. #else
  1747. EXPECT_TRUE(ret == detail::EncodingType::None);
  1748. #endif
  1749. }
  1750. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1751. Request req;
  1752. req.set_header("Accept-Encoding",
  1753. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1754. Response res;
  1755. res.set_header("Content-Type", "text/plain");
  1756. auto ret = detail::encoding_type(req, res);
  1757. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1758. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1759. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1760. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1761. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1762. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1763. #else
  1764. EXPECT_TRUE(ret == detail::EncodingType::None);
  1765. #endif
  1766. }
  1767. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1768. // All supported encodings rejected with q=0 should return None
  1769. Request req;
  1770. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1771. Response res;
  1772. res.set_header("Content-Type", "text/plain");
  1773. auto ret = detail::encoding_type(req, res);
  1774. EXPECT_TRUE(ret == detail::EncodingType::None);
  1775. }
  1776. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1777. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1778. Request req;
  1779. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1780. Response res;
  1781. res.set_header("Content-Type", "text/plain");
  1782. auto ret = detail::encoding_type(req, res);
  1783. EXPECT_TRUE(ret == detail::EncodingType::None);
  1784. }
  1785. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  1786. Request req;
  1787. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  1788. Response res;
  1789. res.set_header("Content-Type", "text/plain");
  1790. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  1791. }
  1792. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1793. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1794. Request req;
  1795. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1796. Response res;
  1797. res.set_header("Content-Type", "text/plain");
  1798. auto ret = detail::encoding_type(req, res);
  1799. EXPECT_TRUE(ret == detail::EncodingType::None);
  1800. }
  1801. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1802. // RFC 7231: Accept-Encoding values are case-insensitive
  1803. Request req;
  1804. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1805. Response res;
  1806. res.set_header("Content-Type", "text/plain");
  1807. auto ret = detail::encoding_type(req, res);
  1808. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1809. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1810. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1811. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1812. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1813. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1814. #else
  1815. EXPECT_TRUE(ret == detail::EncodingType::None);
  1816. #endif
  1817. }
  1818. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1819. // q value should determine priority, not hardcoded order
  1820. Request req;
  1821. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1822. Response res;
  1823. res.set_header("Content-Type", "text/plain");
  1824. auto ret = detail::encoding_type(req, res);
  1825. // gzip has highest q=1.0, so it should be selected even though
  1826. // br and zstd are also supported
  1827. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1828. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1829. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1830. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1831. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1832. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1833. #else
  1834. EXPECT_TRUE(ret == detail::EncodingType::None);
  1835. #endif
  1836. }
  1837. TEST(BufferStreamTest, read) {
  1838. detail::BufferStream strm1;
  1839. Stream &strm = strm1;
  1840. EXPECT_EQ(5, strm.write("hello"));
  1841. char buf[512];
  1842. EXPECT_EQ(2, strm.read(buf, 2));
  1843. EXPECT_EQ('h', buf[0]);
  1844. EXPECT_EQ('e', buf[1]);
  1845. EXPECT_EQ(2, strm.read(buf, 2));
  1846. EXPECT_EQ('l', buf[0]);
  1847. EXPECT_EQ('l', buf[1]);
  1848. EXPECT_EQ(1, strm.read(buf, 1));
  1849. EXPECT_EQ('o', buf[0]);
  1850. EXPECT_EQ(0, strm.read(buf, 1));
  1851. }
  1852. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1853. auto host = "www.httpwatch.com";
  1854. auto ip = hosted_at(host);
  1855. EXPECT_EQ("23.96.13.243", ip);
  1856. std::vector<std::string> addrs;
  1857. hosted_at(host, addrs);
  1858. EXPECT_EQ(1u, addrs.size());
  1859. }
  1860. #if 0 // It depends on each test environment...
  1861. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1862. auto host = "www.youtube.com";
  1863. std::vector<std::string> addrs;
  1864. hosted_at(host, addrs);
  1865. EXPECT_EQ(20u, addrs.size());
  1866. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1867. EXPECT_TRUE(it != addrs.end());
  1868. }
  1869. #endif
  1870. class ChunkedEncodingTest : public ::testing::Test {
  1871. protected:
  1872. ChunkedEncodingTest()
  1873. : cli_(HOST, PORT)
  1874. #ifdef CPPHTTPLIB_SSL_ENABLED
  1875. ,
  1876. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1877. #endif
  1878. {
  1879. cli_.set_connection_timeout(2);
  1880. #ifdef CPPHTTPLIB_SSL_ENABLED
  1881. cli_.enable_server_certificate_verification(false);
  1882. #endif
  1883. }
  1884. virtual void SetUp() {
  1885. read_file("./image.jpg", image_data_);
  1886. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1887. res.set_content("Hello World!", "text/plain");
  1888. });
  1889. svr_.Get(
  1890. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1891. res.set_chunked_content_provider(
  1892. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1893. size_t remaining = image_data_.size() - offset;
  1894. if (remaining == 0) {
  1895. sink.done();
  1896. } else {
  1897. constexpr size_t CHUNK_SIZE = 1024;
  1898. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1899. sink.write(&image_data_[offset], send_size);
  1900. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1901. }
  1902. return true;
  1903. });
  1904. });
  1905. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1906. svr_.wait_until_ready();
  1907. }
  1908. virtual void TearDown() {
  1909. svr_.stop();
  1910. if (!request_threads_.empty()) {
  1911. std::this_thread::sleep_for(std::chrono::seconds(1));
  1912. for (auto &t : request_threads_) {
  1913. t.join();
  1914. }
  1915. }
  1916. t_.join();
  1917. }
  1918. #ifdef CPPHTTPLIB_SSL_ENABLED
  1919. SSLClient cli_;
  1920. SSLServer svr_;
  1921. #else
  1922. Client cli_;
  1923. Server svr_;
  1924. #endif
  1925. thread t_;
  1926. std::vector<thread> request_threads_;
  1927. std::string image_data_;
  1928. };
  1929. TEST_F(ChunkedEncodingTest, NormalGet) {
  1930. auto res = cli_.Get("/chunked");
  1931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1932. std::string out;
  1933. read_file("./image.jpg", out);
  1934. EXPECT_EQ(StatusCode::OK_200, res->status);
  1935. EXPECT_EQ(out, res->body);
  1936. }
  1937. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1938. std::string body;
  1939. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1940. body.append(data, data_length);
  1941. return true;
  1942. });
  1943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1944. std::string out;
  1945. read_file("./image.jpg", out);
  1946. EXPECT_EQ(StatusCode::OK_200, res->status);
  1947. EXPECT_EQ(out, body);
  1948. }
  1949. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1950. std::string body;
  1951. auto res = cli_.Get(
  1952. "/chunked",
  1953. [&](const Response &response) {
  1954. EXPECT_EQ(StatusCode::OK_200, response.status);
  1955. return true;
  1956. },
  1957. [&](const char *data, size_t data_length) {
  1958. body.append(data, data_length);
  1959. return true;
  1960. });
  1961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1962. std::string out;
  1963. read_file("./image.jpg", out);
  1964. EXPECT_EQ(StatusCode::OK_200, res->status);
  1965. EXPECT_EQ(out, body);
  1966. }
  1967. TEST(RangeTest, FromHTTPBin_Online) {
  1968. auto host = "httpbingo.org";
  1969. auto path = std::string{"/range/32"};
  1970. #ifdef CPPHTTPLIB_SSL_ENABLED
  1971. auto port = 443;
  1972. SSLClient cli(host, port);
  1973. #else
  1974. auto port = 80;
  1975. Client cli(host, port);
  1976. #endif
  1977. cli.set_connection_timeout(5);
  1978. {
  1979. auto res = cli.Get(path);
  1980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1981. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1982. EXPECT_EQ(StatusCode::OK_200, res->status);
  1983. }
  1984. {
  1985. Headers headers = {make_range_header({{1, -1}})};
  1986. auto res = cli.Get(path, headers);
  1987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1988. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1989. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1990. }
  1991. {
  1992. Headers headers = {make_range_header({{1, 10}})};
  1993. auto res = cli.Get(path, headers);
  1994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1995. EXPECT_EQ("bcdefghijk", res->body);
  1996. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1997. }
  1998. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1999. // entire resource, while the original httpbin returned 200. Both are
  2000. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2001. {
  2002. Headers headers = {make_range_header({{0, 31}})};
  2003. auto res = cli.Get(path, headers);
  2004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2005. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2006. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2007. res->status == StatusCode::PartialContent_206);
  2008. }
  2009. {
  2010. Headers headers = {make_range_header({{0, -1}})};
  2011. auto res = cli.Get(path, headers);
  2012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2013. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2014. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2015. res->status == StatusCode::PartialContent_206);
  2016. }
  2017. // go-httpbin returns 206 with clamped range for over-range requests,
  2018. // while the original httpbin returned 416. Both behaviors are observed
  2019. // in real servers, so we only verify the request succeeds.
  2020. {
  2021. Headers headers = {make_range_header({{0, 32}})};
  2022. auto res = cli.Get(path, headers);
  2023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2024. }
  2025. }
  2026. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2027. auto host = "unresolvableaddress.local";
  2028. auto path = std::string{"/"};
  2029. #ifdef CPPHTTPLIB_SSL_ENABLED
  2030. auto port = 443;
  2031. SSLClient cli(host, port);
  2032. #else
  2033. auto port = 80;
  2034. Client cli(host, port);
  2035. #endif
  2036. cli.set_connection_timeout(1);
  2037. {
  2038. auto res = cli.Get(path);
  2039. ASSERT_FALSE(res);
  2040. }
  2041. std::this_thread::sleep_for(std::chrono::seconds(8));
  2042. }
  2043. #if defined(__linux__) && defined(__GLIBC__) && \
  2044. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2045. // Forward declaration: in split builds split.py strips `inline` and moves the
  2046. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2047. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2048. // against the symbol in both header-only and split builds.
  2049. namespace httplib {
  2050. namespace detail {
  2051. int getaddrinfo_with_timeout(const char *node, const char *service,
  2052. const struct addrinfo *hints,
  2053. struct addrinfo **res, time_t timeout_sec);
  2054. } // namespace detail
  2055. } // namespace httplib
  2056. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2057. //
  2058. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2059. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2060. // gai_suspend() call hits the connection timeout the function calls
  2061. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2062. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2063. // still alive and still references the now-destroyed stack frame.
  2064. //
  2065. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2066. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2067. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2068. // and runs them in a container.
  2069. namespace {
  2070. bool should_run_issue_2431_tests() {
  2071. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2072. return v && *v && std::string(v) != "0";
  2073. }
  2074. std::string unique_unresolvable_host(int n) {
  2075. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2076. // glibc still asks the configured nameserver — which is exactly the path
  2077. // we want to exercise. A unique label per call avoids the resolver cache.
  2078. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2079. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2080. std::to_string(n) + ".invalid";
  2081. }
  2082. } // namespace
  2083. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2084. if (!should_run_issue_2431_tests()) {
  2085. GTEST_SKIP()
  2086. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2087. }
  2088. for (int i = 0; i < 8; ++i) {
  2089. struct addrinfo hints;
  2090. memset(&hints, 0, sizeof(hints));
  2091. hints.ai_family = AF_UNSPEC;
  2092. hints.ai_socktype = SOCK_STREAM;
  2093. auto host = unique_unresolvable_host(i);
  2094. struct addrinfo *result = nullptr;
  2095. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2096. &result, /*timeout_sec=*/1);
  2097. if (rc == 0 && result) { freeaddrinfo(result); }
  2098. }
  2099. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2100. // stack region they still believe holds their gaicb.
  2101. std::this_thread::sleep_for(std::chrono::seconds(3));
  2102. }
  2103. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2104. if (!should_run_issue_2431_tests()) {
  2105. GTEST_SKIP()
  2106. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2107. }
  2108. std::atomic<bool> stop{false};
  2109. std::vector<std::thread> threads;
  2110. for (int t = 0; t < 8; ++t) {
  2111. threads.emplace_back([t, &stop] {
  2112. int i = 0;
  2113. while (!stop.load(std::memory_order_relaxed)) {
  2114. struct addrinfo hints;
  2115. memset(&hints, 0, sizeof(hints));
  2116. hints.ai_family = AF_UNSPEC;
  2117. hints.ai_socktype = SOCK_STREAM;
  2118. auto host = unique_unresolvable_host(t * 100000 + i++);
  2119. struct addrinfo *result = nullptr;
  2120. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2121. &result, /*timeout_sec=*/1);
  2122. if (rc == 0 && result) { freeaddrinfo(result); }
  2123. }
  2124. });
  2125. }
  2126. std::this_thread::sleep_for(std::chrono::seconds(8));
  2127. stop.store(true, std::memory_order_relaxed);
  2128. for (auto &th : threads) {
  2129. th.join();
  2130. }
  2131. std::this_thread::sleep_for(std::chrono::seconds(3));
  2132. }
  2133. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2134. if (!should_run_issue_2431_tests()) {
  2135. GTEST_SKIP()
  2136. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2137. }
  2138. std::atomic<bool> stop{false};
  2139. std::vector<std::thread> threads;
  2140. for (int t = 0; t < 8; ++t) {
  2141. threads.emplace_back([t, &stop] {
  2142. int i = 0;
  2143. while (!stop.load(std::memory_order_relaxed)) {
  2144. auto host = unique_unresolvable_host(t * 100000 + i++);
  2145. Client cli(host, 80);
  2146. cli.set_connection_timeout(1, 0);
  2147. cli.set_read_timeout(1, 0);
  2148. cli.set_write_timeout(1, 0);
  2149. (void)cli.Get("/");
  2150. }
  2151. });
  2152. }
  2153. std::this_thread::sleep_for(std::chrono::seconds(8));
  2154. stop.store(true, std::memory_order_relaxed);
  2155. for (auto &th : threads) {
  2156. th.join();
  2157. }
  2158. std::this_thread::sleep_for(std::chrono::seconds(3));
  2159. }
  2160. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2161. TEST(ConnectionErrorTest, InvalidHost) {
  2162. auto host = "-abcde.com";
  2163. #ifdef CPPHTTPLIB_SSL_ENABLED
  2164. auto port = 443;
  2165. SSLClient cli(host, port);
  2166. #else
  2167. auto port = 80;
  2168. Client cli(host, port);
  2169. #endif
  2170. cli.set_connection_timeout(std::chrono::seconds(2));
  2171. auto res = cli.Get("/");
  2172. ASSERT_TRUE(!res);
  2173. EXPECT_EQ(Error::Connection, res.error());
  2174. }
  2175. TEST(ConnectionErrorTest, InvalidHost2) {
  2176. auto host = "httpcan.org/";
  2177. #ifdef CPPHTTPLIB_SSL_ENABLED
  2178. SSLClient cli(host);
  2179. #else
  2180. Client cli(host);
  2181. #endif
  2182. cli.set_connection_timeout(std::chrono::seconds(2));
  2183. auto res = cli.Get("/");
  2184. ASSERT_TRUE(!res);
  2185. EXPECT_EQ(Error::Connection, res.error());
  2186. }
  2187. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2188. auto host = "httpcan.org/";
  2189. #ifdef CPPHTTPLIB_SSL_ENABLED
  2190. SSLClient cli(host);
  2191. #else
  2192. Client cli(host);
  2193. #endif
  2194. cli.set_connection_timeout(std::chrono::seconds(2));
  2195. auto res = cli.Get("/");
  2196. ASSERT_TRUE(!res);
  2197. stringstream s;
  2198. s << "error code: " << res.error();
  2199. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2200. }
  2201. TEST(ConnectionErrorTest, InvalidPort) {
  2202. auto host = "localhost";
  2203. auto port = 44380;
  2204. #ifdef CPPHTTPLIB_SSL_ENABLED
  2205. SSLClient cli(host, port);
  2206. #else
  2207. Client cli(host, port);
  2208. #endif
  2209. cli.set_connection_timeout(std::chrono::seconds(2));
  2210. auto res = cli.Get("/");
  2211. ASSERT_TRUE(!res);
  2212. EXPECT_TRUE(Error::Connection == res.error() ||
  2213. Error::ConnectionTimeout == res.error());
  2214. }
  2215. TEST(ConnectionErrorTest, Timeout_Online) {
  2216. auto host = "google.com";
  2217. #ifdef CPPHTTPLIB_SSL_ENABLED
  2218. auto port = 44380;
  2219. SSLClient cli(host, port);
  2220. #else
  2221. auto port = 8080;
  2222. Client cli(host, port);
  2223. #endif
  2224. cli.set_connection_timeout(std::chrono::seconds(2));
  2225. // only probe one address type so that the error reason
  2226. // correlates to the timed-out IPv4, not the unsupported
  2227. // IPv6 connection attempt
  2228. cli.set_address_family(AF_INET);
  2229. auto res = cli.Get("/");
  2230. ASSERT_TRUE(!res);
  2231. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2232. }
  2233. TEST(CancelTest, NoCancel_Online) {
  2234. auto host = "httpbingo.org";
  2235. auto path = std::string{"/range/32"};
  2236. #ifdef CPPHTTPLIB_SSL_ENABLED
  2237. auto port = 443;
  2238. SSLClient cli(host, port);
  2239. #else
  2240. auto port = 80;
  2241. Client cli(host, port);
  2242. #endif
  2243. cli.set_connection_timeout(std::chrono::seconds(5));
  2244. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2246. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2247. EXPECT_EQ(StatusCode::OK_200, res->status);
  2248. }
  2249. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2250. // Use /bytes with a large payload so that the DownloadProgress callback
  2251. // (which only fires for Content-Length responses) is invoked before the
  2252. // entire body is received, giving cancellation a chance to fire.
  2253. auto host = "httpbingo.org";
  2254. auto path = std::string{"/bytes/524288"};
  2255. #ifdef CPPHTTPLIB_SSL_ENABLED
  2256. auto port = 443;
  2257. SSLClient cli(host, port);
  2258. #else
  2259. auto port = 80;
  2260. Client cli(host, port);
  2261. #endif
  2262. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2263. cli.set_connection_timeout(std::chrono::seconds(5));
  2264. ASSERT_TRUE(!res);
  2265. EXPECT_EQ(Error::Canceled, res.error());
  2266. }
  2267. TEST(CancelTest, WithCancelLargePayload_Online) {
  2268. auto host = "httpbingo.org";
  2269. auto path = std::string{"/bytes/524288"};
  2270. #ifdef CPPHTTPLIB_SSL_ENABLED
  2271. auto port = 443;
  2272. SSLClient cli(host, port);
  2273. #else
  2274. auto port = 80;
  2275. Client cli(host, port);
  2276. #endif
  2277. cli.set_connection_timeout(std::chrono::seconds(5));
  2278. uint32_t count = 0;
  2279. auto res =
  2280. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2281. ASSERT_TRUE(!res);
  2282. EXPECT_EQ(Error::Canceled, res.error());
  2283. }
  2284. TEST(CancelTest, NoCancelPost) {
  2285. Server svr;
  2286. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2287. res.set_content("Hello World!", "text/plain");
  2288. });
  2289. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2290. auto se = detail::scope_exit([&] {
  2291. svr.stop();
  2292. thread.join();
  2293. ASSERT_FALSE(svr.is_running());
  2294. });
  2295. svr.wait_until_ready();
  2296. Client cli(HOST, PORT);
  2297. cli.set_connection_timeout(std::chrono::seconds(5));
  2298. auto res =
  2299. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2300. "application/json", [](uint64_t, uint64_t) { return true; });
  2301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2302. EXPECT_EQ("Hello World!", res->body);
  2303. EXPECT_EQ(StatusCode::OK_200, res->status);
  2304. }
  2305. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2306. Server svr;
  2307. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2308. res.set_content("Hello World!", "text/plain");
  2309. });
  2310. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2311. auto se = detail::scope_exit([&] {
  2312. svr.stop();
  2313. thread.join();
  2314. ASSERT_FALSE(svr.is_running());
  2315. });
  2316. svr.wait_until_ready();
  2317. Client cli(HOST, PORT);
  2318. cli.set_connection_timeout(std::chrono::seconds(5));
  2319. auto res =
  2320. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2321. "application/json", [](uint64_t, uint64_t) { return false; });
  2322. ASSERT_TRUE(!res);
  2323. EXPECT_EQ(Error::Canceled, res.error());
  2324. }
  2325. TEST(CancelTest, WithCancelLargePayloadPost) {
  2326. Server svr;
  2327. svr.set_payload_max_length(200 * 1024 * 1024);
  2328. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2329. res.set_content(LARGE_DATA, "text/plain");
  2330. });
  2331. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2332. auto se = detail::scope_exit([&] {
  2333. svr.stop();
  2334. thread.join();
  2335. ASSERT_FALSE(svr.is_running());
  2336. });
  2337. svr.wait_until_ready();
  2338. Client cli(HOST, PORT);
  2339. cli.set_payload_max_length(200 * 1024 * 1024);
  2340. cli.set_connection_timeout(std::chrono::seconds(5));
  2341. auto res =
  2342. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2343. "application/json", [](uint64_t, uint64_t) { return false; });
  2344. ASSERT_TRUE(!res);
  2345. EXPECT_EQ(Error::Canceled, res.error());
  2346. }
  2347. TEST(CancelTest, NoCancelPut) {
  2348. Server svr;
  2349. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2350. res.set_content("Hello World!", "text/plain");
  2351. });
  2352. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2353. auto se = detail::scope_exit([&] {
  2354. svr.stop();
  2355. thread.join();
  2356. ASSERT_FALSE(svr.is_running());
  2357. });
  2358. svr.wait_until_ready();
  2359. Client cli(HOST, PORT);
  2360. cli.set_connection_timeout(std::chrono::seconds(5));
  2361. auto res =
  2362. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2363. "application/json", [](uint64_t, uint64_t) { return true; });
  2364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2365. EXPECT_EQ("Hello World!", res->body);
  2366. EXPECT_EQ(StatusCode::OK_200, res->status);
  2367. }
  2368. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2369. Server svr;
  2370. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2371. res.set_content("Hello World!", "text/plain");
  2372. });
  2373. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2374. auto se = detail::scope_exit([&] {
  2375. svr.stop();
  2376. thread.join();
  2377. ASSERT_FALSE(svr.is_running());
  2378. });
  2379. svr.wait_until_ready();
  2380. Client cli(HOST, PORT);
  2381. cli.set_connection_timeout(std::chrono::seconds(5));
  2382. auto res =
  2383. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2384. "application/json", [](uint64_t, uint64_t) { return false; });
  2385. ASSERT_TRUE(!res);
  2386. EXPECT_EQ(Error::Canceled, res.error());
  2387. }
  2388. TEST(CancelTest, WithCancelLargePayloadPut) {
  2389. Server svr;
  2390. svr.set_payload_max_length(200 * 1024 * 1024);
  2391. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2392. res.set_content(LARGE_DATA, "text/plain");
  2393. });
  2394. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2395. auto se = detail::scope_exit([&] {
  2396. svr.stop();
  2397. thread.join();
  2398. ASSERT_FALSE(svr.is_running());
  2399. });
  2400. svr.wait_until_ready();
  2401. Client cli(HOST, PORT);
  2402. cli.set_payload_max_length(200 * 1024 * 1024);
  2403. cli.set_connection_timeout(std::chrono::seconds(5));
  2404. auto res =
  2405. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2406. "application/json", [](uint64_t, uint64_t) { return false; });
  2407. ASSERT_TRUE(!res);
  2408. EXPECT_EQ(Error::Canceled, res.error());
  2409. }
  2410. TEST(CancelTest, NoCancelPatch) {
  2411. Server svr;
  2412. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2413. res.set_content("Hello World!", "text/plain");
  2414. });
  2415. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2416. auto se = detail::scope_exit([&] {
  2417. svr.stop();
  2418. thread.join();
  2419. ASSERT_FALSE(svr.is_running());
  2420. });
  2421. svr.wait_until_ready();
  2422. Client cli(HOST, PORT);
  2423. cli.set_connection_timeout(std::chrono::seconds(5));
  2424. auto res =
  2425. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2426. "application/json", [](uint64_t, uint64_t) { return true; });
  2427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2428. EXPECT_EQ("Hello World!", res->body);
  2429. EXPECT_EQ(StatusCode::OK_200, res->status);
  2430. }
  2431. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2432. Server svr;
  2433. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2434. res.set_content("Hello World!", "text/plain");
  2435. });
  2436. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2437. auto se = detail::scope_exit([&] {
  2438. svr.stop();
  2439. thread.join();
  2440. ASSERT_FALSE(svr.is_running());
  2441. });
  2442. svr.wait_until_ready();
  2443. Client cli(HOST, PORT);
  2444. cli.set_connection_timeout(std::chrono::seconds(5));
  2445. auto res =
  2446. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2447. "application/json", [](uint64_t, uint64_t) { return false; });
  2448. ASSERT_TRUE(!res);
  2449. EXPECT_EQ(Error::Canceled, res.error());
  2450. }
  2451. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2452. Server svr;
  2453. svr.set_payload_max_length(200 * 1024 * 1024);
  2454. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2455. res.set_content(LARGE_DATA, "text/plain");
  2456. });
  2457. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2458. auto se = detail::scope_exit([&] {
  2459. svr.stop();
  2460. thread.join();
  2461. ASSERT_FALSE(svr.is_running());
  2462. });
  2463. svr.wait_until_ready();
  2464. Client cli(HOST, PORT);
  2465. cli.set_payload_max_length(200 * 1024 * 1024);
  2466. cli.set_connection_timeout(std::chrono::seconds(5));
  2467. auto res =
  2468. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2469. "application/json", [](uint64_t, uint64_t) { return false; });
  2470. ASSERT_TRUE(!res);
  2471. EXPECT_EQ(Error::Canceled, res.error());
  2472. }
  2473. TEST(CancelTest, NoCancelDelete) {
  2474. Server svr;
  2475. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2476. res.set_content("Hello World!", "text/plain");
  2477. });
  2478. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2479. auto se = detail::scope_exit([&] {
  2480. svr.stop();
  2481. thread.join();
  2482. ASSERT_FALSE(svr.is_running());
  2483. });
  2484. svr.wait_until_ready();
  2485. Client cli(HOST, PORT);
  2486. cli.set_connection_timeout(std::chrono::seconds(5));
  2487. auto res =
  2488. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2489. "application/json", [](uint64_t, uint64_t) { return true; });
  2490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2491. EXPECT_EQ("Hello World!", res->body);
  2492. EXPECT_EQ(StatusCode::OK_200, res->status);
  2493. }
  2494. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2495. Server svr;
  2496. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2497. res.set_content("Hello World!", "text/plain");
  2498. });
  2499. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2500. auto se = detail::scope_exit([&] {
  2501. svr.stop();
  2502. thread.join();
  2503. ASSERT_FALSE(svr.is_running());
  2504. });
  2505. svr.wait_until_ready();
  2506. Client cli(HOST, PORT);
  2507. cli.set_connection_timeout(std::chrono::seconds(5));
  2508. auto res =
  2509. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2510. "application/json", [](uint64_t, uint64_t) { return false; });
  2511. ASSERT_TRUE(!res);
  2512. EXPECT_EQ(Error::Canceled, res.error());
  2513. }
  2514. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2515. Server svr;
  2516. svr.set_payload_max_length(200 * 1024 * 1024);
  2517. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2518. res.set_content(LARGE_DATA, "text/plain");
  2519. });
  2520. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2521. auto se = detail::scope_exit([&] {
  2522. svr.stop();
  2523. thread.join();
  2524. ASSERT_FALSE(svr.is_running());
  2525. });
  2526. svr.wait_until_ready();
  2527. Client cli(HOST, PORT);
  2528. cli.set_payload_max_length(200 * 1024 * 1024);
  2529. cli.set_connection_timeout(std::chrono::seconds(5));
  2530. auto res =
  2531. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2532. "application/json", [](uint64_t, uint64_t) { return false; });
  2533. ASSERT_TRUE(!res);
  2534. EXPECT_EQ(Error::Canceled, res.error());
  2535. }
  2536. static std::string remove_whitespace(const std::string &input) {
  2537. std::string output;
  2538. output.reserve(input.size());
  2539. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2540. [](unsigned char c) { return !std::isspace(c); });
  2541. return output;
  2542. }
  2543. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2544. auto host = "httpbingo.org";
  2545. auto path = std::string{"/basic-auth/hello/world"};
  2546. #ifdef CPPHTTPLIB_SSL_ENABLED
  2547. auto port = 443;
  2548. SSLClient cli(host, port);
  2549. #else
  2550. auto port = 80;
  2551. Client cli(host, port);
  2552. #endif
  2553. {
  2554. auto res = cli.Get(path);
  2555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2556. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2557. }
  2558. {
  2559. auto res = cli.Get(
  2560. path, Headers{make_basic_authentication_header("hello", "world")});
  2561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2562. auto body = remove_whitespace(res->body);
  2563. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2564. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2565. EXPECT_EQ(StatusCode::OK_200, res->status);
  2566. }
  2567. {
  2568. cli.set_basic_auth("hello", "world");
  2569. auto res = cli.Get(path);
  2570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2571. auto body = remove_whitespace(res->body);
  2572. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2573. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2574. EXPECT_EQ(StatusCode::OK_200, res->status);
  2575. }
  2576. {
  2577. cli.set_basic_auth("hello", "bad");
  2578. auto res = cli.Get(path);
  2579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2580. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2581. }
  2582. {
  2583. cli.set_basic_auth("bad", "world");
  2584. auto res = cli.Get(path);
  2585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2586. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2587. }
  2588. }
  2589. #ifdef CPPHTTPLIB_SSL_ENABLED
  2590. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2591. auto host = "httpbingo.org";
  2592. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2593. auto paths = std::vector<std::string>{
  2594. "/digest-auth/auth/hello/world/MD5",
  2595. "/digest-auth/auth/hello/world/SHA-256",
  2596. };
  2597. auto port = 443;
  2598. SSLClient cli(host, port);
  2599. {
  2600. auto res = cli.Get(unauth_path);
  2601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2602. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2603. }
  2604. {
  2605. cli.set_digest_auth("hello", "world");
  2606. for (const auto &path : paths) {
  2607. auto res = cli.Get(path.c_str());
  2608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2609. auto body = remove_whitespace(res->body);
  2610. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2611. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2612. EXPECT_EQ(StatusCode::OK_200, res->status);
  2613. }
  2614. cli.set_digest_auth("hello", "bad");
  2615. for (const auto &path : paths) {
  2616. auto res = cli.Get(path.c_str());
  2617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2618. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2619. }
  2620. }
  2621. }
  2622. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2623. // comma-separated list of challenges, and each challenge may itself carry a
  2624. // comma-separated auth-param list, so a server can legally offer Basic
  2625. // before Digest, either as two field lines or packed into one. Runs one 401
  2626. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2627. // value() joins them in receipt order) and checks that the retry carries a
  2628. // well-formed Digest Authorization header naming expected_realm.
  2629. static void
  2630. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2631. const std::string &expected_realm) {
  2632. std::atomic<int> hits{0};
  2633. Server svr;
  2634. svr.Get("/x", [&](const Request &req, Response &res) {
  2635. if (++hits == 1) {
  2636. res.status = StatusCode::Unauthorized_401;
  2637. for (const auto &challenge : challenges) {
  2638. res.set_header("WWW-Authenticate", challenge);
  2639. }
  2640. } else {
  2641. auto authorization = req.get_header_value("Authorization");
  2642. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2643. EXPECT_NE(std::string::npos,
  2644. authorization.find("realm=\"" + expected_realm + "\""));
  2645. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2646. res.set_content("ok", "text/plain");
  2647. }
  2648. });
  2649. auto port = svr.bind_to_any_port(HOST);
  2650. std::thread t([&]() { svr.listen_after_bind(); });
  2651. auto se = detail::scope_exit([&] {
  2652. svr.stop();
  2653. t.join();
  2654. });
  2655. svr.wait_until_ready();
  2656. Client cli(HOST, port);
  2657. cli.set_digest_auth("hello", "world");
  2658. auto res = cli.Get("/x");
  2659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2660. EXPECT_EQ(2, hits.load());
  2661. }
  2662. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2663. static const char *kDigestChallenge =
  2664. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2665. "algorithm=MD5";
  2666. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2667. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2668. "testrealm");
  2669. }
  2670. // Same challenge list with the schemes in the opposite order, to make sure
  2671. // the fix above didn't just special-case "Basic first".
  2672. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2673. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2674. "testrealm");
  2675. }
  2676. // A comma inside a quoted auth-param value must not be mistaken for the
  2677. // separator between two challenges (or two auth-params).
  2678. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2679. run_digest_challenge_list_test(
  2680. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2681. "algorithm=MD5"},
  2682. "test,realm");
  2683. }
  2684. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2685. // make_digest_authentication_header() dereferences both unconditionally, so
  2686. // a server sending a challenge missing either one must not be treated as
  2687. // usable -- doing so used to crash the client with std::out_of_range.
  2688. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2689. Server svr;
  2690. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2691. res.status = StatusCode::Unauthorized_401;
  2692. res.set_header("WWW-Authenticate", challenge);
  2693. });
  2694. auto port = svr.bind_to_any_port(HOST);
  2695. std::thread t([&]() { svr.listen_after_bind(); });
  2696. auto se = detail::scope_exit([&] {
  2697. svr.stop();
  2698. t.join();
  2699. });
  2700. svr.wait_until_ready();
  2701. Client cli(HOST, port);
  2702. cli.set_digest_auth("hello", "world");
  2703. auto res = cli.Get("/x");
  2704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2705. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2706. }
  2707. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2708. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2709. }
  2710. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2711. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2712. }
  2713. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2714. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2715. }
  2716. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2717. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2718. // when storing the values, so the header builder has to re-escape them (and
  2719. // keep algorithm a bare token); otherwise the value breaks out of its
  2720. // quoted-string and injects extra auth-params into the client's Authorization.
  2721. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2722. std::atomic<int> hits{0};
  2723. std::string authorization;
  2724. Server svr;
  2725. svr.Get("/x", [&](const Request &req, Response &res) {
  2726. if (++hits == 1) {
  2727. res.status = StatusCode::Unauthorized_401;
  2728. // On the wire the quotes embedded in the values are backslash-escaped.
  2729. res.set_header("WWW-Authenticate",
  2730. "Digest realm=\"testrealm\", "
  2731. "nonce=\"n\\\"; injected=\\\"x\", "
  2732. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2733. } else {
  2734. authorization = req.get_header_value("Authorization");
  2735. res.set_content("ok", "text/plain");
  2736. }
  2737. });
  2738. auto port = svr.bind_to_any_port(HOST);
  2739. std::thread t([&]() { svr.listen_after_bind(); });
  2740. auto se = detail::scope_exit([&] {
  2741. svr.stop();
  2742. t.join();
  2743. });
  2744. svr.wait_until_ready();
  2745. Client cli(HOST, port);
  2746. cli.set_digest_auth("hello", "world");
  2747. auto res = cli.Get("/x");
  2748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2749. EXPECT_EQ(2, hits.load());
  2750. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2751. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  2752. // inside its quoted-string rather than starting an "injected" auth-param.
  2753. EXPECT_NE(std::string::npos,
  2754. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  2755. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  2756. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  2757. }
  2758. #endif
  2759. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2760. auto host = "google.com";
  2761. auto another_host = "example.com";
  2762. auto wrong_ip = "0.0.0.0";
  2763. #ifdef CPPHTTPLIB_SSL_ENABLED
  2764. SSLClient cli(host);
  2765. #else
  2766. Client cli(host);
  2767. #endif
  2768. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2769. auto res = cli.Get("/");
  2770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2771. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2772. }
  2773. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2774. auto host = "google.com";
  2775. auto wrong_ip = "0.0.0.0";
  2776. #ifdef CPPHTTPLIB_SSL_ENABLED
  2777. SSLClient cli(host);
  2778. #else
  2779. Client cli(host);
  2780. #endif
  2781. cli.set_hostname_addr_map({{host, wrong_ip}});
  2782. auto res = cli.Get("/");
  2783. ASSERT_TRUE(!res);
  2784. EXPECT_EQ(Error::Connection, res.error());
  2785. }
  2786. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2787. // A mapped value that is not an IP literal must be resolved. "localhost"
  2788. // resolves from the hosts file, so this test needs no external DNS.
  2789. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2790. auto host = "target.invalid";
  2791. Server svr;
  2792. std::string received_host;
  2793. svr.Get("/hi", [&](const Request &req, Response &res) {
  2794. received_host = req.get_header_value("Host");
  2795. res.set_content("Hello World!", "text/plain");
  2796. });
  2797. auto port = svr.bind_to_any_port(HOST);
  2798. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2799. auto se = detail::scope_exit([&] {
  2800. svr.stop();
  2801. thread.join();
  2802. ASSERT_FALSE(svr.is_running());
  2803. });
  2804. svr.wait_until_ready();
  2805. Client cli(host, port);
  2806. cli.set_hostname_addr_map({{host, HOST}});
  2807. auto res = cli.Get("/hi");
  2808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2809. EXPECT_EQ(StatusCode::OK_200, res->status);
  2810. // The mapping only redirects the connection; the identity stays host_.
  2811. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2812. }
  2813. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2814. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2815. auto host = "target.invalid";
  2816. Server svr;
  2817. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2818. res.set_content("Hello World!", "text/plain");
  2819. });
  2820. auto port = svr.bind_to_any_port("127.0.0.1");
  2821. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2822. auto se = detail::scope_exit([&] {
  2823. svr.stop();
  2824. thread.join();
  2825. ASSERT_FALSE(svr.is_running());
  2826. });
  2827. svr.wait_until_ready();
  2828. Client cli(host, port);
  2829. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2830. auto res = cli.Get("/hi");
  2831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2832. EXPECT_EQ(StatusCode::OK_200, res->status);
  2833. }
  2834. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2835. // An empty mapped value must leave host_ as the connection target. Without
  2836. // that guard the empty value would become the host argument, getaddrinfo
  2837. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2838. // loopback - silently connecting somewhere the caller never asked for.
  2839. // The server listens on loopback, so such a fallback would succeed and is
  2840. // therefore observable as a failure of this test.
  2841. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2842. Server svr;
  2843. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2844. res.set_content("Hello World!", "text/plain");
  2845. });
  2846. auto port = svr.bind_to_any_port(HOST);
  2847. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2848. auto se = detail::scope_exit([&] {
  2849. svr.stop();
  2850. thread.join();
  2851. ASSERT_FALSE(svr.is_running());
  2852. });
  2853. svr.wait_until_ready();
  2854. Client cli(blackhole, port);
  2855. cli.set_hostname_addr_map({{blackhole, ""}});
  2856. cli.set_connection_timeout(1);
  2857. auto res = cli.Get("/hi");
  2858. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2859. }
  2860. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2861. auto host = "httpbingo.org";
  2862. auto path = std::string{"/absolute-redirect/3"};
  2863. #ifdef CPPHTTPLIB_SSL_ENABLED
  2864. SSLClient cli(host);
  2865. #else
  2866. Client cli(host);
  2867. #endif
  2868. cli.set_follow_location(true);
  2869. auto res = cli.Get(path);
  2870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2871. EXPECT_EQ(StatusCode::OK_200, res->status);
  2872. }
  2873. TEST(RedirectTest, Redirect_Online) {
  2874. auto host = "httpbingo.org";
  2875. auto path = std::string{"/redirect/3"};
  2876. #ifdef CPPHTTPLIB_SSL_ENABLED
  2877. SSLClient cli(host);
  2878. #else
  2879. Client cli(host);
  2880. #endif
  2881. cli.set_follow_location(true);
  2882. auto res = cli.Get(path);
  2883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2884. EXPECT_EQ(StatusCode::OK_200, res->status);
  2885. }
  2886. TEST(RelativeRedirectTest, Redirect_Online) {
  2887. auto host = "httpbingo.org";
  2888. auto path = std::string{"/relative-redirect/3"};
  2889. #ifdef CPPHTTPLIB_SSL_ENABLED
  2890. SSLClient cli(host);
  2891. #else
  2892. Client cli(host);
  2893. #endif
  2894. cli.set_follow_location(true);
  2895. auto res = cli.Get(path);
  2896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2897. EXPECT_EQ(StatusCode::OK_200, res->status);
  2898. }
  2899. TEST(TooManyRedirectTest, Redirect_Online) {
  2900. auto host = "httpbingo.org";
  2901. auto path = std::string{"/redirect/21"};
  2902. #ifdef CPPHTTPLIB_SSL_ENABLED
  2903. SSLClient cli(host);
  2904. #else
  2905. Client cli(host);
  2906. #endif
  2907. cli.set_follow_location(true);
  2908. auto res = cli.Get(path);
  2909. ASSERT_TRUE(!res);
  2910. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2911. }
  2912. #ifdef CPPHTTPLIB_SSL_ENABLED
  2913. TEST(YahooRedirectTest, Redirect_Online) {
  2914. Client cli("yahoo.com");
  2915. auto res = cli.Get("/");
  2916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2917. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2918. cli.set_follow_location(true);
  2919. res = cli.Get("/");
  2920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2921. EXPECT_EQ(StatusCode::OK_200, res->status);
  2922. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2923. }
  2924. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2925. #define REDIR_HOST "httpbingo.org"
  2926. #define REDIR_PATH "/redirect-to"
  2927. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2928. SSLClient cli(REDIR_HOST);
  2929. cli.set_follow_location(true);
  2930. auto res =
  2931. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2933. EXPECT_EQ(StatusCode::OK_200, res->status);
  2934. }
  2935. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2936. SSLClient cli(REDIR_HOST);
  2937. cli.set_follow_location(true);
  2938. Params params;
  2939. params.emplace("url", "http://example.com");
  2940. params.emplace("status_code", "302");
  2941. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2943. EXPECT_EQ(StatusCode::OK_200, res->status);
  2944. }
  2945. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2946. SSLClient cli(REDIR_HOST);
  2947. cli.set_follow_location(true);
  2948. Params params;
  2949. params.emplace("url", "http://example.com");
  2950. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2952. EXPECT_EQ(StatusCode::OK_200, res->status);
  2953. }
  2954. TEST(UrlWithSpace, Redirect_Online) {
  2955. SSLClient cli("edge.forgecdn.net");
  2956. cli.set_follow_location(true);
  2957. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2959. EXPECT_EQ(StatusCode::OK_200, res->status);
  2960. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2961. }
  2962. #endif
  2963. #if !defined(_WIN32) && !defined(_WIN64)
  2964. TEST(ReceiveSignals, Signal) {
  2965. auto setupSignalHandlers = []() {
  2966. struct sigaction act;
  2967. sigemptyset(&act.sa_mask);
  2968. act.sa_flags = SA_SIGINFO;
  2969. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2970. switch (sig) {
  2971. case SIGINT:
  2972. default: break;
  2973. }
  2974. };
  2975. ::sigaction(SIGINT, &act, nullptr);
  2976. };
  2977. Server svr;
  2978. int port = 0;
  2979. auto thread = std::thread([&]() {
  2980. setupSignalHandlers();
  2981. port = svr.bind_to_any_port(HOST);
  2982. svr.listen_after_bind();
  2983. });
  2984. auto se = detail::scope_exit([&] {
  2985. svr.stop();
  2986. thread.join();
  2987. ASSERT_FALSE(svr.is_running());
  2988. });
  2989. svr.wait_until_ready();
  2990. ASSERT_TRUE(svr.is_running());
  2991. pthread_kill(thread.native_handle(), SIGINT);
  2992. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2993. ASSERT_TRUE(svr.is_running());
  2994. }
  2995. #endif
  2996. TEST(RedirectToDifferentPort, Redirect) {
  2997. Server svr1;
  2998. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2999. res.set_content("Hello World!", "text/plain");
  3000. });
  3001. int svr1_port = 0;
  3002. auto thread1 = std::thread([&]() {
  3003. svr1_port = svr1.bind_to_any_port(HOST);
  3004. svr1.listen_after_bind();
  3005. });
  3006. Server svr2;
  3007. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3008. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3009. });
  3010. int svr2_port = 0;
  3011. auto thread2 = std::thread([&]() {
  3012. svr2_port = svr2.bind_to_any_port(HOST);
  3013. svr2.listen_after_bind();
  3014. });
  3015. auto se = detail::scope_exit([&] {
  3016. svr2.stop();
  3017. thread2.join();
  3018. svr1.stop();
  3019. thread1.join();
  3020. ASSERT_FALSE(svr2.is_running());
  3021. ASSERT_FALSE(svr1.is_running());
  3022. });
  3023. svr1.wait_until_ready();
  3024. svr2.wait_until_ready();
  3025. Client cli("localhost", svr2_port);
  3026. cli.set_follow_location(true);
  3027. auto res = cli.Get("/2");
  3028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3029. EXPECT_EQ(StatusCode::OK_200, res->status);
  3030. EXPECT_EQ("Hello World!", res->body);
  3031. }
  3032. static void
  3033. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3034. Server svr1;
  3035. std::string captured_authorization;
  3036. svr1.Get("/target", [&](const Request &req, Response &res) {
  3037. captured_authorization = req.get_header_value("Authorization");
  3038. res.set_content("OK", "text/plain");
  3039. });
  3040. int svr1_port = 0;
  3041. auto thread1 = std::thread([&]() {
  3042. svr1_port = svr1.bind_to_any_port(HOST);
  3043. svr1.listen_after_bind();
  3044. });
  3045. Server svr2;
  3046. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3047. res.set_redirect(
  3048. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3049. });
  3050. int svr2_port = 0;
  3051. auto thread2 = std::thread([&]() {
  3052. svr2_port = svr2.bind_to_any_port(HOST);
  3053. svr2.listen_after_bind();
  3054. });
  3055. auto se = detail::scope_exit([&] {
  3056. svr2.stop();
  3057. thread2.join();
  3058. svr1.stop();
  3059. thread1.join();
  3060. ASSERT_FALSE(svr2.is_running());
  3061. ASSERT_FALSE(svr1.is_running());
  3062. });
  3063. svr1.wait_until_ready();
  3064. svr2.wait_until_ready();
  3065. Client cli("localhost", svr2_port);
  3066. cli.set_follow_location(true);
  3067. set_auth(cli);
  3068. auto res = cli.Get("/redir");
  3069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3070. EXPECT_EQ(StatusCode::OK_200, res->status);
  3071. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3072. EXPECT_TRUE(captured_authorization.empty());
  3073. }
  3074. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3075. TestDoNotForwardCredentialsOnRedirect(
  3076. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3077. }
  3078. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3079. TestDoNotForwardCredentialsOnRedirect(
  3080. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3081. }
  3082. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3083. Server svr1;
  3084. std::string captured_cookie;
  3085. bool target_hit = false;
  3086. svr1.Get("/target", [&](const Request &req, Response &res) {
  3087. captured_cookie = req.get_header_value("Cookie");
  3088. target_hit = true;
  3089. res.set_content("OK", "text/plain");
  3090. });
  3091. int svr1_port = 0;
  3092. auto thread1 = std::thread([&]() {
  3093. svr1_port = svr1.bind_to_any_port(HOST);
  3094. svr1.listen_after_bind();
  3095. });
  3096. Server svr2;
  3097. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3098. res.set_redirect(
  3099. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3100. });
  3101. int svr2_port = 0;
  3102. auto thread2 = std::thread([&]() {
  3103. svr2_port = svr2.bind_to_any_port(HOST);
  3104. svr2.listen_after_bind();
  3105. });
  3106. auto se = detail::scope_exit([&] {
  3107. svr2.stop();
  3108. thread2.join();
  3109. svr1.stop();
  3110. thread1.join();
  3111. ASSERT_FALSE(svr2.is_running());
  3112. ASSERT_FALSE(svr1.is_running());
  3113. });
  3114. svr1.wait_until_ready();
  3115. svr2.wait_until_ready();
  3116. Client cli("localhost", svr2_port);
  3117. cli.set_follow_location(true);
  3118. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  3119. auto res = cli.Get("/redir", headers);
  3120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3121. EXPECT_EQ(StatusCode::OK_200, res->status);
  3122. EXPECT_TRUE(target_hit);
  3123. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3124. EXPECT_TRUE(captured_cookie.empty());
  3125. }
  3126. TEST(RedirectToSamePort, ForwardCookie) {
  3127. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3128. // header so that ordinary session flows keep working.
  3129. Server svr;
  3130. std::string captured_cookie;
  3131. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3132. res.set_redirect("/target", 302);
  3133. });
  3134. svr.Get("/target", [&](const Request &req, Response &res) {
  3135. captured_cookie = req.get_header_value("Cookie");
  3136. res.set_content("OK", "text/plain");
  3137. });
  3138. auto port = svr.bind_to_any_port(HOST);
  3139. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3140. auto se = detail::scope_exit([&] {
  3141. svr.stop();
  3142. thread.join();
  3143. ASSERT_FALSE(svr.is_running());
  3144. });
  3145. svr.wait_until_ready();
  3146. Client cli(HOST, port);
  3147. cli.set_follow_location(true);
  3148. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3149. auto res = cli.Get("/redir", headers);
  3150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3151. EXPECT_EQ(StatusCode::OK_200, res->status);
  3152. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3153. }
  3154. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3155. Server svr;
  3156. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3157. // Port number that overflows int — should not crash
  3158. res.set_redirect("http://localhost:99999999999999999999/target");
  3159. });
  3160. auto port = svr.bind_to_any_port(HOST);
  3161. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3162. auto se = detail::scope_exit([&] {
  3163. svr.stop();
  3164. thread.join();
  3165. ASSERT_FALSE(svr.is_running());
  3166. });
  3167. svr.wait_until_ready();
  3168. Client cli(HOST, port);
  3169. cli.set_follow_location(true);
  3170. auto res = cli.Get("/redir");
  3171. // Should fail gracefully, not crash (no valid response due to bad port)
  3172. EXPECT_FALSE(res);
  3173. }
  3174. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3175. Server svr;
  3176. auto port = svr.bind_to_any_port(HOST);
  3177. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3178. // The server's own port followed by junk must not be followed
  3179. res.set_redirect("http://" + std::string(HOST) + ":" +
  3180. std::to_string(port) + "junk/target");
  3181. });
  3182. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3183. res.set_content("target", "text/plain");
  3184. });
  3185. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3186. auto se = detail::scope_exit([&] {
  3187. svr.stop();
  3188. thread.join();
  3189. ASSERT_FALSE(svr.is_running());
  3190. });
  3191. svr.wait_until_ready();
  3192. Client cli(HOST, port);
  3193. cli.set_follow_location(true);
  3194. auto res = cli.Get("/redir");
  3195. EXPECT_FALSE(res);
  3196. }
  3197. TEST(RedirectFromPageWithContent, Redirect) {
  3198. Server svr;
  3199. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3200. res.set_content("___", "text/plain");
  3201. res.set_redirect("/2");
  3202. });
  3203. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3204. res.set_content("Hello World!", "text/plain");
  3205. });
  3206. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3207. auto se = detail::scope_exit([&] {
  3208. svr.stop();
  3209. th.join();
  3210. ASSERT_FALSE(svr.is_running());
  3211. });
  3212. svr.wait_until_ready();
  3213. {
  3214. Client cli("localhost", PORT);
  3215. cli.set_follow_location(true);
  3216. std::string body;
  3217. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3218. body.append(data, data_length);
  3219. return true;
  3220. });
  3221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3222. EXPECT_EQ(StatusCode::OK_200, res->status);
  3223. EXPECT_EQ("Hello World!", body);
  3224. }
  3225. {
  3226. Client cli("localhost", PORT);
  3227. std::string body;
  3228. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3229. body.append(data, data_length);
  3230. return true;
  3231. });
  3232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3233. EXPECT_EQ(StatusCode::Found_302, res->status);
  3234. EXPECT_EQ("___", body);
  3235. }
  3236. }
  3237. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3238. Server svr;
  3239. auto port_str = std::to_string(PORT);
  3240. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3241. auto expected_host = "[::1]:" + port_str;
  3242. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3243. res.set_content("___", "text/plain");
  3244. // res.set_redirect("/2");
  3245. res.set_redirect(redirect_url);
  3246. });
  3247. svr.Get("/2", [&](const Request &req, Response &res) {
  3248. auto host_header = req.headers.find("Host");
  3249. ASSERT_TRUE(host_header != req.headers.end());
  3250. EXPECT_EQ(expected_host, host_header->second);
  3251. res.set_content("Hello World!", "text/plain");
  3252. });
  3253. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3254. auto se = detail::scope_exit([&] {
  3255. svr.stop();
  3256. th.join();
  3257. ASSERT_FALSE(svr.is_running());
  3258. });
  3259. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3260. // actually starts anything, so the condition !svr.is_running() will
  3261. // always remain true, and the loop never stops.
  3262. // This basically counts how many milliseconds have passed since the
  3263. // call to svr.listen(), and if after 5 seconds nothing started yet
  3264. // aborts the test.
  3265. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3266. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3267. ASSERT_LT(milliseconds, 5000U);
  3268. }
  3269. {
  3270. Client cli("::1", PORT);
  3271. cli.set_follow_location(true);
  3272. std::string body;
  3273. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3274. body.append(data, data_length);
  3275. return true;
  3276. });
  3277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3278. EXPECT_EQ(StatusCode::OK_200, res->status);
  3279. EXPECT_EQ("Hello World!", body);
  3280. }
  3281. {
  3282. Client cli("::1", PORT);
  3283. std::string body;
  3284. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3285. body.append(data, data_length);
  3286. return true;
  3287. });
  3288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3289. EXPECT_EQ(StatusCode::Found_302, res->status);
  3290. EXPECT_EQ("___", body);
  3291. }
  3292. }
  3293. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3294. Server svr;
  3295. svr.Get("/foo", [](const Request &req, Response &res) {
  3296. auto a = req.params.find("a");
  3297. if (a != req.params.end()) {
  3298. res.set_content((*a).second, "text/plain");
  3299. res.status = StatusCode::OK_200;
  3300. } else {
  3301. res.status = StatusCode::BadRequest_400;
  3302. }
  3303. });
  3304. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3305. auto se = detail::scope_exit([&] {
  3306. svr.stop();
  3307. thread.join();
  3308. ASSERT_FALSE(svr.is_running());
  3309. });
  3310. svr.wait_until_ready();
  3311. {
  3312. Client cli(HOST, PORT);
  3313. cli.set_path_encode(false);
  3314. auto res = cli.Get("/foo?a=explicitly+encoded");
  3315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3316. EXPECT_EQ(StatusCode::OK_200, res->status);
  3317. // This expects it back with a space, as the `+` won't have been
  3318. // url-encoded, and server-side the params get decoded turning `+`
  3319. // into spaces.
  3320. EXPECT_EQ("explicitly encoded", res->body);
  3321. }
  3322. }
  3323. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3324. // When path encoding is disabled the client must transmit the supplied
  3325. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3326. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3327. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3328. // than a space (0x20). Assert on the raw wire target to catch this.
  3329. Server svr;
  3330. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3331. svr.Get("/foo", [&](const Request &req, Response &res) {
  3332. EXPECT_EQ(expected_target, req.target);
  3333. res.status = StatusCode::OK_200;
  3334. });
  3335. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3336. auto se = detail::scope_exit([&] {
  3337. svr.stop();
  3338. thread.join();
  3339. ASSERT_FALSE(svr.is_running());
  3340. });
  3341. svr.wait_until_ready();
  3342. {
  3343. Client cli(HOST, PORT);
  3344. cli.set_path_encode(false);
  3345. auto res = cli.Get(expected_target.c_str());
  3346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3347. EXPECT_EQ(StatusCode::OK_200, res->status);
  3348. }
  3349. }
  3350. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3351. // `open_stream()` used to skip the path encoding that the buffered send
  3352. // path applies, so the same `path` produced different bytes in the request
  3353. // line depending on which API was used. Assert the two agree.
  3354. Server svr;
  3355. std::string target;
  3356. svr.Get(".*", [&](const Request &req, Response &res) {
  3357. target = req.target;
  3358. res.status = StatusCode::OK_200;
  3359. });
  3360. auto port = svr.bind_to_any_port(HOST);
  3361. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3362. auto se = detail::scope_exit([&] {
  3363. svr.stop();
  3364. thread.join();
  3365. ASSERT_FALSE(svr.is_running());
  3366. });
  3367. svr.wait_until_ready();
  3368. struct {
  3369. const char *path;
  3370. const char *expected;
  3371. } cases[] = {
  3372. {"/a b?x=1", "/a%20b?x=1"},
  3373. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3374. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3375. };
  3376. for (const auto &c : cases) {
  3377. Client cli(HOST, port);
  3378. target.clear();
  3379. auto res = cli.Get(c.path);
  3380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3381. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3382. auto buffered_target = target;
  3383. target.clear();
  3384. auto handle = cli.open_stream("GET", c.path);
  3385. EXPECT_TRUE(handle.is_valid())
  3386. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3387. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3388. }
  3389. }
  3390. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3391. // The `set_path_encode(false)` contract — transmit the supplied target
  3392. // verbatim — must hold for the streaming API too.
  3393. Server svr;
  3394. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3395. std::string target;
  3396. svr.Get("/foo", [&](const Request &req, Response &res) {
  3397. target = req.target;
  3398. res.status = StatusCode::OK_200;
  3399. });
  3400. auto port = svr.bind_to_any_port(HOST);
  3401. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3402. auto se = detail::scope_exit([&] {
  3403. svr.stop();
  3404. thread.join();
  3405. ASSERT_FALSE(svr.is_running());
  3406. });
  3407. svr.wait_until_ready();
  3408. {
  3409. Client cli(HOST, port);
  3410. cli.set_path_encode(false);
  3411. auto handle = cli.open_stream("GET", expected_target);
  3412. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3413. EXPECT_EQ(expected_target, target);
  3414. }
  3415. }
  3416. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3417. // With path encoding enabled a CR/LF in the target is percent-encoded
  3418. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3419. // write_request_line still backstops `set_path_encode(false)`, which is
  3420. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3421. Server svr;
  3422. // Captured before routing: the decoded path contains a newline, which a
  3423. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3424. std::string target;
  3425. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3426. target = req.target;
  3427. res.status = StatusCode::OK_200;
  3428. return Server::HandlerResponse::Handled;
  3429. });
  3430. auto port = svr.bind_to_any_port(HOST);
  3431. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3432. auto se = detail::scope_exit([&] {
  3433. svr.stop();
  3434. thread.join();
  3435. ASSERT_FALSE(svr.is_running());
  3436. });
  3437. svr.wait_until_ready();
  3438. {
  3439. Client cli(HOST, port);
  3440. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3441. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3442. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3443. }
  3444. }
  3445. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3446. // Every control character is percent-encoded, not just CR/LF, so the target
  3447. // passes the request-target check in write_request_line.
  3448. Server svr;
  3449. std::string target;
  3450. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3451. target = req.target;
  3452. res.status = StatusCode::OK_200;
  3453. return Server::HandlerResponse::Handled;
  3454. });
  3455. auto port = svr.bind_to_any_port(HOST);
  3456. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3457. auto se = detail::scope_exit([&] {
  3458. svr.stop();
  3459. thread.join();
  3460. ASSERT_FALSE(svr.is_running());
  3461. });
  3462. svr.wait_until_ready();
  3463. {
  3464. Client cli(HOST, port);
  3465. auto res = cli.Get("/a\tb\x1b\x7f");
  3466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3467. EXPECT_EQ("/a%09b%1B%7F", target);
  3468. }
  3469. }
  3470. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3471. // Nothing may reach the wire: a raw CR/LF target would split the request
  3472. // line and inject headers.
  3473. Server svr;
  3474. // Pre-routing so that "not called" means nothing reached the server at all,
  3475. // rather than merely failing to match a handler pattern.
  3476. auto handler_called = false;
  3477. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3478. handler_called = true;
  3479. res.status = StatusCode::OK_200;
  3480. return Server::HandlerResponse::Handled;
  3481. });
  3482. auto port = svr.bind_to_any_port(HOST);
  3483. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3484. auto se = detail::scope_exit([&] {
  3485. svr.stop();
  3486. thread.join();
  3487. ASSERT_FALSE(svr.is_running());
  3488. });
  3489. svr.wait_until_ready();
  3490. {
  3491. Client cli(HOST, port);
  3492. cli.set_path_encode(false);
  3493. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3494. EXPECT_FALSE(handle.is_valid());
  3495. EXPECT_EQ(Error::Write, handle.error);
  3496. EXPECT_FALSE(handler_called);
  3497. }
  3498. }
  3499. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3500. // Which of the two branches runs is decided by whether the query component
  3501. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3502. // an empty query and must still fall back to building one from
  3503. // `req.params`, while a non-empty query must win over `req.params`.
  3504. Server svr;
  3505. std::string target;
  3506. svr.Get("/foo", [&](const Request &req, Response &res) {
  3507. target = req.target;
  3508. res.status = StatusCode::OK_200;
  3509. });
  3510. auto port = svr.bind_to_any_port(HOST);
  3511. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3512. auto se = detail::scope_exit([&] {
  3513. svr.stop();
  3514. thread.join();
  3515. ASSERT_FALSE(svr.is_running());
  3516. });
  3517. svr.wait_until_ready();
  3518. {
  3519. // Trailing `?` -> empty query component -> `req.params` is used.
  3520. Client cli(HOST, port);
  3521. Request req;
  3522. req.method = "GET";
  3523. req.path = "/foo?";
  3524. req.params.emplace("a", "1");
  3525. target.clear();
  3526. auto res = cli.send(req);
  3527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3528. EXPECT_EQ("/foo?a=1", target);
  3529. }
  3530. {
  3531. // Non-empty query in `req.path` -> `req.params` is not appended.
  3532. Client cli(HOST, port);
  3533. Request req;
  3534. req.method = "GET";
  3535. req.path = "/foo?b=2";
  3536. req.params.emplace("a", "1");
  3537. target.clear();
  3538. auto res = cli.send(req);
  3539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3540. EXPECT_EQ("/foo?b=2", target);
  3541. }
  3542. }
  3543. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3544. Server svr;
  3545. svr.Get("/", [](const Request &req, Response &) {
  3546. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3547. });
  3548. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3549. auto se = detail::scope_exit([&] {
  3550. svr.stop();
  3551. thread.join();
  3552. ASSERT_FALSE(svr.is_running());
  3553. });
  3554. svr.wait_until_ready();
  3555. {
  3556. Client cli(HOST, PORT);
  3557. cli.set_path_encode(false);
  3558. auto res = cli.Get("/?something=%0A");
  3559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3560. EXPECT_EQ(StatusCode::OK_200, res->status);
  3561. }
  3562. }
  3563. TEST(BindServerTest, BindDualStack) {
  3564. Server svr;
  3565. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3566. res.set_content("Hello World!", "text/plain");
  3567. });
  3568. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3569. auto se = detail::scope_exit([&] {
  3570. svr.stop();
  3571. thread.join();
  3572. ASSERT_FALSE(svr.is_running());
  3573. });
  3574. svr.wait_until_ready();
  3575. {
  3576. Client cli("127.0.0.1", PORT);
  3577. auto res = cli.Get("/1");
  3578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3579. EXPECT_EQ(StatusCode::OK_200, res->status);
  3580. EXPECT_EQ("Hello World!", res->body);
  3581. }
  3582. {
  3583. Client cli("::1", PORT);
  3584. auto res = cli.Get("/1");
  3585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3586. EXPECT_EQ(StatusCode::OK_200, res->status);
  3587. EXPECT_EQ("Hello World!", res->body);
  3588. }
  3589. }
  3590. TEST(BindServerTest, BindAndListenSeparately) {
  3591. Server svr;
  3592. int port = svr.bind_to_any_port("0.0.0.0");
  3593. ASSERT_TRUE(svr.is_valid());
  3594. ASSERT_TRUE(port > 0);
  3595. svr.stop();
  3596. }
  3597. // Reports whether anything is still listening on a loopback port. A plain
  3598. // connect() is used instead of a Client request because a socket left bound by
  3599. // mistake accepts the connection into its backlog and never answers, which
  3600. // would hang the test instead of failing it.
  3601. static bool is_loopback_port_accepting(int port) {
  3602. sockaddr_in addr{};
  3603. addr.sin_family = AF_INET;
  3604. addr.sin_port = htons(static_cast<uint16_t>(port));
  3605. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3606. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3607. EXPECT_NE(sock, INVALID_SOCKET);
  3608. if (sock == INVALID_SOCKET) { return false; }
  3609. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3610. static_cast<socklen_t>(sizeof(addr)));
  3611. detail::close_socket(sock);
  3612. return ret == 0;
  3613. }
  3614. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3615. Server svr;
  3616. auto port = svr.bind_to_any_port("127.0.0.1");
  3617. ASSERT_TRUE(port > 0);
  3618. svr.stop();
  3619. // bind_to_any_port() already called listen(2), so until stop() closed the
  3620. // descriptor the port kept accepting connections into the backlog. ASSERT
  3621. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3622. // below blocks forever in the accept loop.
  3623. ASSERT_FALSE(is_loopback_port_accepting(port));
  3624. // Nothing is left to accept on, so listen_after_bind() must report failure
  3625. // instead of returning success without ever serving.
  3626. EXPECT_FALSE(svr.listen_after_bind());
  3627. // The failed listen marks the server decommissioned, so a waiter returns
  3628. // instead of spinning forever.
  3629. svr.wait_until_ready();
  3630. }
  3631. #ifdef CPPHTTPLIB_SSL_ENABLED
  3632. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3633. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3634. CLIENT_CA_CERT_DIR);
  3635. int port = svr.bind_to_any_port("0.0.0.0");
  3636. ASSERT_TRUE(svr.is_valid());
  3637. ASSERT_TRUE(port > 0);
  3638. svr.stop();
  3639. }
  3640. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3641. // or a rejected CustomRoute() registration would not stop the server binding.
  3642. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3643. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3644. CLIENT_CA_CERT_DIR);
  3645. ASSERT_TRUE(svr.is_valid());
  3646. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3647. EXPECT_FALSE(svr.is_valid());
  3648. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3649. }
  3650. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3651. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3652. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3653. int port = svr.bind_to_any_port("0.0.0.0");
  3654. ASSERT_TRUE(svr.is_valid());
  3655. ASSERT_TRUE(port > 0);
  3656. svr.stop();
  3657. }
  3658. TEST(BindServerTest, UpdateCertsPem) {
  3659. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3660. int port = svr.bind_to_any_port("0.0.0.0");
  3661. ASSERT_TRUE(svr.is_valid());
  3662. ASSERT_TRUE(port > 0);
  3663. // Read PEM files
  3664. std::string cert_pem, key_pem, ca_pem;
  3665. read_file(SERVER_CERT_FILE, cert_pem);
  3666. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3667. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3668. // Update server certificates using PEM API
  3669. ASSERT_TRUE(
  3670. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3671. ASSERT_TRUE(svr.is_valid());
  3672. svr.stop();
  3673. }
  3674. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3675. // Start server with client CA (enables client auth)
  3676. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3677. ASSERT_TRUE(svr.is_valid());
  3678. bool handler_called = false;
  3679. svr.Get("/test", [&](const Request &req, Response &res) {
  3680. handler_called = true;
  3681. // Verify client certificate is present
  3682. auto cert = req.peer_cert();
  3683. EXPECT_TRUE(static_cast<bool>(cert));
  3684. res.set_content("ok", "text/plain");
  3685. });
  3686. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3687. auto se = detail::scope_exit([&] {
  3688. svr.stop();
  3689. t.join();
  3690. ASSERT_FALSE(svr.is_running());
  3691. });
  3692. svr.wait_until_ready();
  3693. // Read PEM files
  3694. std::string cert_pem, key_pem, ca_pem;
  3695. read_file(SERVER_CERT_FILE, cert_pem);
  3696. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3697. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3698. // Update server certificates and client CA using PEM API while server running
  3699. ASSERT_TRUE(
  3700. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3701. // Connect with client certificate
  3702. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3703. cli.enable_server_certificate_verification(false);
  3704. cli.set_connection_timeout(30);
  3705. auto res = cli.Get("/test");
  3706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3707. ASSERT_EQ(StatusCode::OK_200, res->status);
  3708. ASSERT_TRUE(handler_called);
  3709. EXPECT_EQ("ok", res->body);
  3710. }
  3711. #endif
  3712. TEST(ErrorHandlerTest, ContentLength) {
  3713. Server svr;
  3714. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3715. res.status = StatusCode::OK_200;
  3716. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3717. "text/html"); // <= Content-Length still 13
  3718. });
  3719. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3720. res.set_content("Hello World!\n", "text/plain");
  3721. res.status = 524;
  3722. });
  3723. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3724. auto se = detail::scope_exit([&] {
  3725. svr.stop();
  3726. thread.join();
  3727. ASSERT_FALSE(svr.is_running());
  3728. });
  3729. svr.wait_until_ready();
  3730. {
  3731. Client cli(HOST, PORT);
  3732. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3734. EXPECT_EQ(StatusCode::OK_200, res->status);
  3735. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3736. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3737. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3738. }
  3739. }
  3740. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3741. TEST(ExceptionTest, WithoutExceptionHandler) {
  3742. Server svr;
  3743. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3744. throw std::runtime_error("exception...");
  3745. });
  3746. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3747. throw std::runtime_error("exception\r\n...");
  3748. });
  3749. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3750. auto se = detail::scope_exit([&] {
  3751. svr.stop();
  3752. listen_thread.join();
  3753. ASSERT_FALSE(svr.is_running());
  3754. });
  3755. svr.wait_until_ready();
  3756. Client cli("localhost", PORT);
  3757. {
  3758. auto res = cli.Get("/exception");
  3759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3760. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3761. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3762. }
  3763. {
  3764. auto res = cli.Get("/unknown");
  3765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3766. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3767. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3768. }
  3769. }
  3770. TEST(ExceptionTest, WithExceptionHandler) {
  3771. Server svr;
  3772. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3773. std::exception_ptr ep) {
  3774. EXPECT_FALSE(ep == nullptr);
  3775. try {
  3776. std::rethrow_exception(ep);
  3777. } catch (std::exception &e) {
  3778. EXPECT_EQ("abc", std::string(e.what()));
  3779. } catch (...) {}
  3780. res.status = StatusCode::InternalServerError_500;
  3781. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3782. "text/html"); // <= Content-Length still 13 at this point
  3783. });
  3784. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3785. res.set_content("Hello World!\n", "text/plain");
  3786. throw std::runtime_error("abc");
  3787. });
  3788. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3789. auto se = detail::scope_exit([&] {
  3790. svr.stop();
  3791. thread.join();
  3792. ASSERT_FALSE(svr.is_running());
  3793. });
  3794. svr.wait_until_ready();
  3795. for (size_t i = 0; i < 10; i++) {
  3796. Client cli(HOST, PORT);
  3797. for (size_t j = 0; j < 100; j++) {
  3798. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3800. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3801. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3802. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3803. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3804. }
  3805. cli.set_keep_alive(true);
  3806. for (size_t j = 0; j < 100; j++) {
  3807. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3809. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3810. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3811. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3812. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3813. }
  3814. }
  3815. }
  3816. TEST(ExceptionTest, AndErrorHandler) {
  3817. Server svr;
  3818. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3819. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3820. });
  3821. svr.set_exception_handler(
  3822. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3823. EXPECT_FALSE(ep == nullptr);
  3824. try {
  3825. std::rethrow_exception(ep);
  3826. } catch (std::exception &e) {
  3827. res.set_content(e.what(), "text/html");
  3828. } catch (...) {}
  3829. res.status = StatusCode::InternalServerError_500;
  3830. });
  3831. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3832. throw std::runtime_error("EXCEPTION");
  3833. });
  3834. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3835. res.set_content("ERROR", "text/html");
  3836. res.status = StatusCode::InternalServerError_500;
  3837. });
  3838. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3839. auto se = detail::scope_exit([&] {
  3840. svr.stop();
  3841. thread.join();
  3842. ASSERT_FALSE(svr.is_running());
  3843. });
  3844. svr.wait_until_ready();
  3845. Client cli(HOST, PORT);
  3846. {
  3847. auto res = cli.Get("/exception");
  3848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3849. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3850. EXPECT_EQ("EXCEPTION", res->body);
  3851. }
  3852. {
  3853. auto res = cli.Get("/error");
  3854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3855. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3856. EXPECT_EQ("ERROR", res->body);
  3857. }
  3858. {
  3859. auto res = cli.Get("/invalid");
  3860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3861. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3862. EXPECT_EQ("NOT_FOUND", res->body);
  3863. }
  3864. }
  3865. #endif
  3866. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3867. // process_request() wraps only routing() in a try/catch, so an exception from
  3868. // any other user callback used to unwind into the task queue - which does not
  3869. // catch - and terminate the process. Each test below runs the server on a
  3870. // single worker thread: a guard that catches the exception but still loses the
  3871. // thread would otherwise be hidden by a spare worker serving the follow-up
  3872. // request. Note that a regression here aborts the whole test binary rather
  3873. // than failing one test.
  3874. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3875. Server svr;
  3876. svr.new_task_queue = [] { return new ThreadPool(1); };
  3877. std::atomic<int> reported{0};
  3878. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3879. if (err == Error::UserCallbackException) { reported++; }
  3880. });
  3881. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3882. res.set_content_provider(
  3883. 1024, "text/plain",
  3884. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3885. sink.write("hello", 5);
  3886. throw std::runtime_error("from the content provider");
  3887. });
  3888. });
  3889. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3890. res.set_content("ok", "text/plain");
  3891. });
  3892. auto port = svr.bind_to_any_port(HOST);
  3893. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3894. auto se = detail::scope_exit([&] {
  3895. svr.stop();
  3896. listen_thread.join();
  3897. ASSERT_FALSE(svr.is_running());
  3898. });
  3899. svr.wait_until_ready();
  3900. {
  3901. Client cli(HOST, port);
  3902. cli.set_read_timeout(5, 0);
  3903. EXPECT_FALSE(cli.Get("/throw"));
  3904. }
  3905. EXPECT_TRUE(svr.is_running());
  3906. EXPECT_EQ(1, reported.load());
  3907. // A request on a fresh connection is still served.
  3908. {
  3909. Client cli(HOST, port);
  3910. auto res = cli.Get("/ok");
  3911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3912. EXPECT_EQ(StatusCode::OK_200, res->status);
  3913. EXPECT_EQ("ok", res->body);
  3914. }
  3915. }
  3916. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3917. Server svr;
  3918. svr.new_task_queue = [] { return new ThreadPool(1); };
  3919. std::atomic<bool> should_throw{true};
  3920. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3921. res.set_content("hi", "text/plain");
  3922. });
  3923. svr.set_post_routing_handler(
  3924. [&](const Request & /*req*/, Response & /*res*/) {
  3925. if (should_throw) {
  3926. throw std::runtime_error("from the post-routing handler");
  3927. }
  3928. });
  3929. auto port = svr.bind_to_any_port(HOST);
  3930. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3931. auto se = detail::scope_exit([&] {
  3932. svr.stop();
  3933. listen_thread.join();
  3934. ASSERT_FALSE(svr.is_running());
  3935. });
  3936. svr.wait_until_ready();
  3937. {
  3938. Client cli(HOST, port);
  3939. cli.set_read_timeout(5, 0);
  3940. EXPECT_FALSE(cli.Get("/hi"));
  3941. }
  3942. EXPECT_TRUE(svr.is_running());
  3943. should_throw = false;
  3944. {
  3945. Client cli(HOST, port);
  3946. auto res = cli.Get("/hi");
  3947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3948. EXPECT_EQ(StatusCode::OK_200, res->status);
  3949. EXPECT_EQ("hi", res->body);
  3950. }
  3951. }
  3952. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  3953. // The guard reports the caught exception through the error logger, which is
  3954. // a user callback too. A logger that throws has to be contained as well, or
  3955. // the process would terminate from inside the catch.
  3956. Server svr;
  3957. svr.new_task_queue = [] { return new ThreadPool(1); };
  3958. std::atomic<int> reported{0};
  3959. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3960. if (err == Error::UserCallbackException) {
  3961. reported++;
  3962. throw std::runtime_error("from the error logger");
  3963. }
  3964. });
  3965. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3966. res.set_content_provider(
  3967. 1024, "text/plain",
  3968. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3969. sink.write("hello", 5);
  3970. throw std::runtime_error("from the content provider");
  3971. });
  3972. });
  3973. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3974. res.set_content("ok", "text/plain");
  3975. });
  3976. auto port = svr.bind_to_any_port(HOST);
  3977. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3978. auto se = detail::scope_exit([&] {
  3979. svr.stop();
  3980. listen_thread.join();
  3981. ASSERT_FALSE(svr.is_running());
  3982. });
  3983. svr.wait_until_ready();
  3984. {
  3985. Client cli(HOST, port);
  3986. cli.set_read_timeout(5, 0);
  3987. EXPECT_FALSE(cli.Get("/throw"));
  3988. }
  3989. EXPECT_TRUE(svr.is_running());
  3990. EXPECT_EQ(1, reported.load());
  3991. {
  3992. Client cli(HOST, port);
  3993. auto res = cli.Get("/ok");
  3994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3995. EXPECT_EQ(StatusCode::OK_200, res->status);
  3996. EXPECT_EQ("ok", res->body);
  3997. }
  3998. }
  3999. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4000. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4001. // so the exception unwinds through the ws::WebSocket object on its way to
  4002. // the guard. None of the HTTP cases above cross that.
  4003. Server svr;
  4004. svr.new_task_queue = [] { return new ThreadPool(1); };
  4005. std::atomic<int> reported{0};
  4006. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4007. if (err == Error::UserCallbackException) { reported++; }
  4008. });
  4009. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4010. throw std::runtime_error("from the WebSocket handler");
  4011. });
  4012. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4013. res.set_content("ok", "text/plain");
  4014. });
  4015. auto port = svr.bind_to_any_port(HOST);
  4016. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4017. auto se = detail::scope_exit([&] {
  4018. svr.stop();
  4019. listen_thread.join();
  4020. ASSERT_FALSE(svr.is_running());
  4021. });
  4022. svr.wait_until_ready();
  4023. {
  4024. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4025. "/ws");
  4026. auto res = client.connect();
  4027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4028. // The server dropped the connection instead of dying.
  4029. std::string msg;
  4030. EXPECT_FALSE(client.read(msg));
  4031. client.close();
  4032. }
  4033. EXPECT_TRUE(svr.is_running());
  4034. EXPECT_EQ(1, reported.load());
  4035. {
  4036. Client cli(HOST, port);
  4037. auto res = cli.Get("/ok");
  4038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4039. EXPECT_EQ(StatusCode::OK_200, res->status);
  4040. EXPECT_EQ("ok", res->body);
  4041. }
  4042. }
  4043. #ifdef CPPHTTPLIB_SSL_ENABLED
  4044. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4045. // SSLServer::process_and_close_socket() is a separate overload with its own
  4046. // guard, so it is exercised on its own.
  4047. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4048. ASSERT_TRUE(svr.is_valid());
  4049. svr.new_task_queue = [] { return new ThreadPool(1); };
  4050. std::atomic<int> reported{0};
  4051. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4052. if (err == Error::UserCallbackException) { reported++; }
  4053. });
  4054. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4055. res.set_content_provider(
  4056. 1024, "text/plain",
  4057. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4058. sink.write("hello", 5);
  4059. throw std::runtime_error("from the content provider");
  4060. });
  4061. });
  4062. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4063. res.set_content("ok", "text/plain");
  4064. });
  4065. auto port = svr.bind_to_any_port(HOST);
  4066. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4067. auto se = detail::scope_exit([&] {
  4068. svr.stop();
  4069. listen_thread.join();
  4070. ASSERT_FALSE(svr.is_running());
  4071. });
  4072. svr.wait_until_ready();
  4073. {
  4074. SSLClient cli(HOST, port);
  4075. cli.enable_server_certificate_verification(false);
  4076. cli.set_read_timeout(5, 0);
  4077. EXPECT_FALSE(cli.Get("/throw"));
  4078. }
  4079. EXPECT_TRUE(svr.is_running());
  4080. EXPECT_EQ(1, reported.load());
  4081. {
  4082. SSLClient cli(HOST, port);
  4083. cli.enable_server_certificate_verification(false);
  4084. auto res = cli.Get("/ok");
  4085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4086. EXPECT_EQ(StatusCode::OK_200, res->status);
  4087. EXPECT_EQ("ok", res->body);
  4088. }
  4089. }
  4090. #endif
  4091. #endif
  4092. TEST(NoContentTest, ContentLength) {
  4093. Server svr;
  4094. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4095. res.status = StatusCode::NoContent_204;
  4096. });
  4097. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4098. auto se = detail::scope_exit([&] {
  4099. svr.stop();
  4100. thread.join();
  4101. ASSERT_FALSE(svr.is_running());
  4102. });
  4103. svr.wait_until_ready();
  4104. {
  4105. Client cli(HOST, PORT);
  4106. auto res = cli.Get("/hi");
  4107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4108. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4109. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4110. }
  4111. }
  4112. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4113. #ifdef CPPHTTPLIB_SSL_ENABLED
  4114. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4115. ASSERT_TRUE(svr.is_valid());
  4116. #else
  4117. Server svr;
  4118. #endif
  4119. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4120. if (req.path == "/routing_handler") {
  4121. res.set_header("PRE_ROUTING", "on");
  4122. res.set_content("Routing Handler", "text/plain");
  4123. return httplib::Server::HandlerResponse::Handled;
  4124. }
  4125. return httplib::Server::HandlerResponse::Unhandled;
  4126. });
  4127. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4128. res.set_content("Error", "text/html");
  4129. });
  4130. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4131. if (req.path == "/routing_handler") {
  4132. res.set_header("POST_ROUTING", "on");
  4133. }
  4134. });
  4135. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4136. res.set_content("Hello World!\n", "text/plain");
  4137. });
  4138. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4139. auto se = detail::scope_exit([&] {
  4140. svr.stop();
  4141. thread.join();
  4142. ASSERT_FALSE(svr.is_running());
  4143. });
  4144. svr.wait_until_ready();
  4145. {
  4146. #ifdef CPPHTTPLIB_SSL_ENABLED
  4147. SSLClient cli(HOST, PORT);
  4148. cli.enable_server_certificate_verification(false);
  4149. #else
  4150. Client cli(HOST, PORT);
  4151. #endif
  4152. auto res = cli.Get("/routing_handler");
  4153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4154. EXPECT_EQ(StatusCode::OK_200, res->status);
  4155. EXPECT_EQ("Routing Handler", res->body);
  4156. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4157. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4158. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4159. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4160. }
  4161. {
  4162. #ifdef CPPHTTPLIB_SSL_ENABLED
  4163. SSLClient cli(HOST, PORT);
  4164. cli.enable_server_certificate_verification(false);
  4165. #else
  4166. Client cli(HOST, PORT);
  4167. #endif
  4168. auto res = cli.Get("/hi");
  4169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4170. EXPECT_EQ(StatusCode::OK_200, res->status);
  4171. EXPECT_EQ("Hello World!\n", res->body);
  4172. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4173. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4174. }
  4175. {
  4176. #ifdef CPPHTTPLIB_SSL_ENABLED
  4177. SSLClient cli(HOST, PORT);
  4178. cli.enable_server_certificate_verification(false);
  4179. #else
  4180. Client cli(HOST, PORT);
  4181. #endif
  4182. auto res = cli.Get("/aaa");
  4183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4184. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4185. EXPECT_EQ("Error", res->body);
  4186. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4187. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4188. }
  4189. }
  4190. TEST(RequestHandlerTest, PreRequestHandler) {
  4191. auto route_path = "/user/:user";
  4192. Server svr;
  4193. svr.Get("/hi", [](const Request &, Response &res) {
  4194. res.set_content("hi", "text/plain");
  4195. });
  4196. svr.Get(route_path, [](const Request &req, Response &res) {
  4197. res.set_content(req.path_params.at("user"), "text/plain");
  4198. });
  4199. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4200. if (req.matched_route == route_path) {
  4201. auto user = req.path_params.at("user");
  4202. if (user != "john") {
  4203. res.status = StatusCode::Forbidden_403;
  4204. res.set_content("error", "text/html");
  4205. return Server::HandlerResponse::Handled;
  4206. }
  4207. }
  4208. return Server::HandlerResponse::Unhandled;
  4209. });
  4210. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4211. auto se = detail::scope_exit([&] {
  4212. svr.stop();
  4213. thread.join();
  4214. ASSERT_FALSE(svr.is_running());
  4215. });
  4216. svr.wait_until_ready();
  4217. Client cli(HOST, PORT);
  4218. {
  4219. auto res = cli.Get("/hi");
  4220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4221. EXPECT_EQ(StatusCode::OK_200, res->status);
  4222. EXPECT_EQ("hi", res->body);
  4223. }
  4224. {
  4225. auto res = cli.Get("/user/john");
  4226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4227. EXPECT_EQ(StatusCode::OK_200, res->status);
  4228. EXPECT_EQ("john", res->body);
  4229. }
  4230. {
  4231. auto res = cli.Get("/user/invalid-user");
  4232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4233. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4234. EXPECT_EQ("error", res->body);
  4235. }
  4236. }
  4237. // The pre-request handler must run before the request body is read, so a
  4238. // rejected request never forces the server to buffer a (potentially large)
  4239. // body. Here the posted body is larger than the payload limit: if the body
  4240. // were read first the server would answer 413, but because the pre-request
  4241. // handler runs first it answers 403 and the body is never read.
  4242. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4243. Server svr;
  4244. svr.set_payload_max_length(8);
  4245. auto handler_ran = false;
  4246. svr.Post("/reject", [&](const Request &req, Response &res) {
  4247. handler_ran = true;
  4248. res.set_content(req.body, "text/plain");
  4249. });
  4250. svr.Post("/accept", [](const Request &req, Response &res) {
  4251. res.set_content(req.body, "text/plain");
  4252. });
  4253. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4254. if (req.matched_route == "/reject") {
  4255. res.status = StatusCode::Forbidden_403;
  4256. res.set_content("denied", "text/plain");
  4257. return Server::HandlerResponse::Handled;
  4258. }
  4259. return Server::HandlerResponse::Unhandled;
  4260. });
  4261. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4262. auto se = detail::scope_exit([&] {
  4263. svr.stop();
  4264. thread.join();
  4265. ASSERT_FALSE(svr.is_running());
  4266. });
  4267. svr.wait_until_ready();
  4268. Client cli(HOST, PORT);
  4269. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4270. // rejects with 403 before the body is read, so 413 is never reached.
  4271. {
  4272. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4274. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4275. EXPECT_EQ("denied", res->body);
  4276. EXPECT_FALSE(handler_ran);
  4277. }
  4278. // An approved route still reads the body and enforces the payload limit.
  4279. {
  4280. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4282. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4283. }
  4284. }
  4285. TEST(UserDataTest, BasicOperations) {
  4286. httplib::UserData ud;
  4287. // Initially empty
  4288. EXPECT_FALSE(ud.has("key"));
  4289. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4290. // set and get
  4291. ud.set("key", 42);
  4292. EXPECT_TRUE(ud.has("key"));
  4293. auto *p = ud.get<int>("key");
  4294. ASSERT_NE(nullptr, p);
  4295. EXPECT_EQ(42, *p);
  4296. // Type mismatch → nullptr
  4297. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4298. // Overwrite with different type
  4299. ud.set("key", std::string("hello"));
  4300. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4301. auto *s = ud.get<std::string>("key");
  4302. ASSERT_NE(nullptr, s);
  4303. EXPECT_EQ("hello", *s);
  4304. // erase
  4305. ud.erase("key");
  4306. EXPECT_FALSE(ud.has("key"));
  4307. // clear
  4308. ud.set("a", 1);
  4309. ud.set("b", 2);
  4310. ud.clear();
  4311. EXPECT_FALSE(ud.has("a"));
  4312. EXPECT_FALSE(ud.has("b"));
  4313. }
  4314. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4315. struct AuthCtx {
  4316. std::string user_id;
  4317. };
  4318. Server svr;
  4319. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4320. res.user_data.set("auth", AuthCtx{"alice"});
  4321. return Server::HandlerResponse::Unhandled;
  4322. });
  4323. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4324. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4325. ASSERT_NE(nullptr, ctx);
  4326. res.set_content("Hello " + ctx->user_id, "text/plain");
  4327. });
  4328. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4329. auto se = detail::scope_exit([&] {
  4330. svr.stop();
  4331. thread.join();
  4332. ASSERT_FALSE(svr.is_running());
  4333. });
  4334. svr.wait_until_ready();
  4335. Client cli(HOST, PORT);
  4336. auto res = cli.Get("/me");
  4337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4338. EXPECT_EQ(StatusCode::OK_200, res->status);
  4339. EXPECT_EQ("Hello alice", res->body);
  4340. }
  4341. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4342. struct RoleCtx {
  4343. std::string role;
  4344. };
  4345. Server svr;
  4346. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4347. res.user_data.set("role", RoleCtx{"admin"});
  4348. return Server::HandlerResponse::Unhandled;
  4349. });
  4350. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4351. auto *ctx = res.user_data.get<RoleCtx>("role");
  4352. ASSERT_NE(nullptr, ctx);
  4353. res.set_content(ctx->role, "text/plain");
  4354. });
  4355. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4356. auto se = detail::scope_exit([&] {
  4357. svr.stop();
  4358. thread.join();
  4359. ASSERT_FALSE(svr.is_running());
  4360. });
  4361. svr.wait_until_ready();
  4362. Client cli(HOST, PORT);
  4363. auto res = cli.Get("/role");
  4364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4365. EXPECT_EQ(StatusCode::OK_200, res->status);
  4366. EXPECT_EQ("admin", res->body);
  4367. }
  4368. TEST(InvalidFormatTest, StatusCode) {
  4369. Server svr;
  4370. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4371. res.set_content("Hello World!\n", "text/plain");
  4372. res.status = 9999; // Status should be a three-digit code...
  4373. });
  4374. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4375. auto se = detail::scope_exit([&] {
  4376. svr.stop();
  4377. thread.join();
  4378. ASSERT_FALSE(svr.is_running());
  4379. });
  4380. svr.wait_until_ready();
  4381. {
  4382. Client cli(HOST, PORT);
  4383. auto res = cli.Get("/hi");
  4384. ASSERT_FALSE(res);
  4385. }
  4386. }
  4387. TEST(URLFragmentTest, WithFragment) {
  4388. Server svr;
  4389. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4390. EXPECT_TRUE(req.target == "/hi");
  4391. });
  4392. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4393. auto se = detail::scope_exit([&] {
  4394. svr.stop();
  4395. thread.join();
  4396. ASSERT_FALSE(svr.is_running());
  4397. });
  4398. svr.wait_until_ready();
  4399. {
  4400. Client cli(HOST, PORT);
  4401. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4402. EXPECT_TRUE(res);
  4403. EXPECT_EQ(StatusCode::OK_200, res->status);
  4404. res = cli.Get("/hi%23key1=val1=key2=val2");
  4405. EXPECT_TRUE(res);
  4406. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4407. }
  4408. }
  4409. TEST(HeaderWriter, SetHeaderWriter) {
  4410. Server svr;
  4411. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4412. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4413. return detail::write_headers(strm, hdrs);
  4414. });
  4415. svr.Get("/hi", [](const Request &req, Response &res) {
  4416. auto it = req.headers.find("CustomClientHeader");
  4417. EXPECT_TRUE(it != req.headers.end());
  4418. EXPECT_EQ(it->second, "CustomClientValue");
  4419. res.set_content("Hello World!\n", "text/plain");
  4420. });
  4421. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4422. auto se = detail::scope_exit([&] {
  4423. svr.stop();
  4424. thread.join();
  4425. ASSERT_FALSE(svr.is_running());
  4426. });
  4427. svr.wait_until_ready();
  4428. {
  4429. Client cli(HOST, PORT);
  4430. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4431. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4432. return detail::write_headers(strm, hdrs);
  4433. });
  4434. auto res = cli.Get("/hi");
  4435. EXPECT_TRUE(res);
  4436. EXPECT_EQ(StatusCode::OK_200, res->status);
  4437. auto it = res->headers.find("CustomServerHeader");
  4438. EXPECT_TRUE(it != res->headers.end());
  4439. EXPECT_EQ(it->second, "CustomServerValue");
  4440. }
  4441. }
  4442. class ServerTest : public ::testing::Test {
  4443. protected:
  4444. ServerTest()
  4445. : cli_(HOST, PORT)
  4446. #ifdef CPPHTTPLIB_SSL_ENABLED
  4447. ,
  4448. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4449. #endif
  4450. {
  4451. #ifdef CPPHTTPLIB_SSL_ENABLED
  4452. cli_.enable_server_certificate_verification(false);
  4453. #endif
  4454. // Allow LARGE_DATA (100MB) responses
  4455. cli_.set_payload_max_length(200 * 1024 * 1024);
  4456. }
  4457. virtual void SetUp() {
  4458. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4459. svr_.set_payload_max_length(200 * 1024 * 1024);
  4460. svr_.set_mount_point("/", "./www");
  4461. svr_.set_mount_point("/mount", "./www2");
  4462. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4463. svr_.Get("/hi",
  4464. [&](const Request & /*req*/, Response &res) {
  4465. res.set_content("Hello World!", "text/plain");
  4466. })
  4467. .Get("/file_content",
  4468. [&](const Request & /*req*/, Response &res) {
  4469. res.set_file_content("./www/dir/test.html");
  4470. })
  4471. .Get("/file_content_with_content_type",
  4472. [&](const Request & /*req*/, Response &res) {
  4473. res.set_file_content("./www/file", "text/plain");
  4474. })
  4475. .Get("/invalid_file_content",
  4476. [&](const Request & /*req*/, Response &res) {
  4477. res.set_file_content("./www/dir/invalid_file_path");
  4478. })
  4479. .Get("/http_response_splitting",
  4480. [&](const Request & /*req*/, Response &res) {
  4481. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4482. EXPECT_EQ(0U, res.headers.size());
  4483. EXPECT_FALSE(res.has_header("a"));
  4484. res.set_header("a", "1\nSet-Cookie: a=1");
  4485. EXPECT_EQ(0U, res.headers.size());
  4486. EXPECT_FALSE(res.has_header("a"));
  4487. res.set_header("a", "1\rSet-Cookie: a=1");
  4488. EXPECT_EQ(0U, res.headers.size());
  4489. EXPECT_FALSE(res.has_header("a"));
  4490. res.set_header("a\r\nb", "0");
  4491. EXPECT_EQ(0U, res.headers.size());
  4492. EXPECT_FALSE(res.has_header("a"));
  4493. res.set_header("a\rb", "0");
  4494. EXPECT_EQ(0U, res.headers.size());
  4495. EXPECT_FALSE(res.has_header("a"));
  4496. res.set_header("a\nb", "0");
  4497. EXPECT_EQ(0U, res.headers.size());
  4498. EXPECT_FALSE(res.has_header("a"));
  4499. res.set_redirect("1\r\nSet-Cookie: a=1");
  4500. EXPECT_EQ(0U, res.headers.size());
  4501. EXPECT_FALSE(res.has_header("Location"));
  4502. })
  4503. .Get("/slow",
  4504. [&](const Request & /*req*/, Response &res) {
  4505. std::this_thread::sleep_for(std::chrono::seconds(4));
  4506. res.set_content("slow", "text/plain");
  4507. })
  4508. #if 0
  4509. .Post("/slowpost",
  4510. [&](const Request & /*req*/, Response &res) {
  4511. std::this_thread::sleep_for(std::chrono::seconds(2));
  4512. res.set_content("slow", "text/plain");
  4513. })
  4514. #endif
  4515. .Get("/remote_addr",
  4516. [&](const Request &req, Response &res) {
  4517. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4518. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4519. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4520. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4521. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4522. #endif
  4523. res.set_content(req.remote_addr, "text/plain");
  4524. })
  4525. .Get("/local_addr",
  4526. [&](const Request &req, Response &res) {
  4527. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4528. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4529. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4530. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4531. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4532. #endif
  4533. auto local_addr = req.local_addr;
  4534. auto local_port = std::to_string(req.local_port);
  4535. res.set_content(local_addr.append(":").append(local_port),
  4536. "text/plain");
  4537. })
  4538. .Get("/endwith%",
  4539. [&](const Request & /*req*/, Response &res) {
  4540. res.set_content("Hello World!", "text/plain");
  4541. })
  4542. .Get("/a\\+\\+b",
  4543. [&](const Request &req, Response &res) {
  4544. ASSERT_TRUE(req.has_param("a +b"));
  4545. auto val = req.get_param_value("a +b");
  4546. res.set_content(val, "text/plain");
  4547. })
  4548. .Get("/", [&](const Request & /*req*/,
  4549. Response &res) { res.set_redirect("/hi"); })
  4550. .Post("/1",
  4551. [](const Request & /*req*/, Response &res) {
  4552. res.set_redirect("/2", StatusCode::SeeOther_303);
  4553. })
  4554. .Get("/2",
  4555. [](const Request & /*req*/, Response &res) {
  4556. res.set_content("redirected.", "text/plain");
  4557. res.status = StatusCode::OK_200;
  4558. })
  4559. .Post("/person",
  4560. [&](const Request &req, Response &res) {
  4561. if (req.has_param("name") && req.has_param("note")) {
  4562. persons_[req.get_param_value("name")] =
  4563. req.get_param_value("note");
  4564. } else {
  4565. res.status = StatusCode::BadRequest_400;
  4566. }
  4567. })
  4568. .Put("/person",
  4569. [&](const Request &req, Response &res) {
  4570. if (req.has_param("name") && req.has_param("note")) {
  4571. persons_[req.get_param_value("name")] =
  4572. req.get_param_value("note");
  4573. } else {
  4574. res.status = StatusCode::BadRequest_400;
  4575. }
  4576. })
  4577. .Get("/person/(.*)",
  4578. [&](const Request &req, Response &res) {
  4579. string name = req.matches[1];
  4580. if (persons_.find(name) != persons_.end()) {
  4581. auto note = persons_[name];
  4582. res.set_content(note, "text/plain");
  4583. } else {
  4584. res.status = StatusCode::NotFound_404;
  4585. }
  4586. })
  4587. .Delete("/person",
  4588. [&](const Request &req, Response &res) {
  4589. if (req.has_param("name")) {
  4590. string name = req.get_param_value("name");
  4591. if (persons_.find(name) != persons_.end()) {
  4592. persons_.erase(name);
  4593. res.set_content("DELETED", "text/plain");
  4594. } else {
  4595. res.status = StatusCode::NotFound_404;
  4596. }
  4597. } else {
  4598. res.status = StatusCode::BadRequest_400;
  4599. }
  4600. })
  4601. .Post("/x-www-form-urlencoded-json",
  4602. [&](const Request &req, Response &res) {
  4603. auto json = req.get_param_value("json");
  4604. ASSERT_EQ(JSON_DATA, json);
  4605. res.set_content(json, "appliation/json");
  4606. res.status = StatusCode::OK_200;
  4607. })
  4608. .Get("/streamed-chunked",
  4609. [&](const Request & /*req*/, Response &res) {
  4610. res.set_chunked_content_provider(
  4611. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4612. sink.os << "123";
  4613. sink.os << "456";
  4614. sink.os << "789";
  4615. sink.done();
  4616. return true;
  4617. });
  4618. })
  4619. .Get("/streamed-chunked-with-prohibited-trailer",
  4620. [&](const Request & /*req*/, Response &res) {
  4621. auto i = new int(0);
  4622. // Declare both a prohibited trailer (Content-Length) and an
  4623. // allowed one
  4624. res.set_header("Trailer", "Content-Length, X-Allowed");
  4625. res.set_chunked_content_provider(
  4626. "text/plain",
  4627. [i](size_t /*offset*/, DataSink &sink) {
  4628. switch (*i) {
  4629. case 0: sink.os << "123"; break;
  4630. case 1: sink.os << "456"; break;
  4631. case 2: sink.os << "789"; break;
  4632. case 3: {
  4633. sink.done_with_trailer(
  4634. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4635. } break;
  4636. }
  4637. (*i)++;
  4638. return true;
  4639. },
  4640. [i](bool success) {
  4641. EXPECT_TRUE(success);
  4642. delete i;
  4643. });
  4644. })
  4645. .Get("/streamed-chunked2",
  4646. [&](const Request & /*req*/, Response &res) {
  4647. auto i = new int(0);
  4648. res.set_chunked_content_provider(
  4649. "text/plain",
  4650. [i](size_t /*offset*/, DataSink &sink) {
  4651. switch (*i) {
  4652. case 0: sink.os << "123"; break;
  4653. case 1: sink.os << "456"; break;
  4654. case 2: sink.os << "789"; break;
  4655. case 3: sink.done(); break;
  4656. }
  4657. (*i)++;
  4658. return true;
  4659. },
  4660. [i](bool success) {
  4661. EXPECT_TRUE(success);
  4662. delete i;
  4663. });
  4664. })
  4665. .Get("/streamed-chunked-with-trailer",
  4666. [&](const Request & /*req*/, Response &res) {
  4667. auto i = new int(0);
  4668. res.set_header("Trailer", "Dummy1, Dummy2");
  4669. res.set_chunked_content_provider(
  4670. "text/plain",
  4671. [i](size_t /*offset*/, DataSink &sink) {
  4672. switch (*i) {
  4673. case 0: sink.os << "123"; break;
  4674. case 1: sink.os << "456"; break;
  4675. case 2: sink.os << "789"; break;
  4676. case 3: {
  4677. sink.done_with_trailer(
  4678. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4679. } break;
  4680. }
  4681. (*i)++;
  4682. return true;
  4683. },
  4684. [i](bool success) {
  4685. EXPECT_TRUE(success);
  4686. delete i;
  4687. });
  4688. })
  4689. .Get("/streamed",
  4690. [&](const Request & /*req*/, Response &res) {
  4691. res.set_content_provider(
  4692. 6, "text/plain",
  4693. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4694. sink.os << (offset < 3 ? "a" : "b");
  4695. return true;
  4696. });
  4697. })
  4698. .Get("/streamed-without-length",
  4699. [&](const Request & /*req*/, Response &res) {
  4700. auto data = new std::string("abcdefg");
  4701. res.set_content_provider(
  4702. "text/plain",
  4703. [data](size_t offset, DataSink &sink) {
  4704. if (offset < data->size()) {
  4705. sink.os << data->substr(offset);
  4706. }
  4707. sink.done();
  4708. return true;
  4709. },
  4710. [data](bool success) {
  4711. EXPECT_TRUE(success);
  4712. delete data;
  4713. });
  4714. })
  4715. .Get("/streamed-with-range",
  4716. [&](const Request &req, Response &res) {
  4717. auto data = new std::string("abcdefg");
  4718. // An explicit status keeps the server from picking the 206 it
  4719. // would otherwise choose for a ranged request, so the response
  4720. // is not a partial representation.
  4721. auto status = req.get_param_value("status");
  4722. if (status == "200") {
  4723. res.status = StatusCode::OK_200;
  4724. } else if (status == "403") {
  4725. res.status = StatusCode::Forbidden_403;
  4726. }
  4727. res.set_content_provider(
  4728. data->size(), "text/plain",
  4729. [data](size_t offset, size_t length, DataSink &sink) {
  4730. size_t DATA_CHUNK_SIZE = 4;
  4731. const auto &d = *data;
  4732. auto out_len =
  4733. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4734. auto ret =
  4735. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4736. EXPECT_TRUE(ret);
  4737. return true;
  4738. },
  4739. [data, &req](bool success) {
  4740. EXPECT_EQ(success, !req.has_param("error"));
  4741. delete data;
  4742. });
  4743. })
  4744. .Get("/streamed-cancel",
  4745. [&](const Request & /*req*/, Response &res) {
  4746. res.set_content_provider(
  4747. size_t(-1), "text/plain",
  4748. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4749. sink.os << "data_chunk";
  4750. return true;
  4751. });
  4752. })
  4753. .Get("/regex-with-delimiter",
  4754. [&](const Request &req, Response & /*res*/) {
  4755. ASSERT_TRUE(req.has_param("key"));
  4756. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4757. })
  4758. .Get("/with-range",
  4759. [&](const Request & /*req*/, Response &res) {
  4760. res.set_content("abcdefg", "text/plain");
  4761. })
  4762. .Get("/test-start-time",
  4763. [&](const Request &req, Response & /*res*/) {
  4764. EXPECT_NE(req.start_time_,
  4765. std::chrono::steady_clock::time_point::min());
  4766. })
  4767. .Get("/with-range-customized-response",
  4768. [&](const Request & /*req*/, Response &res) {
  4769. res.status = StatusCode::BadRequest_400;
  4770. res.set_content(JSON_DATA, "application/json");
  4771. })
  4772. .Post("/chunked",
  4773. [&](const Request &req, Response & /*res*/) {
  4774. EXPECT_EQ(req.body, "dechunked post body");
  4775. })
  4776. .Post("/large-chunked",
  4777. [&](const Request &req, Response & /*res*/) {
  4778. std::string expected(6 * 30 * 1024u, 'a');
  4779. EXPECT_EQ(req.body, expected);
  4780. })
  4781. .Post("/multipart",
  4782. [&](const Request &req, Response & /*res*/) {
  4783. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4784. req.form.get_field_count("text2") +
  4785. req.form.get_field_count("file3") +
  4786. req.form.get_field_count("file4"));
  4787. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4788. req.form.get_file_count("file2"));
  4789. ASSERT_TRUE(!req.form.has_file("???"));
  4790. ASSERT_TRUE(!req.form.has_field("???"));
  4791. ASSERT_TRUE(req.body.empty());
  4792. {
  4793. const auto &text = req.form.get_field("text1");
  4794. EXPECT_EQ("text default", text);
  4795. }
  4796. {
  4797. const auto &text = req.form.get_field("text2");
  4798. EXPECT_EQ("aωb", text);
  4799. }
  4800. {
  4801. const auto &file = req.form.get_file("file1");
  4802. EXPECT_EQ("hello.txt", file.filename);
  4803. EXPECT_EQ("text/plain", file.content_type);
  4804. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4805. }
  4806. {
  4807. const auto &file = req.form.get_file("file2");
  4808. EXPECT_EQ("world.json", file.filename);
  4809. EXPECT_EQ("application/json", file.content_type);
  4810. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4811. }
  4812. {
  4813. const auto &text = req.form.get_field("file3");
  4814. EXPECT_EQ(0u, text.size());
  4815. }
  4816. {
  4817. const auto &text = req.form.get_field("file4");
  4818. EXPECT_EQ(0u, text.size());
  4819. }
  4820. })
  4821. .Post("/multipart/multi_file_values",
  4822. [&](const Request &req, Response & /*res*/) {
  4823. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4824. req.form.get_field_count("multi_text1"));
  4825. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4826. ASSERT_TRUE(!req.form.has_file("???"));
  4827. ASSERT_TRUE(!req.form.has_field("???"));
  4828. ASSERT_TRUE(req.body.empty());
  4829. {
  4830. const auto &text = req.form.get_field("text");
  4831. EXPECT_EQ("default text", text);
  4832. }
  4833. {
  4834. const auto &text1_values = req.form.get_fields("multi_text1");
  4835. EXPECT_EQ(2u, text1_values.size());
  4836. EXPECT_EQ("aaaaa", text1_values[0]);
  4837. EXPECT_EQ("bbbbb", text1_values[1]);
  4838. }
  4839. {
  4840. const auto &file1_values = req.form.get_files("multi_file1");
  4841. EXPECT_EQ(2u, file1_values.size());
  4842. auto file1 = file1_values[0];
  4843. EXPECT_EQ(file1.filename, "hello.txt");
  4844. EXPECT_EQ(file1.content_type, "text/plain");
  4845. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4846. auto file2 = file1_values[1];
  4847. EXPECT_EQ(file2.filename, "world.json");
  4848. EXPECT_EQ(file2.content_type, "application/json");
  4849. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4850. }
  4851. })
  4852. .Post("/empty",
  4853. [&](const Request &req, Response &res) {
  4854. EXPECT_EQ(req.body, "");
  4855. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4856. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4857. res.set_content("empty", "text/plain");
  4858. })
  4859. .Post("/empty-no-content-type",
  4860. [&](const Request &req, Response &res) {
  4861. EXPECT_EQ(req.body, "");
  4862. EXPECT_FALSE(req.has_header("Content-Type"));
  4863. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4864. res.set_content("empty-no-content-type", "text/plain");
  4865. })
  4866. .Post("/path-only",
  4867. [&](const Request &req, Response &res) {
  4868. EXPECT_EQ(req.body, "");
  4869. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4870. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4871. res.set_content("path-only", "text/plain");
  4872. })
  4873. .Post("/path-headers-only",
  4874. [&](const Request &req, Response &res) {
  4875. EXPECT_EQ(req.body, "");
  4876. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4877. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4878. EXPECT_EQ("world", req.get_header_value("hello"));
  4879. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4880. res.set_content("path-headers-only", "text/plain");
  4881. })
  4882. .Post("/post-large",
  4883. [&](const Request &req, Response &res) {
  4884. EXPECT_EQ(req.body, LARGE_DATA);
  4885. res.set_content(req.body, "text/plain");
  4886. })
  4887. .Post("/post-loopback",
  4888. [&](const Request &, Response &res,
  4889. ContentReader const &content_reader) {
  4890. std::string body;
  4891. content_reader([&](const char *data, size_t data_length) {
  4892. body.append(data, data_length);
  4893. return true;
  4894. });
  4895. res.set_content(body, "text/plain");
  4896. })
  4897. .Put("/put-loopback",
  4898. [&](const Request &, Response &res,
  4899. ContentReader const &content_reader) {
  4900. std::string body;
  4901. content_reader([&](const char *data, size_t data_length) {
  4902. body.append(data, data_length);
  4903. return true;
  4904. });
  4905. res.set_content(body, "text/plain");
  4906. })
  4907. .Patch("/patch-loopback",
  4908. [&](const Request &, Response &res,
  4909. ContentReader const &content_reader) {
  4910. std::string body;
  4911. content_reader([&](const char *data, size_t data_length) {
  4912. body.append(data, data_length);
  4913. return true;
  4914. });
  4915. res.set_content(body, "text/plain");
  4916. })
  4917. .Put("/empty-no-content-type",
  4918. [&](const Request &req, Response &res) {
  4919. EXPECT_EQ(req.body, "");
  4920. EXPECT_FALSE(req.has_header("Content-Type"));
  4921. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4922. res.set_content("empty-no-content-type", "text/plain");
  4923. })
  4924. .Put("/put",
  4925. [&](const Request &req, Response &res) {
  4926. EXPECT_EQ(req.body, "PUT");
  4927. res.set_content(req.body, "text/plain");
  4928. })
  4929. .Put("/put-large",
  4930. [&](const Request &req, Response &res) {
  4931. EXPECT_EQ(req.body, LARGE_DATA);
  4932. res.set_content(req.body, "text/plain");
  4933. })
  4934. .Patch("/patch",
  4935. [&](const Request &req, Response &res) {
  4936. EXPECT_EQ(req.body, "PATCH");
  4937. res.set_content(req.body, "text/plain");
  4938. })
  4939. .Delete("/delete",
  4940. [&](const Request & /*req*/, Response &res) {
  4941. res.set_content("DELETE", "text/plain");
  4942. })
  4943. .Delete("/delete-body",
  4944. [&](const Request &req, Response &res) {
  4945. EXPECT_EQ(req.body, "content");
  4946. res.set_content(req.body, "text/plain");
  4947. })
  4948. .Options(R"(\*)",
  4949. [&](const Request & /*req*/, Response &res) {
  4950. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4951. })
  4952. .CustomRoute("PROPFIND", "/dav/:id",
  4953. [&](const Request &req, Response &res) {
  4954. res.set_header("x-body-size",
  4955. std::to_string(req.body.size()));
  4956. res.set_header("x-matched-route", req.matched_route);
  4957. res.set_header("x-dav-id", req.path_params.at("id"));
  4958. res.status = StatusCode::MultiStatus_207;
  4959. res.set_content(req.body, "application/xml");
  4960. })
  4961. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4962. [&](const Request &req, Response &res) {
  4963. res.set_header("x-dav-match", req.matches[1]);
  4964. res.status = StatusCode::MultiStatus_207;
  4965. })
  4966. .CustomRoute("MKCOL", "/dav-mkcol",
  4967. [&](const Request &req, Response &res) {
  4968. EXPECT_TRUE(req.body.empty());
  4969. res.status = StatusCode::Created_201;
  4970. })
  4971. .CustomRoute(
  4972. "REPORT", "/dav-report",
  4973. [&](const Request & /*req*/, Response &res,
  4974. const ContentReader &content_reader) {
  4975. std::string body;
  4976. content_reader([&](const char *data, size_t data_length) {
  4977. body.append(data, data_length);
  4978. return true;
  4979. });
  4980. res.set_header("x-body-size", std::to_string(body.size()));
  4981. res.status = StatusCode::MultiStatus_207;
  4982. res.set_content(body, "application/xml");
  4983. })
  4984. .Get("/request-target",
  4985. [&](const Request &req, Response & /*res*/) {
  4986. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4987. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4988. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4989. })
  4990. .Get("/long-query-value",
  4991. [&](const Request &req, Response & /*res*/) {
  4992. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4993. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4994. })
  4995. .Get("/too-long-query-value",
  4996. [&](const Request &req, Response & /*res*/) {
  4997. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4998. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4999. })
  5000. .Get("/array-param",
  5001. [&](const Request &req, Response & /*res*/) {
  5002. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5003. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5004. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5005. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5006. })
  5007. .Get("/array-param-values",
  5008. [&](const Request &req, Response & /*res*/) {
  5009. auto values = req.get_param_values("array");
  5010. EXPECT_EQ(3u, values.size());
  5011. EXPECT_EQ("value1", values[0]);
  5012. EXPECT_EQ("value2", values[1]);
  5013. EXPECT_EQ("value3", values[2]);
  5014. auto empty = req.get_param_values("nonexistent");
  5015. EXPECT_TRUE(empty.empty());
  5016. })
  5017. .Post("/validate-no-multiple-headers",
  5018. [&](const Request &req, Response & /*res*/) {
  5019. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5020. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5021. })
  5022. .Post("/content_receiver",
  5023. [&](const Request &req, Response &res,
  5024. const ContentReader &content_reader) {
  5025. if (req.is_multipart_form_data()) {
  5026. std::vector<FormData> items;
  5027. content_reader(
  5028. [&](const FormData &file) {
  5029. items.push_back(file);
  5030. return true;
  5031. },
  5032. [&](const char *data, size_t data_length) {
  5033. items.back().content.append(data, data_length);
  5034. return true;
  5035. });
  5036. EXPECT_EQ(5u, items.size());
  5037. {
  5038. const auto &file = get_file_value(items, "text1");
  5039. EXPECT_TRUE(file.filename.empty());
  5040. EXPECT_EQ("text default", file.content);
  5041. }
  5042. {
  5043. const auto &file = get_file_value(items, "text2");
  5044. EXPECT_TRUE(file.filename.empty());
  5045. EXPECT_EQ("aωb", file.content);
  5046. }
  5047. {
  5048. const auto &file = get_file_value(items, "file1");
  5049. EXPECT_EQ("hello.txt", file.filename);
  5050. EXPECT_EQ("text/plain", file.content_type);
  5051. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5052. }
  5053. {
  5054. const auto &file = get_file_value(items, "file2");
  5055. EXPECT_EQ("world.json", file.filename);
  5056. EXPECT_EQ("application/json", file.content_type);
  5057. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5058. }
  5059. {
  5060. const auto &file = get_file_value(items, "file3");
  5061. EXPECT_TRUE(file.filename.empty());
  5062. EXPECT_EQ("application/octet-stream", file.content_type);
  5063. EXPECT_EQ(0u, file.content.size());
  5064. }
  5065. } else {
  5066. std::string body;
  5067. content_reader([&](const char *data, size_t data_length) {
  5068. EXPECT_EQ(7U, data_length);
  5069. body.append(data, data_length);
  5070. return true;
  5071. });
  5072. EXPECT_EQ(body, "content");
  5073. res.set_content(body, "text/plain");
  5074. }
  5075. })
  5076. .Put("/content_receiver",
  5077. [&](const Request & /*req*/, Response &res,
  5078. const ContentReader &content_reader) {
  5079. std::string body;
  5080. content_reader([&](const char *data, size_t data_length) {
  5081. body.append(data, data_length);
  5082. return true;
  5083. });
  5084. EXPECT_EQ(body, "content");
  5085. res.set_content(body, "text/plain");
  5086. })
  5087. .Patch("/content_receiver",
  5088. [&](const Request & /*req*/, Response &res,
  5089. const ContentReader &content_reader) {
  5090. std::string body;
  5091. content_reader([&](const char *data, size_t data_length) {
  5092. body.append(data, data_length);
  5093. return true;
  5094. });
  5095. EXPECT_EQ(body, "content");
  5096. res.set_content(body, "text/plain");
  5097. })
  5098. .Post("/query-string-and-body",
  5099. [&](const Request &req, Response & /*res*/) {
  5100. ASSERT_TRUE(req.has_param("key"));
  5101. EXPECT_EQ(req.get_param_value("key"), "value");
  5102. EXPECT_EQ(req.body, "content");
  5103. })
  5104. .Get("/last-request",
  5105. [&](const Request &req, Response & /*res*/) {
  5106. EXPECT_EQ("close", req.get_header_value("Connection"));
  5107. })
  5108. .Get(R"(/redirect/(\d+))",
  5109. [&](const Request &req, Response &res) {
  5110. auto num = std::stoi(req.matches[1]) + 1;
  5111. std::string url = "/redirect/" + std::to_string(num);
  5112. res.set_redirect(url);
  5113. })
  5114. .Post("/binary",
  5115. [&](const Request &req, Response &res) {
  5116. EXPECT_EQ(4U, req.body.size());
  5117. EXPECT_EQ("application/octet-stream",
  5118. req.get_header_value("Content-Type"));
  5119. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5120. res.set_content(req.body, "application/octet-stream");
  5121. })
  5122. .Put("/binary",
  5123. [&](const Request &req, Response &res) {
  5124. EXPECT_EQ(4U, req.body.size());
  5125. EXPECT_EQ("application/octet-stream",
  5126. req.get_header_value("Content-Type"));
  5127. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5128. res.set_content(req.body, "application/octet-stream");
  5129. })
  5130. .Patch("/binary",
  5131. [&](const Request &req, Response &res) {
  5132. EXPECT_EQ(4U, req.body.size());
  5133. EXPECT_EQ("application/octet-stream",
  5134. req.get_header_value("Content-Type"));
  5135. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5136. res.set_content(req.body, "application/octet-stream");
  5137. })
  5138. .Delete("/binary",
  5139. [&](const Request &req, Response &res) {
  5140. EXPECT_EQ(4U, req.body.size());
  5141. EXPECT_EQ("application/octet-stream",
  5142. req.get_header_value("Content-Type"));
  5143. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5144. res.set_content(req.body, "application/octet-stream");
  5145. })
  5146. .Get("/issue1772",
  5147. [&](const Request & /*req*/, Response &res) {
  5148. res.status = 401;
  5149. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5150. })
  5151. .Delete("/issue609",
  5152. [](const httplib::Request &, httplib::Response &res,
  5153. const httplib::ContentReader &) {
  5154. res.set_content("ok", "text/plain");
  5155. })
  5156. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5157. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5158. .Get("/compress",
  5159. [&](const Request & /*req*/, Response &res) {
  5160. res.set_content(
  5161. "12345678901234567890123456789012345678901234567890123456789"
  5162. "01234567890123456789012345678901234567890",
  5163. "text/plain");
  5164. })
  5165. .Get("/compress-with-charset",
  5166. [&](const Request & /*req*/, Response &res) {
  5167. res.set_content(
  5168. "12345678901234567890123456789012345678901234567890123456789"
  5169. "01234567890123456789012345678901234567890",
  5170. "application/json; charset=utf-8");
  5171. })
  5172. .Get("/nocompress",
  5173. [&](const Request & /*req*/, Response &res) {
  5174. res.set_content(
  5175. "12345678901234567890123456789012345678901234567890123456789"
  5176. "01234567890123456789012345678901234567890",
  5177. "application/octet-stream");
  5178. })
  5179. .Post("/compress-multipart",
  5180. [&](const Request &req, Response & /*res*/) {
  5181. EXPECT_EQ(2u, req.form.fields.size());
  5182. ASSERT_TRUE(!req.form.has_field("???"));
  5183. {
  5184. const auto &text = req.form.get_field("key1");
  5185. EXPECT_EQ("test", text);
  5186. }
  5187. {
  5188. const auto &text = req.form.get_field("key2");
  5189. EXPECT_EQ("--abcdefg123", text);
  5190. }
  5191. })
  5192. #endif
  5193. ;
  5194. persons_["john"] = "programmer";
  5195. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5196. svr_.wait_until_ready();
  5197. }
  5198. virtual void TearDown() {
  5199. svr_.stop();
  5200. if (!request_threads_.empty()) {
  5201. std::this_thread::sleep_for(std::chrono::seconds(1));
  5202. for (auto &t : request_threads_) {
  5203. t.join();
  5204. }
  5205. }
  5206. t_.join();
  5207. }
  5208. map<string, string> persons_;
  5209. #ifdef CPPHTTPLIB_SSL_ENABLED
  5210. SSLClient cli_;
  5211. SSLServer svr_;
  5212. #else
  5213. Client cli_;
  5214. Server svr_;
  5215. #endif
  5216. thread t_;
  5217. std::vector<thread> request_threads_;
  5218. };
  5219. TEST_F(ServerTest, GetMethod200) {
  5220. auto res = cli_.Get("/hi");
  5221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5222. EXPECT_EQ("HTTP/1.1", res->version);
  5223. EXPECT_EQ(StatusCode::OK_200, res->status);
  5224. EXPECT_EQ("OK", res->reason);
  5225. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5226. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5227. EXPECT_EQ("Hello World!", res->body);
  5228. }
  5229. TEST_F(ServerTest, GetEmptyFile) {
  5230. auto res = cli_.Get("/empty_file");
  5231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5232. EXPECT_EQ(StatusCode::OK_200, res->status);
  5233. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5234. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5235. EXPECT_EQ("", res->body);
  5236. }
  5237. TEST_F(ServerTest, GetFileContent) {
  5238. auto res = cli_.Get("/file_content");
  5239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5240. EXPECT_EQ(StatusCode::OK_200, res->status);
  5241. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5242. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5243. EXPECT_EQ("test.html", res->body);
  5244. }
  5245. TEST_F(ServerTest, GetFileContentWithRange) {
  5246. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5248. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5249. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5250. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5251. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5252. EXPECT_EQ("est", res->body);
  5253. }
  5254. TEST_F(ServerTest, GetFileContentWithContentType) {
  5255. auto res = cli_.Get("/file_content_with_content_type");
  5256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5257. EXPECT_EQ(StatusCode::OK_200, res->status);
  5258. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5259. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5260. EXPECT_EQ("file\n", res->body);
  5261. }
  5262. TEST_F(ServerTest, GetInvalidFileContent) {
  5263. auto res = cli_.Get("/invalid_file_content");
  5264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5265. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5266. }
  5267. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5268. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5270. EXPECT_EQ("HTTP/1.1", res->version);
  5271. EXPECT_EQ(StatusCode::OK_200, res->status);
  5272. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5273. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5274. EXPECT_EQ("Hello World!", res->body);
  5275. }
  5276. TEST_F(ServerTest, GetMethod302) {
  5277. auto res = cli_.Get("/");
  5278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5279. EXPECT_EQ(StatusCode::Found_302, res->status);
  5280. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5281. }
  5282. TEST_F(ServerTest, GetMethod302Redirect) {
  5283. cli_.set_follow_location(true);
  5284. auto res = cli_.Get("/");
  5285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5286. EXPECT_EQ(StatusCode::OK_200, res->status);
  5287. EXPECT_EQ("Hello World!", res->body);
  5288. EXPECT_EQ("/hi", res->location);
  5289. }
  5290. TEST_F(ServerTest, GetMethod404) {
  5291. auto res = cli_.Get("/invalid");
  5292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5293. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5294. }
  5295. TEST_F(ServerTest, HeadMethod200) {
  5296. auto res = cli_.Head("/hi");
  5297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5298. EXPECT_EQ(StatusCode::OK_200, res->status);
  5299. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5300. EXPECT_TRUE(res->body.empty());
  5301. }
  5302. TEST_F(ServerTest, HeadMethod200Static) {
  5303. auto res = cli_.Head("/mount/dir/index.html");
  5304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5305. EXPECT_EQ(StatusCode::OK_200, res->status);
  5306. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5307. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5308. EXPECT_TRUE(res->body.empty());
  5309. }
  5310. TEST_F(ServerTest, HeadMethod404) {
  5311. auto res = cli_.Head("/invalid");
  5312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5313. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5314. EXPECT_TRUE(res->body.empty());
  5315. }
  5316. TEST_F(ServerTest, GetMethodPersonJohn) {
  5317. auto res = cli_.Get("/person/john");
  5318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5319. EXPECT_EQ(StatusCode::OK_200, res->status);
  5320. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5321. EXPECT_EQ("programmer", res->body);
  5322. }
  5323. TEST_F(ServerTest, PostMethod1) {
  5324. auto res = cli_.Get("/person/john1");
  5325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5326. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5327. res = cli_.Post("/person", "name=john1&note=coder",
  5328. "application/x-www-form-urlencoded");
  5329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5330. ASSERT_EQ(StatusCode::OK_200, res->status);
  5331. res = cli_.Get("/person/john1");
  5332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5333. ASSERT_EQ(StatusCode::OK_200, res->status);
  5334. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5335. ASSERT_EQ("coder", res->body);
  5336. }
  5337. TEST_F(ServerTest, PostMethod2) {
  5338. auto res = cli_.Get("/person/john2");
  5339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5340. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5341. Params params;
  5342. params.emplace("name", "john2");
  5343. params.emplace("note", "coder");
  5344. res = cli_.Post("/person", params);
  5345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5346. ASSERT_EQ(StatusCode::OK_200, res->status);
  5347. res = cli_.Get("/person/john2");
  5348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5349. ASSERT_EQ(StatusCode::OK_200, res->status);
  5350. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5351. ASSERT_EQ("coder", res->body);
  5352. }
  5353. TEST_F(ServerTest, PutMethod3) {
  5354. auto res = cli_.Get("/person/john3");
  5355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5356. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5357. Params params;
  5358. params.emplace("name", "john3");
  5359. params.emplace("note", "coder");
  5360. res = cli_.Put("/person", params);
  5361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5362. ASSERT_EQ(StatusCode::OK_200, res->status);
  5363. res = cli_.Get("/person/john3");
  5364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5365. ASSERT_EQ(StatusCode::OK_200, res->status);
  5366. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5367. ASSERT_EQ("coder", res->body);
  5368. }
  5369. TEST_F(ServerTest, DeleteMethod1) {
  5370. auto res = cli_.Get("/person/john4");
  5371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5372. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5373. Params params;
  5374. params.emplace("name", "john4");
  5375. params.emplace("note", "coder");
  5376. res = cli_.Post("/person", params);
  5377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5378. ASSERT_EQ(StatusCode::OK_200, res->status);
  5379. res = cli_.Get("/person/john4");
  5380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5381. ASSERT_EQ(StatusCode::OK_200, res->status);
  5382. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5383. ASSERT_EQ("coder", res->body);
  5384. Params delete_params;
  5385. delete_params.emplace("name", "john4");
  5386. res = cli_.Delete("/person", delete_params);
  5387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5388. ASSERT_EQ(StatusCode::OK_200, res->status);
  5389. ASSERT_EQ("DELETED", res->body);
  5390. res = cli_.Get("/person/john4");
  5391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5392. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5393. }
  5394. TEST_F(ServerTest, DeleteMethod2) {
  5395. auto res = cli_.Get("/person/john5");
  5396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5397. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5398. Params params;
  5399. params.emplace("name", "john5");
  5400. params.emplace("note", "developer");
  5401. res = cli_.Post("/person", params);
  5402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5403. ASSERT_EQ(StatusCode::OK_200, res->status);
  5404. res = cli_.Get("/person/john5");
  5405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5406. ASSERT_EQ(StatusCode::OK_200, res->status);
  5407. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5408. ASSERT_EQ("developer", res->body);
  5409. Params delete_params;
  5410. delete_params.emplace("name", "john5");
  5411. Headers headers;
  5412. headers.emplace("Custom-Header", "test-value");
  5413. res = cli_.Delete("/person", headers, delete_params);
  5414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5415. ASSERT_EQ(StatusCode::OK_200, res->status);
  5416. ASSERT_EQ("DELETED", res->body);
  5417. res = cli_.Get("/person/john5");
  5418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5419. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5420. }
  5421. TEST_F(ServerTest, DeleteMethod3) {
  5422. auto res = cli_.Get("/person/john6");
  5423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5424. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5425. Params params;
  5426. params.emplace("name", "john6");
  5427. params.emplace("note", "tester");
  5428. res = cli_.Post("/person", params);
  5429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5430. ASSERT_EQ(StatusCode::OK_200, res->status);
  5431. res = cli_.Get("/person/john6");
  5432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5433. ASSERT_EQ(StatusCode::OK_200, res->status);
  5434. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5435. ASSERT_EQ("tester", res->body);
  5436. Params delete_params;
  5437. delete_params.emplace("name", "john6");
  5438. Headers headers;
  5439. headers.emplace("Custom-Header", "test-value");
  5440. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5442. ASSERT_EQ(StatusCode::OK_200, res->status);
  5443. ASSERT_EQ("DELETED", res->body);
  5444. res = cli_.Get("/person/john6");
  5445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5446. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5447. }
  5448. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5449. Params params;
  5450. params.emplace("json", JSON_DATA);
  5451. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5453. ASSERT_EQ(StatusCode::OK_200, res->status);
  5454. ASSERT_EQ(JSON_DATA, res->body);
  5455. }
  5456. TEST_F(ServerTest, PostEmptyContent) {
  5457. auto res = cli_.Post("/empty", "", "text/plain");
  5458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5459. ASSERT_EQ(StatusCode::OK_200, res->status);
  5460. ASSERT_EQ("empty", res->body);
  5461. }
  5462. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5463. auto res = cli_.Post("/empty-no-content-type");
  5464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5465. ASSERT_EQ(StatusCode::OK_200, res->status);
  5466. ASSERT_EQ("empty-no-content-type", res->body);
  5467. }
  5468. TEST_F(ServerTest, PostPathOnly) {
  5469. auto res = cli_.Post("/path-only");
  5470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5471. ASSERT_EQ(StatusCode::OK_200, res->status);
  5472. ASSERT_EQ("path-only", res->body);
  5473. }
  5474. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5475. auto res = cli_.Post("/path-headers-only",
  5476. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5478. ASSERT_EQ(StatusCode::OK_200, res->status);
  5479. ASSERT_EQ("path-headers-only", res->body);
  5480. }
  5481. TEST_F(ServerTest, PostLarge) {
  5482. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5484. ASSERT_EQ(StatusCode::OK_200, res->status);
  5485. EXPECT_EQ(LARGE_DATA, res->body);
  5486. }
  5487. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5488. auto res = cli_.Put("/empty-no-content-type");
  5489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5490. ASSERT_EQ(StatusCode::OK_200, res->status);
  5491. ASSERT_EQ("empty-no-content-type", res->body);
  5492. }
  5493. TEST_F(ServerTest, GetMethodDir) {
  5494. auto res = cli_.Get("/dir/");
  5495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5496. EXPECT_EQ(StatusCode::OK_200, res->status);
  5497. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5498. auto body = R"(<html>
  5499. <head>
  5500. </head>
  5501. <body>
  5502. <a href="/dir/test.html">Test</a>
  5503. <a href="/hi">hi</a>
  5504. </body>
  5505. </html>
  5506. )";
  5507. EXPECT_EQ(body, res->body);
  5508. }
  5509. TEST_F(ServerTest, GetMethodDirTest) {
  5510. auto res = cli_.Get("/dir/test.html");
  5511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5512. EXPECT_EQ(StatusCode::OK_200, res->status);
  5513. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5514. EXPECT_EQ("test.html", res->body);
  5515. }
  5516. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5517. auto res = cli_.Get("/dir/../dir/test.html");
  5518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5519. EXPECT_EQ(StatusCode::OK_200, res->status);
  5520. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5521. EXPECT_EQ("test.html", res->body);
  5522. }
  5523. TEST_F(ServerTest, GetMethodInvalidPath) {
  5524. auto res = cli_.Get("/dir/../test.html");
  5525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5526. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5527. }
  5528. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5529. auto res = cli_.Get("/../www/dir/test.html");
  5530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5531. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5532. }
  5533. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5534. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5536. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5537. }
  5538. TEST_F(ServerTest, GetMethodDirMountTest) {
  5539. auto res = cli_.Get("/mount/dir/test.html");
  5540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5541. EXPECT_EQ(StatusCode::OK_200, res->status);
  5542. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5543. EXPECT_EQ("test.html", res->body);
  5544. }
  5545. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5546. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5548. EXPECT_EQ(StatusCode::OK_200, res->status);
  5549. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5550. EXPECT_EQ("test.html", res->body);
  5551. }
  5552. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5553. auto res = cli_.Get("/mount/dir/../test.html");
  5554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5555. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5556. }
  5557. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5558. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5560. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5561. }
  5562. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5563. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5565. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5566. }
  5567. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5568. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5570. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5571. }
  5572. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5573. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5575. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5576. }
  5577. TEST_F(ServerTest, PostMethod303) {
  5578. auto res = cli_.Post("/1", "body", "text/plain");
  5579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5580. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5581. EXPECT_EQ("/2", res->get_header_value("Location"));
  5582. }
  5583. TEST_F(ServerTest, PostMethod303Redirect) {
  5584. cli_.set_follow_location(true);
  5585. auto res = cli_.Post("/1", "body", "text/plain");
  5586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5587. EXPECT_EQ(StatusCode::OK_200, res->status);
  5588. EXPECT_EQ("redirected.", res->body);
  5589. EXPECT_EQ("/2", res->location);
  5590. }
  5591. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5592. auto res = cli_.Get("/dir/test.abcde");
  5593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5594. EXPECT_EQ(StatusCode::OK_200, res->status);
  5595. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5596. EXPECT_EQ("abcde", res->body);
  5597. }
  5598. TEST_F(ServerTest, StaticFileRange) {
  5599. auto res =
  5600. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5602. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5603. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5604. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5605. EXPECT_EQ(true, res->has_header("Content-Range"));
  5606. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5607. EXPECT_EQ(std::string("cd"), res->body);
  5608. }
  5609. TEST_F(ServerTest, StaticFileRanges) {
  5610. auto res = cli_.Get("/dir/test.abcde",
  5611. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5613. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5614. EXPECT_TRUE(
  5615. res->get_header_value("Content-Type")
  5616. .find(
  5617. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5618. 0);
  5619. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5620. }
  5621. TEST_F(ServerTest, StaticFileRangeHead) {
  5622. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5624. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5625. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5626. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5627. EXPECT_EQ(true, res->has_header("Content-Range"));
  5628. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5629. }
  5630. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5631. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5633. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5634. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5635. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5636. EXPECT_EQ(true, res->has_header("Content-Range"));
  5637. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5638. res->get_header_value("Content-Range"));
  5639. EXPECT_EQ("LAST\n", res->body);
  5640. }
  5641. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5642. auto res =
  5643. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5645. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5646. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5647. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5648. EXPECT_EQ(true, res->has_header("Content-Range"));
  5649. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5650. }
  5651. TEST_F(ServerTest, StaticFileBigFile) {
  5652. auto res = cli_.Get("/dir/1MB.txt");
  5653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5654. EXPECT_EQ(StatusCode::OK_200, res->status);
  5655. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5656. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5657. }
  5658. TEST_F(ServerTest, InvalidBaseDirMount) {
  5659. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5660. }
  5661. TEST_F(ServerTest, Binary) {
  5662. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5663. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5664. "application/octet-stream");
  5665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5666. ASSERT_EQ(StatusCode::OK_200, res->status);
  5667. ASSERT_EQ(4U, res->body.size());
  5668. res = cli_.Put("/binary", binary.data(), binary.size(),
  5669. "application/octet-stream");
  5670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5671. ASSERT_EQ(StatusCode::OK_200, res->status);
  5672. ASSERT_EQ(4U, res->body.size());
  5673. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5674. "application/octet-stream");
  5675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5676. ASSERT_EQ(StatusCode::OK_200, res->status);
  5677. ASSERT_EQ(4U, res->body.size());
  5678. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5679. "application/octet-stream");
  5680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5681. ASSERT_EQ(StatusCode::OK_200, res->status);
  5682. ASSERT_EQ(4U, res->body.size());
  5683. }
  5684. TEST_F(ServerTest, BinaryString) {
  5685. auto binary = std::string("\x00\x01\x02\x03", 4);
  5686. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5688. ASSERT_EQ(StatusCode::OK_200, res->status);
  5689. ASSERT_EQ(4U, res->body.size());
  5690. res = cli_.Put("/binary", binary, "application/octet-stream");
  5691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5692. ASSERT_EQ(StatusCode::OK_200, res->status);
  5693. ASSERT_EQ(4U, res->body.size());
  5694. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5696. ASSERT_EQ(StatusCode::OK_200, res->status);
  5697. ASSERT_EQ(4U, res->body.size());
  5698. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5700. ASSERT_EQ(StatusCode::OK_200, res->status);
  5701. ASSERT_EQ(4U, res->body.size());
  5702. }
  5703. TEST_F(ServerTest, EmptyRequest) {
  5704. auto res = cli_.Get("");
  5705. ASSERT_TRUE(!res);
  5706. EXPECT_EQ(Error::Connection, res.error());
  5707. }
  5708. TEST_F(ServerTest, LongRequest) {
  5709. std::string request;
  5710. for (size_t i = 0; i < 545; i++) {
  5711. request += "/TooLongRequest";
  5712. }
  5713. request += "OK";
  5714. auto res = cli_.Get(request.c_str());
  5715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5716. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5717. }
  5718. TEST_F(ServerTest, TooLongRequest) {
  5719. std::string request;
  5720. for (size_t i = 0; i < 546; i++) {
  5721. request += "/TooLongRequest";
  5722. }
  5723. request += "_NG";
  5724. auto start = std::chrono::high_resolution_clock::now();
  5725. cli_.set_keep_alive(true);
  5726. auto res = cli_.Get(request.c_str());
  5727. auto end = std::chrono::high_resolution_clock::now();
  5728. auto elapsed =
  5729. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5730. .count();
  5731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5732. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5733. EXPECT_LE(elapsed, 1000);
  5734. EXPECT_EQ("close", res->get_header_value("Connection"));
  5735. EXPECT_FALSE(cli_.is_socket_open());
  5736. }
  5737. TEST_F(ServerTest, AlmostTooLongRequest) {
  5738. // test for #2046 - URI length check shouldn't include other content on req
  5739. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5740. // leading /, space, HTTP/1.1)
  5741. std::string request =
  5742. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5743. auto res = cli_.Get(request.c_str());
  5744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5745. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5746. }
  5747. TEST_F(ServerTest, LongHeader) {
  5748. Request req;
  5749. req.method = "GET";
  5750. req.path = "/hi";
  5751. std::string host_and_port;
  5752. host_and_port += HOST;
  5753. host_and_port += ":";
  5754. host_and_port += std::to_string(PORT);
  5755. req.headers.emplace("Host", host_and_port.c_str());
  5756. req.headers.emplace("Accept", "*/*");
  5757. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5758. req.headers.emplace(
  5759. "Header-Name",
  5760. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5761. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5762. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5763. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5764. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5765. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5766. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5767. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5768. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5769. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5770. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5771. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5772. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5773. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5774. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5775. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5776. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5777. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5778. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5779. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5780. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5781. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5782. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5783. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5786. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5787. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5788. "@@@@@@@@@@@@@@@@");
  5789. auto res = std::make_shared<Response>();
  5790. auto error = Error::Success;
  5791. auto ret = cli_.send(req, *res, error);
  5792. ASSERT_TRUE(ret);
  5793. EXPECT_EQ(StatusCode::OK_200, res->status);
  5794. }
  5795. TEST_F(ServerTest, LongQueryValue) {
  5796. auto start = std::chrono::high_resolution_clock::now();
  5797. cli_.set_keep_alive(true);
  5798. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5799. auto end = std::chrono::high_resolution_clock::now();
  5800. auto elapsed =
  5801. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5802. .count();
  5803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5804. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5805. EXPECT_LE(elapsed, 1000);
  5806. EXPECT_EQ("close", res->get_header_value("Connection"));
  5807. EXPECT_FALSE(cli_.is_socket_open());
  5808. }
  5809. TEST_F(ServerTest, TooLongQueryValue) {
  5810. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5811. ASSERT_FALSE(res);
  5812. EXPECT_EQ(Error::Read, res.error());
  5813. }
  5814. TEST_F(ServerTest, TooLongHeader) {
  5815. Request req;
  5816. req.method = "GET";
  5817. req.path = "/hi";
  5818. std::string host_and_port;
  5819. host_and_port += HOST;
  5820. host_and_port += ":";
  5821. host_and_port += std::to_string(PORT);
  5822. req.headers.emplace("Host", host_and_port.c_str());
  5823. req.headers.emplace("Accept", "*/*");
  5824. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5825. req.headers.emplace(
  5826. "Header-Name",
  5827. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5828. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5829. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5830. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5831. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5832. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5833. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5834. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5835. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5836. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5837. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5838. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5839. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5840. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5841. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5842. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5843. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5844. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5845. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5846. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5847. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5848. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5849. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5850. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5851. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5852. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5853. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5854. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5855. "@@@@@@@@@@@@@@@@@");
  5856. auto res = std::make_shared<Response>();
  5857. auto error = Error::Success;
  5858. auto ret = cli_.send(req, *res, error);
  5859. ASSERT_TRUE(ret);
  5860. EXPECT_EQ(StatusCode::OK_200, res->status);
  5861. }
  5862. TEST_F(ServerTest, HeaderCountAtLimit) {
  5863. // Test with headers just under the 100 limit
  5864. httplib::Headers headers;
  5865. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5866. // This should keep us just under the 100 header limit
  5867. for (int i = 0; i < 95; i++) {
  5868. std::string name = "X-Test-Header-" + std::to_string(i);
  5869. std::string value = "value" + std::to_string(i);
  5870. headers.emplace(name, value);
  5871. }
  5872. // This should work fine as we're under the limit
  5873. auto res = cli_.Get("/hi", headers);
  5874. EXPECT_TRUE(res);
  5875. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5876. }
  5877. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5878. // Test with many headers to exceed the 100 limit
  5879. httplib::Headers headers;
  5880. // Add 150 headers to definitely exceed the 100 limit
  5881. for (int i = 0; i < 150; i++) {
  5882. std::string name = "X-Test-Header-" + std::to_string(i);
  5883. std::string value = "value" + std::to_string(i);
  5884. headers.emplace(name, value);
  5885. }
  5886. // This should fail due to exceeding header count limit
  5887. cli_.set_keep_alive(true);
  5888. auto res = cli_.Get("/hi", headers);
  5889. // The server should respond with 400 Bad Request
  5890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5891. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5892. EXPECT_EQ("close", res->get_header_value("Connection"));
  5893. EXPECT_FALSE(cli_.is_socket_open());
  5894. }
  5895. TEST_F(ServerTest, PercentEncoding) {
  5896. auto res = cli_.Get("/e%6edwith%");
  5897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5898. EXPECT_EQ(StatusCode::OK_200, res->status);
  5899. }
  5900. TEST_F(ServerTest, PercentEncodingUnicode) {
  5901. auto res = cli_.Get("/e%u006edwith%");
  5902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5903. EXPECT_EQ(StatusCode::OK_200, res->status);
  5904. }
  5905. TEST_F(ServerTest, InvalidPercentEncoding) {
  5906. auto res = cli_.Get("/%endwith%");
  5907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5908. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5909. }
  5910. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5911. auto res = cli_.Get("/%uendwith%");
  5912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5913. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5914. }
  5915. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5916. auto res = cli_.Get("/hello?aaa=bbb%");
  5917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5918. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5919. }
  5920. TEST_F(ServerTest, PlusSignEncoding) {
  5921. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5923. EXPECT_EQ(StatusCode::OK_200, res->status);
  5924. EXPECT_EQ("a +b", res->body);
  5925. }
  5926. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5927. // This test simulates a potential DoS attack using many headers
  5928. // to verify our security fix prevents memory exhaustion
  5929. httplib::Headers attack_headers;
  5930. // Attempt to add many headers like an attacker would (200 headers to far
  5931. // exceed limit)
  5932. for (int i = 0; i < 200; i++) {
  5933. std::string name = "X-Attack-Header-" + std::to_string(i);
  5934. std::string value = "attack_payload_" + std::to_string(i);
  5935. attack_headers.emplace(name, value);
  5936. }
  5937. // Try to POST with excessive headers
  5938. cli_.set_keep_alive(true);
  5939. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5940. // Should either fail or return 400 Bad Request due to security limit
  5941. if (res) {
  5942. // If we get a response, it should be 400 Bad Request
  5943. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5944. EXPECT_EQ("close", res->get_header_value("Connection"));
  5945. }
  5946. EXPECT_FALSE(cli_.is_socket_open());
  5947. }
  5948. TEST_F(ServerTest, MultipartFormData) {
  5949. UploadFormDataItems items = {
  5950. {"text1", "text default", "", ""},
  5951. {"text2", "aωb", "", ""},
  5952. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5953. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5954. {"file3", "", "", "application/octet-stream"},
  5955. {"file4", "", "", " application/json tmp-string "}};
  5956. auto res = cli_.Post("/multipart", items);
  5957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5958. EXPECT_EQ(StatusCode::OK_200, res->status);
  5959. }
  5960. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5961. UploadFormDataItems items = {
  5962. {"text", "default text", "", ""},
  5963. {"multi_text1", "aaaaa", "", ""},
  5964. {"multi_text1", "bbbbb", "", ""},
  5965. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5966. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5967. "application/json"},
  5968. };
  5969. auto res = cli_.Post("/multipart/multi_file_values", items);
  5970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5971. EXPECT_EQ(StatusCode::OK_200, res->status);
  5972. }
  5973. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5974. auto res = cli_.Get("/hi");
  5975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5976. EXPECT_EQ(StatusCode::OK_200, res->status);
  5977. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5978. EXPECT_EQ("Hello World!", res->body);
  5979. }
  5980. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5981. Request req;
  5982. req.method = "POST";
  5983. req.path = "/chunked";
  5984. std::string host_and_port;
  5985. host_and_port += HOST;
  5986. host_and_port += ":";
  5987. host_and_port += std::to_string(PORT);
  5988. req.headers.emplace("Host", host_and_port.c_str());
  5989. req.headers.emplace("Accept", "*/*");
  5990. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5991. req.headers.emplace("Content-Type", "text/plain");
  5992. req.headers.emplace("Content-Length", "0");
  5993. req.headers.emplace(
  5994. "Transfer-Encoding",
  5995. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5996. // Client does not chunk, so make a chunked body manually.
  5997. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5998. auto res = std::make_shared<Response>();
  5999. auto error = Error::Success;
  6000. auto ret = cli_.send(req, *res, error);
  6001. ASSERT_TRUE(ret);
  6002. EXPECT_EQ(StatusCode::OK_200, res->status);
  6003. }
  6004. template <typename ClientT>
  6005. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6006. int expected_status) {
  6007. Request req;
  6008. req.method = "POST";
  6009. req.path = "/chunked";
  6010. std::string host_and_port;
  6011. host_and_port += HOST;
  6012. host_and_port += ":";
  6013. host_and_port += std::to_string(PORT);
  6014. req.headers.emplace("Host", host_and_port.c_str());
  6015. req.headers.emplace("Content-Length", "0");
  6016. req.headers.emplace("Transfer-Encoding", "chunked");
  6017. req.body = body;
  6018. auto res = std::make_shared<Response>();
  6019. auto error = Error::Success;
  6020. ASSERT_TRUE(cli.send(req, *res, error));
  6021. EXPECT_EQ(expected_status, res->status);
  6022. }
  6023. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6024. // rather than treat them as valid lengths.
  6025. template <typename ClientT>
  6026. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6027. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6028. }
  6029. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6030. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6031. }
  6032. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6033. expect_chunked_body_rejected(
  6034. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6035. }
  6036. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6037. // chunk-size line carries no CR, LF or other control character ahead of its
  6038. // terminator. Such a line must be refused rather than read as extension text.
  6039. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6040. expect_chunked_body_rejected(
  6041. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6042. }
  6043. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6044. expect_chunked_body_rejected(
  6045. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6046. }
  6047. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6048. expect_chunked_body_rejected(
  6049. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6050. }
  6051. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6052. // The literal stays split: a hex escape consumes every hex digit that
  6053. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6054. expect_chunked_body_rejected(
  6055. cli_, "4;a\x01"
  6056. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6057. }
  6058. TEST_F(ServerTest, AcceptsChunkExtension) {
  6059. expect_chunked_body_status(cli_,
  6060. "4;name=value\r\ndech\r\n"
  6061. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6062. "0;last\r\n\r\n",
  6063. StatusCode::OK_200);
  6064. }
  6065. TEST_F(ServerTest, GetStreamed2) {
  6066. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6068. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6069. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6070. EXPECT_EQ(true, res->has_header("Content-Range"));
  6071. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6072. EXPECT_EQ(std::string("ab"), res->body);
  6073. }
  6074. TEST_F(ServerTest, GetStreamed) {
  6075. auto res = cli_.Get("/streamed");
  6076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6077. EXPECT_EQ(StatusCode::OK_200, res->status);
  6078. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6079. EXPECT_EQ(std::string("aaabbb"), res->body);
  6080. }
  6081. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6082. auto res = cli_.Get("/streamed-without-length",
  6083. Headers{make_range_header({{0, -1}})});
  6084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6085. EXPECT_EQ(StatusCode::OK_200, res->status);
  6086. EXPECT_EQ(false, res->has_header("Content-Length"));
  6087. EXPECT_EQ(false, res->has_header("Content-Range"));
  6088. EXPECT_EQ(std::string("abcdefg"), res->body);
  6089. }
  6090. TEST_F(ServerTest, GetStreamedWithRange1) {
  6091. auto res =
  6092. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6094. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6095. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6096. EXPECT_EQ(true, res->has_header("Content-Range"));
  6097. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6098. EXPECT_EQ(std::string("def"), res->body);
  6099. }
  6100. TEST_F(ServerTest, GetStreamedWithRange2) {
  6101. auto res =
  6102. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6104. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6105. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6106. EXPECT_EQ(true, res->has_header("Content-Range"));
  6107. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6108. EXPECT_EQ(std::string("bcdefg"), res->body);
  6109. }
  6110. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6111. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6113. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6114. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6115. EXPECT_EQ(true, res->has_header("Content-Range"));
  6116. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6117. EXPECT_EQ(std::string("efg"), res->body);
  6118. }
  6119. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6120. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6121. // the entire representation.
  6122. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6123. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6125. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6126. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6127. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6128. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6129. }
  6130. }
  6131. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6132. auto res =
  6133. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6135. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6136. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6137. EXPECT_EQ(false, res->has_header("Content-Range"));
  6138. EXPECT_EQ(0U, res->body.size());
  6139. }
  6140. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6141. // Only a 206 is served as a partial representation. Under any other status
  6142. // `apply_ranges()` reported the full content length, so the body must match
  6143. // that header, and the content provider must never be asked for an offset
  6144. // outside the representation.
  6145. auto check = [&](int status, const char *range) {
  6146. auto path =
  6147. std::string("/streamed-with-range?status=") + std::to_string(status);
  6148. auto ctx = path + " Range: " + range;
  6149. auto res = cli_.Get(path, Headers{{"Range", range}});
  6150. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6151. EXPECT_EQ(status, res->status) << ctx;
  6152. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6153. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6154. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6155. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6156. };
  6157. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6158. check(403, "bytes=3-5");
  6159. // The offset is far past the representation.
  6160. check(403, "bytes=100000-100200");
  6161. // `first_pos` is still -1 here, and the bounds asserts in
  6162. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6163. check(403, "bytes=-3");
  6164. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6165. // multipart branch would have written one that is empty.
  6166. check(403, "bytes=1-2, 4-5");
  6167. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6168. // covers the whole representation.
  6169. check(200, "bytes=3-5");
  6170. check(200, "bytes=1-2, 4-5");
  6171. }
  6172. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6173. auto res =
  6174. cli_.Get("/streamed-with-range",
  6175. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6176. "92233720368547758079223372036854775807"}});
  6177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6178. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6179. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6180. EXPECT_EQ(false, res->has_header("Content-Range"));
  6181. EXPECT_EQ(0U, res->body.size());
  6182. }
  6183. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6184. auto res = cli_.Get(
  6185. "/with-range",
  6186. Headers{{"Range",
  6187. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6188. {"Accept-Encoding", ""}});
  6189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6190. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6191. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6192. EXPECT_EQ(true, res->has_header("Content-Range"));
  6193. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6194. EXPECT_EQ(std::string("abcdefg"), res->body);
  6195. }
  6196. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6197. auto res = cli_.Get("/with-range", Headers{
  6198. {"Range", "bytes=0-"},
  6199. {"Accept-Encoding", ""},
  6200. });
  6201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6202. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6203. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6204. EXPECT_EQ(true, res->has_header("Content-Range"));
  6205. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6206. EXPECT_EQ(std::string("abcdefg"), res->body);
  6207. }
  6208. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6209. auto res = cli_.Get("/streamed-with-range",
  6210. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6212. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6213. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6214. EXPECT_EQ(false, res->has_header("Content-Range"));
  6215. EXPECT_EQ(267U, res->body.size());
  6216. // Check that both range contents are present
  6217. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6218. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6219. // Check that Content-Range headers are present for both ranges
  6220. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6221. std::string::npos);
  6222. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6223. std::string::npos);
  6224. }
  6225. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6226. Ranges ranges;
  6227. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6228. ranges.emplace_back(0, -1);
  6229. }
  6230. auto res = cli_.Get("/streamed-with-range?error",
  6231. Headers{{make_range_header(ranges)}});
  6232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6233. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6234. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6235. EXPECT_EQ(false, res->has_header("Content-Range"));
  6236. EXPECT_EQ(0U, res->body.size());
  6237. }
  6238. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6239. auto res = cli_.Get("/streamed-with-range",
  6240. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6242. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6243. EXPECT_EQ(5U, res->body.size());
  6244. // Check that overlapping ranges are coalesced into a single range
  6245. EXPECT_EQ("bcdef", res->body);
  6246. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6247. // Should be single range, not multipart
  6248. EXPECT_TRUE(res->has_header("Content-Range"));
  6249. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6250. }
  6251. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6252. auto res = cli_.Get("/streamed-with-range",
  6253. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6255. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6256. EXPECT_EQ(268U, res->body.size());
  6257. // Check that both range contents are present
  6258. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6259. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6260. // Check that Content-Range headers are present for both ranges
  6261. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6262. std::string::npos);
  6263. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6264. std::string::npos);
  6265. }
  6266. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6267. auto res = cli_.Get("/streamed-with-range",
  6268. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6270. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6271. EXPECT_EQ(269U, res->body.size());
  6272. // Check that both duplicate range contents are present
  6273. size_t first_abc = res->body.find("abc\r\n");
  6274. EXPECT_TRUE(first_abc != std::string::npos);
  6275. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6276. EXPECT_TRUE(second_abc != std::string::npos);
  6277. // Check that Content-Range headers are present for both ranges
  6278. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6279. EXPECT_TRUE(first_range != std::string::npos);
  6280. size_t second_range =
  6281. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6282. EXPECT_TRUE(second_range != std::string::npos);
  6283. }
  6284. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6285. auto res =
  6286. cli_.Get("/streamed-with-range?error",
  6287. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6289. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6290. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6291. EXPECT_EQ(false, res->has_header("Content-Range"));
  6292. EXPECT_EQ(0U, res->body.size());
  6293. }
  6294. TEST_F(ServerTest, GetStreamedEndless) {
  6295. uint64_t offset = 0;
  6296. auto res = cli_.Get("/streamed-cancel",
  6297. [&](const char * /*data*/, uint64_t data_length) {
  6298. if (offset < 100) {
  6299. offset += data_length;
  6300. return true;
  6301. }
  6302. return false;
  6303. });
  6304. ASSERT_TRUE(!res);
  6305. EXPECT_EQ(Error::Canceled, res.error());
  6306. }
  6307. TEST_F(ServerTest, ClientStop) {
  6308. std::atomic_size_t count{4};
  6309. std::vector<std::thread> threads;
  6310. for (auto i = count.load(); i != 0; --i) {
  6311. threads.emplace_back([&]() {
  6312. auto res = cli_.Get("/streamed-cancel",
  6313. [&](const char *, uint64_t) { return true; });
  6314. --count;
  6315. ASSERT_TRUE(!res);
  6316. EXPECT_TRUE(res.error() == Error::Canceled ||
  6317. res.error() == Error::Read || res.error() == Error::Write);
  6318. });
  6319. }
  6320. std::this_thread::sleep_for(std::chrono::seconds(2));
  6321. while (count != 0) {
  6322. cli_.stop();
  6323. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6324. }
  6325. for (auto &t : threads) {
  6326. t.join();
  6327. }
  6328. }
  6329. TEST_F(ServerTest, GetWithRange1) {
  6330. auto res = cli_.Get("/with-range", Headers{
  6331. make_range_header({{3, 5}}),
  6332. {"Accept-Encoding", ""},
  6333. });
  6334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6335. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6336. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6337. EXPECT_EQ(true, res->has_header("Content-Range"));
  6338. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6339. EXPECT_EQ(std::string("def"), res->body);
  6340. }
  6341. TEST_F(ServerTest, GetWithRange2) {
  6342. auto res = cli_.Get("/with-range", Headers{
  6343. make_range_header({{1, -1}}),
  6344. {"Accept-Encoding", ""},
  6345. });
  6346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6347. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6348. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6349. EXPECT_EQ(true, res->has_header("Content-Range"));
  6350. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6351. EXPECT_EQ(std::string("bcdefg"), res->body);
  6352. }
  6353. TEST_F(ServerTest, GetWithRange3) {
  6354. auto res = cli_.Get("/with-range", Headers{
  6355. make_range_header({{0, 0}}),
  6356. {"Accept-Encoding", ""},
  6357. });
  6358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6359. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6360. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6361. EXPECT_EQ(true, res->has_header("Content-Range"));
  6362. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6363. EXPECT_EQ(std::string("a"), res->body);
  6364. }
  6365. TEST_F(ServerTest, GetWithRange4) {
  6366. auto res = cli_.Get("/with-range", Headers{
  6367. make_range_header({{-1, 2}}),
  6368. {"Accept-Encoding", ""},
  6369. });
  6370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6371. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6372. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6373. EXPECT_EQ(true, res->has_header("Content-Range"));
  6374. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6375. EXPECT_EQ(std::string("fg"), res->body);
  6376. }
  6377. TEST_F(ServerTest, GetWithRange5) {
  6378. auto res = cli_.Get("/with-range", Headers{
  6379. make_range_header({{0, 5}}),
  6380. {"Accept-Encoding", ""},
  6381. });
  6382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6383. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6384. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6385. EXPECT_EQ(true, res->has_header("Content-Range"));
  6386. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6387. EXPECT_EQ(std::string("abcdef"), res->body);
  6388. }
  6389. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6390. auto res =
  6391. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6393. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6394. }
  6395. TEST_F(ServerTest, GetWithRangeMultipart) {
  6396. auto res =
  6397. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6399. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6400. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6401. EXPECT_EQ(false, res->has_header("Content-Range"));
  6402. EXPECT_EQ(267U, res->body.size());
  6403. }
  6404. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6405. auto res = cli_.Get("/with-range",
  6406. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6408. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6409. }
  6410. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6411. auto res = cli_.Get("/with-range-customized-response",
  6412. Headers{{make_range_header({{1, 2}})}});
  6413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6414. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6415. EXPECT_EQ(true, res->has_header("Content-Length"));
  6416. EXPECT_EQ(false, res->has_header("Content-Range"));
  6417. EXPECT_EQ(JSON_DATA, res->body);
  6418. }
  6419. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6420. auto res = cli_.Get("/with-range-customized-response",
  6421. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6423. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6424. EXPECT_EQ(true, res->has_header("Content-Length"));
  6425. EXPECT_EQ(false, res->has_header("Content-Range"));
  6426. EXPECT_EQ(JSON_DATA, res->body);
  6427. }
  6428. TEST_F(ServerTest, Issue1772) {
  6429. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6431. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6432. }
  6433. TEST_F(ServerTest, Issue609) {
  6434. auto res = cli_.Delete("/issue609");
  6435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6436. EXPECT_EQ(StatusCode::OK_200, res->status);
  6437. EXPECT_EQ(std::string("ok"), res->body);
  6438. }
  6439. TEST_F(ServerTest, GetStreamedChunked) {
  6440. auto res = cli_.Get("/streamed-chunked");
  6441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6442. EXPECT_EQ(StatusCode::OK_200, res->status);
  6443. EXPECT_EQ(std::string("123456789"), res->body);
  6444. }
  6445. TEST_F(ServerTest, GetStreamedChunked2) {
  6446. auto res = cli_.Get("/streamed-chunked2");
  6447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6448. EXPECT_EQ(StatusCode::OK_200, res->status);
  6449. EXPECT_EQ(std::string("123456789"), res->body);
  6450. }
  6451. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6452. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6454. EXPECT_EQ(StatusCode::OK_200, res->status);
  6455. EXPECT_EQ(std::string("123456789"), res->body);
  6456. EXPECT_TRUE(res->has_header("Trailer"));
  6457. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6458. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6459. // Trailers are now stored separately from headers (security fix)
  6460. EXPECT_EQ(2U, res->trailers.size());
  6461. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6462. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6463. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6464. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6465. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6466. // Verify trailers are NOT in headers (security verification)
  6467. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6468. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6469. }
  6470. TEST_F(ServerTest, LargeChunkedPost) {
  6471. Request req;
  6472. req.method = "POST";
  6473. req.path = "/large-chunked";
  6474. std::string host_and_port;
  6475. host_and_port += HOST;
  6476. host_and_port += ":";
  6477. host_and_port += std::to_string(PORT);
  6478. req.headers.emplace("Host", host_and_port.c_str());
  6479. req.headers.emplace("Accept", "*/*");
  6480. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6481. req.headers.emplace("Content-Type", "text/plain");
  6482. req.headers.emplace("Content-Length", "0");
  6483. req.headers.emplace("Transfer-Encoding", "chunked");
  6484. std::string long_string(30 * 1024u, 'a');
  6485. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6486. // Attempt to make a large enough post to exceed OS buffers, to test that
  6487. // the server handles short reads if the full chunk data isn't available.
  6488. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6489. auto res = std::make_shared<Response>();
  6490. auto error = Error::Success;
  6491. auto ret = cli_.send(req, *res, error);
  6492. ASSERT_TRUE(ret);
  6493. EXPECT_EQ(StatusCode::OK_200, res->status);
  6494. }
  6495. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6496. auto res = cli_.Get("/remote_addr");
  6497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6498. EXPECT_EQ(StatusCode::OK_200, res->status);
  6499. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6500. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6501. }
  6502. TEST_F(ServerTest, GetMethodLocalAddr) {
  6503. auto res = cli_.Get("/local_addr");
  6504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6505. EXPECT_EQ(StatusCode::OK_200, res->status);
  6506. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6507. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6508. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6509. }
  6510. TEST_F(ServerTest, HTTPResponseSplitting) {
  6511. auto res = cli_.Get("/http_response_splitting");
  6512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6513. EXPECT_EQ(StatusCode::OK_200, res->status);
  6514. }
  6515. TEST_F(ServerTest, SlowRequest) {
  6516. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6517. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6518. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6519. }
  6520. #if 0
  6521. TEST_F(ServerTest, SlowPost) {
  6522. char buffer[64 * 1024];
  6523. memset(buffer, 0x42, sizeof(buffer));
  6524. auto res = cli_.Post(
  6525. "/slowpost", 64 * 1024 * 1024,
  6526. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6527. auto ret = sink.write(buffer, sizeof(buffer));
  6528. EXPECT_TRUE(ret);
  6529. return true;
  6530. },
  6531. "text/plain");
  6532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6533. EXPECT_EQ(StatusCode::OK_200, res->status);
  6534. }
  6535. TEST_F(ServerTest, SlowPostFail) {
  6536. char buffer[64 * 1024];
  6537. memset(buffer, 0x42, sizeof(buffer));
  6538. cli_.set_write_timeout(std::chrono::seconds(0));
  6539. auto res = cli_.Post(
  6540. "/slowpost", 64 * 1024 * 1024,
  6541. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6542. sink.write(buffer, sizeof(buffer));
  6543. return true;
  6544. },
  6545. "text/plain");
  6546. ASSERT_TRUE(!res);
  6547. EXPECT_EQ(Error::Write, res.error());
  6548. }
  6549. #endif
  6550. TEST_F(ServerTest, Put) {
  6551. auto res = cli_.Put("/put", "PUT", "text/plain");
  6552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6553. EXPECT_EQ(StatusCode::OK_200, res->status);
  6554. EXPECT_EQ("PUT", res->body);
  6555. }
  6556. TEST_F(ServerTest, PutWithContentProvider) {
  6557. auto res = cli_.Put(
  6558. "/put", 3,
  6559. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6560. sink.os << "PUT";
  6561. return true;
  6562. },
  6563. "text/plain");
  6564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6565. EXPECT_EQ(StatusCode::OK_200, res->status);
  6566. EXPECT_EQ("PUT", res->body);
  6567. }
  6568. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6569. auto res = cli_.Post(
  6570. "/post", 42,
  6571. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6572. return false;
  6573. },
  6574. "text/plain");
  6575. ASSERT_TRUE(!res);
  6576. EXPECT_EQ(Error::Canceled, res.error());
  6577. }
  6578. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6579. auto res = cli_.Put(
  6580. "/put",
  6581. [](size_t /*offset*/, DataSink &sink) {
  6582. sink.os << "PUT";
  6583. sink.done();
  6584. return true;
  6585. },
  6586. "text/plain");
  6587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6588. EXPECT_EQ(StatusCode::OK_200, res->status);
  6589. EXPECT_EQ("PUT", res->body);
  6590. }
  6591. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6592. auto res = cli_.Post(
  6593. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6594. "text/plain");
  6595. ASSERT_TRUE(!res);
  6596. EXPECT_EQ(Error::Canceled, res.error());
  6597. }
  6598. TEST_F(ServerTest, PostLoopBack) {
  6599. std::string body;
  6600. auto res = cli_.Post(
  6601. "/post-loopback", 9,
  6602. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6603. EXPECT_EQ(9u, length);
  6604. sink.write("123", 3);
  6605. sink.write("456", 3);
  6606. sink.write("789", 3);
  6607. return true;
  6608. },
  6609. "text/plain",
  6610. [&body](const char *data, size_t data_length) {
  6611. body.append(data, data_length);
  6612. return true;
  6613. });
  6614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6615. EXPECT_EQ(StatusCode::OK_200, res->status);
  6616. EXPECT_EQ("123456789", body);
  6617. }
  6618. TEST_F(ServerTest, PutLoopBack) {
  6619. std::string body;
  6620. auto res = cli_.Put(
  6621. "/put-loopback", 9,
  6622. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6623. EXPECT_EQ(9u, length);
  6624. sink.write("123", 3);
  6625. sink.write("456", 3);
  6626. sink.write("789", 3);
  6627. return true;
  6628. },
  6629. "text/plain",
  6630. [&body](const char *data, size_t data_length) {
  6631. body.append(data, data_length);
  6632. return true;
  6633. });
  6634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6635. EXPECT_EQ(StatusCode::OK_200, res->status);
  6636. EXPECT_EQ("123456789", body);
  6637. }
  6638. TEST_F(ServerTest, PatchLoopBack) {
  6639. std::string body;
  6640. auto res = cli_.Patch(
  6641. "/patch-loopback", 9,
  6642. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6643. EXPECT_EQ(9u, length);
  6644. sink.write("123", 3);
  6645. sink.write("456", 3);
  6646. sink.write("789", 3);
  6647. return true;
  6648. },
  6649. "text/plain",
  6650. [&body](const char *data, size_t data_length) {
  6651. body.append(data, data_length);
  6652. return true;
  6653. });
  6654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6655. EXPECT_EQ(StatusCode::OK_200, res->status);
  6656. EXPECT_EQ("123456789", body);
  6657. }
  6658. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6659. std::string body;
  6660. auto res = cli_.Post(
  6661. "/post-loopback",
  6662. [](size_t /*offset*/, DataSink &sink) {
  6663. sink.write("123", 3);
  6664. sink.write("456", 3);
  6665. sink.write("789", 3);
  6666. sink.done();
  6667. return true;
  6668. },
  6669. "text/plain",
  6670. [&body](const char *data, size_t data_length) {
  6671. body.append(data, data_length);
  6672. return true;
  6673. });
  6674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6675. EXPECT_EQ(StatusCode::OK_200, res->status);
  6676. EXPECT_EQ("123456789", body);
  6677. }
  6678. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6679. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6680. cli_.set_compress(true);
  6681. auto res = cli_.Put(
  6682. "/put", 3,
  6683. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6684. sink.os << "PUT";
  6685. return true;
  6686. },
  6687. "text/plain");
  6688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6689. EXPECT_EQ(StatusCode::OK_200, res->status);
  6690. EXPECT_EQ("PUT", res->body);
  6691. }
  6692. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6693. cli_.set_compress(true);
  6694. auto res = cli_.Post(
  6695. "/post", 42,
  6696. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6697. return false;
  6698. },
  6699. "text/plain");
  6700. ASSERT_TRUE(!res);
  6701. EXPECT_EQ(Error::Canceled, res.error());
  6702. }
  6703. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6704. cli_.set_compress(true);
  6705. auto res = cli_.Put(
  6706. "/put",
  6707. [](size_t /*offset*/, DataSink &sink) {
  6708. sink.os << "PUT";
  6709. sink.done();
  6710. return true;
  6711. },
  6712. "text/plain");
  6713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6714. EXPECT_EQ(StatusCode::OK_200, res->status);
  6715. EXPECT_EQ("PUT", res->body);
  6716. }
  6717. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6718. cli_.set_compress(true);
  6719. auto res = cli_.Post(
  6720. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6721. "text/plain");
  6722. ASSERT_TRUE(!res);
  6723. EXPECT_EQ(Error::Canceled, res.error());
  6724. }
  6725. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6726. cli_.set_compress(true);
  6727. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6729. EXPECT_EQ(StatusCode::OK_200, res->status);
  6730. EXPECT_EQ(LARGE_DATA, res->body);
  6731. }
  6732. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6733. #ifdef CPPHTTPLIB_SSL_ENABLED
  6734. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6735. Client cli(s.c_str());
  6736. cli.enable_server_certificate_verification(false);
  6737. #else
  6738. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6739. Client cli(s.c_str());
  6740. #endif
  6741. cli.set_compress(true);
  6742. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6744. EXPECT_EQ(StatusCode::OK_200, res->status);
  6745. EXPECT_EQ(LARGE_DATA, res->body);
  6746. // The compressed size should be less than a 10th of the original. May vary
  6747. // depending on the zlib library.
  6748. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6749. static_cast<uint64_t>(10 * 1024 * 1024));
  6750. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6751. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6752. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6753. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6754. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6755. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6756. #endif
  6757. }
  6758. TEST_F(ServerTest, PutContentWithDeflate) {
  6759. cli_.set_compress(false);
  6760. Headers headers;
  6761. headers.emplace("Content-Encoding", "deflate");
  6762. // PUT in deflate format:
  6763. auto res = cli_.Put("/put", headers,
  6764. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6766. EXPECT_EQ(StatusCode::OK_200, res->status);
  6767. EXPECT_EQ("PUT", res->body);
  6768. }
  6769. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6770. Headers headers;
  6771. headers.emplace("Accept-Encoding", "gzip, deflate");
  6772. auto res = cli_.Get("/streamed-chunked", headers);
  6773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6774. EXPECT_EQ(StatusCode::OK_200, res->status);
  6775. EXPECT_EQ(std::string("123456789"), res->body);
  6776. }
  6777. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6778. Headers headers;
  6779. headers.emplace("Accept-Encoding", "gzip, deflate");
  6780. auto res = cli_.Get("/streamed-chunked2", headers);
  6781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6782. EXPECT_EQ(StatusCode::OK_200, res->status);
  6783. EXPECT_EQ(std::string("123456789"), res->body);
  6784. }
  6785. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6786. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6788. EXPECT_EQ(StatusCode::OK_200, res->status);
  6789. }
  6790. TEST(GzipDecompressor, ChunkedDecompression) {
  6791. std::string data;
  6792. for (size_t i = 0; i < 32 * 1024; ++i) {
  6793. data.push_back(static_cast<char>('a' + i % 26));
  6794. }
  6795. std::string compressed_data;
  6796. {
  6797. httplib::detail::gzip_compressor compressor;
  6798. bool result = compressor.compress(
  6799. data.data(), data.size(),
  6800. /*last=*/true,
  6801. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6802. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6803. compressed_data_size);
  6804. return true;
  6805. });
  6806. ASSERT_TRUE(result);
  6807. }
  6808. std::string decompressed_data;
  6809. {
  6810. httplib::detail::gzip_decompressor decompressor;
  6811. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6812. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6813. size_t chunk_size = 130;
  6814. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6815. chunk_begin += chunk_size) {
  6816. size_t current_chunk_size =
  6817. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6818. bool result = decompressor.decompress(
  6819. compressed_data.data() + chunk_begin, current_chunk_size,
  6820. [&](const char *decompressed_data_chunk,
  6821. size_t decompressed_data_chunk_size) {
  6822. decompressed_data.insert(decompressed_data.size(),
  6823. decompressed_data_chunk,
  6824. decompressed_data_chunk_size);
  6825. return true;
  6826. });
  6827. ASSERT_TRUE(result);
  6828. }
  6829. }
  6830. ASSERT_EQ(data, decompressed_data);
  6831. }
  6832. TEST(GzipDecompressor, DeflateDecompression) {
  6833. std::string original_text = "Raw deflate without gzip";
  6834. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6835. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6836. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6837. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6838. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6839. std::string decompressed_data;
  6840. {
  6841. httplib::detail::gzip_decompressor decompressor;
  6842. bool result = decompressor.decompress(
  6843. compressed_data.data(), compressed_data.size(),
  6844. [&](const char *decompressed_data_chunk,
  6845. size_t decompressed_data_chunk_size) {
  6846. decompressed_data.insert(decompressed_data.size(),
  6847. decompressed_data_chunk,
  6848. decompressed_data_chunk_size);
  6849. return true;
  6850. });
  6851. ASSERT_TRUE(result);
  6852. }
  6853. ASSERT_EQ(original_text, decompressed_data);
  6854. }
  6855. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6856. std::string original_text = "Raw deflate without gzip";
  6857. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6858. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6859. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6860. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6861. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6862. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6863. std::string decompressed_data;
  6864. {
  6865. httplib::detail::gzip_decompressor decompressor;
  6866. bool result = decompressor.decompress(
  6867. compressed_data.data(), compressed_data.size(),
  6868. [&](const char *decompressed_data_chunk,
  6869. size_t decompressed_data_chunk_size) {
  6870. decompressed_data.insert(decompressed_data.size(),
  6871. decompressed_data_chunk,
  6872. decompressed_data_chunk_size);
  6873. return true;
  6874. });
  6875. ASSERT_TRUE(result);
  6876. }
  6877. ASSERT_EQ(original_text, decompressed_data);
  6878. }
  6879. #endif
  6880. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6881. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6882. Headers headers;
  6883. headers.emplace("Accept-Encoding", "br");
  6884. auto res = cli_.Get("/streamed-chunked", headers);
  6885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6886. EXPECT_EQ(StatusCode::OK_200, res->status);
  6887. EXPECT_EQ(std::string("123456789"), res->body);
  6888. }
  6889. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6890. Headers headers;
  6891. headers.emplace("Accept-Encoding", "br");
  6892. auto res = cli_.Get("/streamed-chunked2", headers);
  6893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6894. EXPECT_EQ(StatusCode::OK_200, res->status);
  6895. EXPECT_EQ(std::string("123456789"), res->body);
  6896. }
  6897. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6898. cli_.set_compress(true);
  6899. auto res = cli_.Put(
  6900. "/put", 3,
  6901. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6902. sink.os << "PUT";
  6903. return true;
  6904. },
  6905. "text/plain");
  6906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6907. EXPECT_EQ(StatusCode::OK_200, res->status);
  6908. EXPECT_EQ("PUT", res->body);
  6909. }
  6910. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6911. cli_.set_compress(true);
  6912. auto res = cli_.Put(
  6913. "/put",
  6914. [](size_t /*offset*/, DataSink &sink) {
  6915. sink.os << "PUT";
  6916. sink.done();
  6917. return true;
  6918. },
  6919. "text/plain");
  6920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6921. EXPECT_EQ(StatusCode::OK_200, res->status);
  6922. EXPECT_EQ("PUT", res->body);
  6923. }
  6924. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6925. cli_.set_compress(true);
  6926. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6928. EXPECT_EQ(StatusCode::OK_200, res->status);
  6929. EXPECT_EQ(LARGE_DATA, res->body);
  6930. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6931. }
  6932. #endif
  6933. TEST_F(ServerTest, Patch) {
  6934. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6936. EXPECT_EQ(StatusCode::OK_200, res->status);
  6937. EXPECT_EQ("PATCH", res->body);
  6938. }
  6939. TEST_F(ServerTest, Delete) {
  6940. auto res = cli_.Delete("/delete");
  6941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6942. EXPECT_EQ(StatusCode::OK_200, res->status);
  6943. EXPECT_EQ("DELETE", res->body);
  6944. }
  6945. TEST_F(ServerTest, DeleteContentReceiver) {
  6946. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6948. EXPECT_EQ(StatusCode::OK_200, res->status);
  6949. EXPECT_EQ("content", res->body);
  6950. }
  6951. TEST_F(ServerTest, Options) {
  6952. auto res = cli_.Options("*");
  6953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6954. EXPECT_EQ(StatusCode::OK_200, res->status);
  6955. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6956. EXPECT_TRUE(res->body.empty());
  6957. }
  6958. TEST_F(ServerTest, URL) {
  6959. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6961. EXPECT_EQ(StatusCode::OK_200, res->status);
  6962. }
  6963. TEST_F(ServerTest, ArrayParam) {
  6964. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6966. EXPECT_EQ(StatusCode::OK_200, res->status);
  6967. }
  6968. TEST_F(ServerTest, ArrayParamValues) {
  6969. auto res =
  6970. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6972. EXPECT_EQ(StatusCode::OK_200, res->status);
  6973. }
  6974. TEST_F(ServerTest, NoMultipleHeaders) {
  6975. Headers headers = {{"Content-Length", "5"}};
  6976. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6977. "text/plain");
  6978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6979. EXPECT_EQ(StatusCode::OK_200, res->status);
  6980. }
  6981. TEST_F(ServerTest, PostContentReceiver) {
  6982. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6984. ASSERT_EQ(StatusCode::OK_200, res->status);
  6985. ASSERT_EQ("content", res->body);
  6986. }
  6987. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6988. UploadFormDataItems items = {
  6989. {"text1", "text default", "", ""},
  6990. {"text2", "aωb", "", ""},
  6991. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6992. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6993. {"file3", "", "", "application/octet-stream"},
  6994. };
  6995. auto res = cli_.Post("/content_receiver", items);
  6996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6997. EXPECT_EQ(StatusCode::OK_200, res->status);
  6998. }
  6999. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7000. UploadFormDataItems items = {
  7001. {"text1", "text default", "", ""},
  7002. {"text2", "aωb", "", ""},
  7003. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7004. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7005. {"file3", "", "", "application/octet-stream"},
  7006. };
  7007. auto boundary = std::string("+++++");
  7008. std::string body;
  7009. for (const auto &item : items) {
  7010. body += "--" + boundary + "\r\n";
  7011. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7012. if (!item.filename.empty()) {
  7013. body += "; filename=\"" + item.filename + "\"";
  7014. }
  7015. body += "\r\n";
  7016. if (!item.content_type.empty()) {
  7017. body += "Content-Type: " + item.content_type + "\r\n";
  7018. }
  7019. body += "\r\n";
  7020. body += item.content + "\r\n";
  7021. }
  7022. body += "--" + boundary + "--\r\n";
  7023. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7024. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7026. EXPECT_EQ(StatusCode::OK_200, res->status);
  7027. }
  7028. TEST(MultipartFormDataTest, FieldEscaping) {
  7029. Server svr;
  7030. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7031. const ContentReader &content_reader) {
  7032. ASSERT_TRUE(req.is_multipart_form_data());
  7033. std::vector<FormData> received;
  7034. content_reader(
  7035. [&](const FormData &file) {
  7036. received.push_back(file);
  7037. return true;
  7038. },
  7039. [&](const char *data, size_t data_length) {
  7040. received.back().content.append(data, data_length);
  7041. return true;
  7042. });
  7043. // '"', CR and LF in names and filenames are escaped following the
  7044. // WHATWG HTML standard, so each part still parses as a single part
  7045. // with no injected headers. Content types get CR/LF escaped too,
  7046. // while '"' (legal there, e.g. quoted charset) is preserved.
  7047. ASSERT_EQ(4U, received.size());
  7048. EXPECT_EQ("na%22me", received[0].name);
  7049. EXPECT_EQ("quoted name", received[0].content);
  7050. EXPECT_EQ("file", received[1].name);
  7051. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7052. received[1].filename);
  7053. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7054. EXPECT_EQ("injected", received[1].content);
  7055. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7056. EXPECT_EQ("my%22file.txt", received[2].filename);
  7057. EXPECT_EQ("cr lf name", received[2].content);
  7058. EXPECT_EQ("typed", received[3].name);
  7059. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7060. received[3].content_type);
  7061. EXPECT_EQ("typed content", received[3].content);
  7062. });
  7063. auto port = svr.bind_to_any_port("localhost");
  7064. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7065. auto se = detail::scope_exit([&] {
  7066. svr.stop();
  7067. t.join();
  7068. ASSERT_FALSE(svr.is_running());
  7069. });
  7070. svr.wait_until_ready();
  7071. Client cli("localhost", port);
  7072. UploadFormDataItems items = {
  7073. {"na\"me", "quoted name", "", ""},
  7074. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7075. "application/octet-stream"},
  7076. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7077. {"typed", "typed content", "",
  7078. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7079. };
  7080. auto res = cli.Post("/post", items);
  7081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7082. EXPECT_EQ(StatusCode::OK_200, res->status);
  7083. }
  7084. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7085. const UploadFormDataItems items = {
  7086. {"name1", "Content 1", "", ""},
  7087. {"name2", "Content 2", "file2.txt", "text/plain"},
  7088. };
  7089. Server svr;
  7090. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7091. const ContentReader &content_reader) {
  7092. ASSERT_TRUE(req.is_multipart_form_data());
  7093. std::vector<FormData> received;
  7094. content_reader(
  7095. [&](const FormData &file) {
  7096. received.push_back(file);
  7097. return true;
  7098. },
  7099. [&](const char *data, size_t data_length) {
  7100. received.back().content.append(data, data_length);
  7101. return true;
  7102. });
  7103. ASSERT_EQ(2U, received.size());
  7104. EXPECT_EQ("name1", received[0].name);
  7105. EXPECT_EQ("Content 1", received[0].content);
  7106. EXPECT_EQ("name2", received[1].name);
  7107. EXPECT_EQ("Content 2", received[1].content);
  7108. EXPECT_EQ("file2.txt", received[1].filename);
  7109. EXPECT_EQ("text/plain", received[1].content_type);
  7110. });
  7111. auto port = svr.bind_to_any_port("localhost");
  7112. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7113. auto se = detail::scope_exit([&] {
  7114. svr.stop();
  7115. t.join();
  7116. ASSERT_FALSE(svr.is_running());
  7117. });
  7118. svr.wait_until_ready();
  7119. Client cli("localhost", port);
  7120. // Whole-body serialization with a generated boundary
  7121. {
  7122. MultipartFormDataWriter writer;
  7123. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7124. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7125. writer.content_type());
  7126. auto body = writer.serialize(items);
  7127. EXPECT_EQ(body.size(), writer.content_length(items));
  7128. auto res = cli.Post("/post", body, writer.content_type());
  7129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7130. EXPECT_EQ(StatusCode::OK_200, res->status);
  7131. }
  7132. // Per-part framing with a custom boundary via a content provider
  7133. {
  7134. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7135. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7136. MultipartFormDataWriter writer("custom-boundary_123");
  7137. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7138. std::string body;
  7139. for (const auto &item : items) {
  7140. body += writer.item_begin(item);
  7141. body += item.content;
  7142. body += MultipartFormDataWriter::item_end();
  7143. }
  7144. body += writer.finish();
  7145. EXPECT_EQ(body.size(), writer.content_length(items));
  7146. auto res = cli.Post(
  7147. "/post", body.size(),
  7148. [&](size_t offset, size_t length, DataSink &sink) {
  7149. sink.write(body.data() + offset, length);
  7150. return true;
  7151. },
  7152. writer.content_type());
  7153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7154. EXPECT_EQ(StatusCode::OK_200, res->status);
  7155. }
  7156. }
  7157. TEST_F(ServerTest, PostContentReceiverGzip) {
  7158. cli_.set_compress(true);
  7159. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7161. ASSERT_EQ(StatusCode::OK_200, res->status);
  7162. ASSERT_EQ("content", res->body);
  7163. }
  7164. TEST_F(ServerTest, PutContentReceiver) {
  7165. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7167. ASSERT_EQ(StatusCode::OK_200, res->status);
  7168. ASSERT_EQ("content", res->body);
  7169. }
  7170. TEST_F(ServerTest, PatchContentReceiver) {
  7171. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7173. ASSERT_EQ(StatusCode::OK_200, res->status);
  7174. ASSERT_EQ("content", res->body);
  7175. }
  7176. template <typename ClientType>
  7177. void TestWithHeadersAndContentReceiver(
  7178. ClientType &cli,
  7179. std::function<Result(ClientType &, const std::string &, const Headers &,
  7180. const std::string &, const std::string &,
  7181. ContentReceiver, DownloadProgress)>
  7182. request_func) {
  7183. Headers headers;
  7184. headers.emplace("X-Custom-Header", "test-value");
  7185. std::string received_body;
  7186. auto res = request_func(
  7187. cli, "/content_receiver", headers, "content", "application/json",
  7188. [&](const char *data, size_t data_length) {
  7189. received_body.append(data, data_length);
  7190. return true;
  7191. },
  7192. nullptr);
  7193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7194. EXPECT_EQ(StatusCode::OK_200, res->status);
  7195. EXPECT_EQ("content", received_body);
  7196. }
  7197. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7198. #ifdef CPPHTTPLIB_SSL_ENABLED
  7199. using ClientT = SSLClient;
  7200. #else
  7201. using ClientT = Client;
  7202. #endif
  7203. TestWithHeadersAndContentReceiver<ClientT>(
  7204. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7205. const std::string &body, const std::string &content_type,
  7206. ContentReceiver receiver, DownloadProgress progress) {
  7207. return cli.Post(path, headers, body, content_type, receiver, progress);
  7208. });
  7209. }
  7210. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7211. #ifdef CPPHTTPLIB_SSL_ENABLED
  7212. using ClientT = SSLClient;
  7213. #else
  7214. using ClientT = Client;
  7215. #endif
  7216. TestWithHeadersAndContentReceiver<ClientT>(
  7217. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7218. const std::string &body, const std::string &content_type,
  7219. ContentReceiver receiver, DownloadProgress progress) {
  7220. return cli.Put(path, headers, body, content_type, receiver, progress);
  7221. });
  7222. }
  7223. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7224. #ifdef CPPHTTPLIB_SSL_ENABLED
  7225. using ClientT = SSLClient;
  7226. #else
  7227. using ClientT = Client;
  7228. #endif
  7229. TestWithHeadersAndContentReceiver<ClientT>(
  7230. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7231. const std::string &body, const std::string &content_type,
  7232. ContentReceiver receiver, DownloadProgress progress) {
  7233. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7234. });
  7235. }
  7236. template <typename ClientType>
  7237. void TestWithHeadersAndContentReceiverWithProgress(
  7238. ClientType &cli,
  7239. std::function<Result(ClientType &, const std::string &, const Headers &,
  7240. const std::string &, const std::string &,
  7241. ContentReceiver, DownloadProgress)>
  7242. request_func) {
  7243. Headers headers;
  7244. headers.emplace("X-Test-Header", "progress-test");
  7245. std::string received_body;
  7246. auto progress_called = false;
  7247. auto res = request_func(
  7248. cli, "/content_receiver", headers, "content", "text/plain",
  7249. [&](const char *data, size_t data_length) {
  7250. received_body.append(data, data_length);
  7251. return true;
  7252. },
  7253. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7254. progress_called = true;
  7255. return true;
  7256. });
  7257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7258. EXPECT_EQ(StatusCode::OK_200, res->status);
  7259. EXPECT_EQ("content", received_body);
  7260. EXPECT_TRUE(progress_called);
  7261. }
  7262. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7263. #ifdef CPPHTTPLIB_SSL_ENABLED
  7264. using ClientT = SSLClient;
  7265. #else
  7266. using ClientT = Client;
  7267. #endif
  7268. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7269. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7270. const std::string &body, const std::string &content_type,
  7271. ContentReceiver receiver, DownloadProgress progress) {
  7272. return cli.Post(path, headers, body, content_type, receiver, progress);
  7273. });
  7274. }
  7275. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7276. #ifdef CPPHTTPLIB_SSL_ENABLED
  7277. using ClientT = SSLClient;
  7278. #else
  7279. using ClientT = Client;
  7280. #endif
  7281. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7282. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7283. const std::string &body, const std::string &content_type,
  7284. ContentReceiver receiver, DownloadProgress progress) {
  7285. return cli.Put(path, headers, body, content_type, receiver, progress);
  7286. });
  7287. }
  7288. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7289. #ifdef CPPHTTPLIB_SSL_ENABLED
  7290. using ClientT = SSLClient;
  7291. #else
  7292. using ClientT = Client;
  7293. #endif
  7294. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7295. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7296. const std::string &body, const std::string &content_type,
  7297. ContentReceiver receiver, DownloadProgress progress) {
  7298. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7299. });
  7300. }
  7301. template <typename ClientType>
  7302. void TestWithHeadersAndContentReceiverError(
  7303. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7304. const Headers &, const std::string &,
  7305. const std::string &, ContentReceiver)>
  7306. request_func) {
  7307. Headers headers;
  7308. headers.emplace("X-Error-Test", "true");
  7309. std::string received_body;
  7310. auto receiver_failed = false;
  7311. auto res =
  7312. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7313. [&](const char *data, size_t data_length) {
  7314. received_body.append(data, data_length);
  7315. receiver_failed = true;
  7316. return false;
  7317. });
  7318. ASSERT_FALSE(res);
  7319. EXPECT_TRUE(receiver_failed);
  7320. }
  7321. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7322. #ifdef CPPHTTPLIB_SSL_ENABLED
  7323. using ClientT = SSLClient;
  7324. #else
  7325. using ClientT = Client;
  7326. #endif
  7327. TestWithHeadersAndContentReceiverError<ClientT>(
  7328. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7329. const std::string &body, const std::string &content_type,
  7330. ContentReceiver receiver) {
  7331. return cli.Post(path, headers, body, content_type, receiver);
  7332. });
  7333. }
  7334. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7335. #ifdef CPPHTTPLIB_SSL_ENABLED
  7336. using ClientT = SSLClient;
  7337. #else
  7338. using ClientT = Client;
  7339. #endif
  7340. TestWithHeadersAndContentReceiverError<ClientT>(
  7341. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7342. const std::string &body, const std::string &content_type,
  7343. ContentReceiver receiver) {
  7344. return cli.Put(path, headers, body, content_type, receiver);
  7345. });
  7346. }
  7347. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7348. #ifdef CPPHTTPLIB_SSL_ENABLED
  7349. using ClientT = SSLClient;
  7350. #else
  7351. using ClientT = Client;
  7352. #endif
  7353. TestWithHeadersAndContentReceiverError<ClientT>(
  7354. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7355. const std::string &body, const std::string &content_type,
  7356. ContentReceiver receiver) {
  7357. return cli.Patch(path, headers, body, content_type, receiver);
  7358. });
  7359. }
  7360. TEST_F(ServerTest, PostQueryStringAndBody) {
  7361. auto res =
  7362. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7364. ASSERT_EQ(StatusCode::OK_200, res->status);
  7365. }
  7366. TEST_F(ServerTest, HTTP2Magic) {
  7367. Request req;
  7368. req.method = "PRI";
  7369. req.path = "*";
  7370. req.body = "SM";
  7371. auto res = std::make_shared<Response>();
  7372. auto error = Error::Success;
  7373. auto ret = cli_.send(req, *res, error);
  7374. ASSERT_TRUE(ret);
  7375. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7376. }
  7377. TEST_F(ServerTest, KeepAlive) {
  7378. auto res = cli_.Get("/hi");
  7379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7380. EXPECT_EQ(StatusCode::OK_200, res->status);
  7381. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7382. EXPECT_EQ("Hello World!", res->body);
  7383. res = cli_.Get("/hi");
  7384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7385. EXPECT_EQ(StatusCode::OK_200, res->status);
  7386. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7387. EXPECT_EQ("Hello World!", res->body);
  7388. res = cli_.Get("/hi");
  7389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7390. EXPECT_EQ(StatusCode::OK_200, res->status);
  7391. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7392. EXPECT_EQ("Hello World!", res->body);
  7393. res = cli_.Get("/not-exist");
  7394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7395. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7396. res = cli_.Post("/empty", "", "text/plain");
  7397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7398. EXPECT_EQ(StatusCode::OK_200, res->status);
  7399. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7400. EXPECT_EQ("empty", res->body);
  7401. EXPECT_EQ("close", res->get_header_value("Connection"));
  7402. res = cli_.Post(
  7403. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7404. "text/plain");
  7405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7406. EXPECT_EQ(StatusCode::OK_200, res->status);
  7407. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7408. EXPECT_EQ("empty", res->body);
  7409. cli_.set_keep_alive(false);
  7410. res = cli_.Get("/last-request");
  7411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7412. EXPECT_EQ(StatusCode::OK_200, res->status);
  7413. EXPECT_EQ("close", res->get_header_value("Connection"));
  7414. }
  7415. TEST_F(ServerTest, TooManyRedirect) {
  7416. cli_.set_follow_location(true);
  7417. auto res = cli_.Get("/redirect/0");
  7418. ASSERT_TRUE(!res);
  7419. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7420. }
  7421. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7422. Request req;
  7423. req.method = "FOOBAR";
  7424. req.path = "/hi";
  7425. cli_.set_keep_alive(true);
  7426. auto res = cli_.send(req);
  7427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7428. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7429. EXPECT_EQ("close", res->get_header_value("Connection"));
  7430. EXPECT_FALSE(cli_.is_socket_open());
  7431. }
  7432. TEST_F(ServerTest, CustomRouteReadsBody) {
  7433. const std::string xml =
  7434. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7435. Request req;
  7436. req.method = "PROPFIND";
  7437. req.path = "/dav/dir";
  7438. req.set_header("Depth", "1");
  7439. req.body = xml;
  7440. auto res = cli_.send(req);
  7441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7442. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7443. EXPECT_EQ(xml, res->body);
  7444. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7445. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7446. }
  7447. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7448. Request req;
  7449. req.method = "PROPFIND";
  7450. req.path = "/dav/42";
  7451. auto res = cli_.send(req);
  7452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7453. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7454. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7455. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7456. }
  7457. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7458. Request req;
  7459. req.method = "PROPFIND";
  7460. req.path = "/dav-re/123";
  7461. auto res = cli_.send(req);
  7462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7463. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7464. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7465. }
  7466. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7467. Request req;
  7468. req.method = "MKCOL";
  7469. req.path = "/dav-mkcol";
  7470. auto res = cli_.send(req);
  7471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7472. EXPECT_EQ(StatusCode::Created_201, res->status);
  7473. }
  7474. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7475. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7476. Request req;
  7477. req.method = "REPORT";
  7478. req.path = "/dav-report";
  7479. req.body = xml;
  7480. auto res = cli_.send(req);
  7481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7482. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7483. EXPECT_EQ(xml, res->body);
  7484. }
  7485. // A content reader route must fire even when the request carries no body,
  7486. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7487. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7488. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7489. Request req;
  7490. req.method = "REPORT";
  7491. req.path = "/dav-report";
  7492. auto res = cli_.send(req);
  7493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7494. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7495. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7496. }
  7497. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7498. Request req;
  7499. req.method = "PROPFIND";
  7500. req.path = "/not-dav";
  7501. auto res = cli_.send(req);
  7502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7503. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7504. }
  7505. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7506. Request req;
  7507. req.method = "UNLOCK";
  7508. req.path = "/dav/dir";
  7509. cli_.set_keep_alive(true);
  7510. auto res = cli_.send(req);
  7511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7512. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7513. EXPECT_EQ("close", res->get_header_value("Connection"));
  7514. EXPECT_FALSE(cli_.is_socket_open());
  7515. }
  7516. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7517. // The mount point serves this path, but only for GET and HEAD.
  7518. auto get_res = cli_.Get("/dir/index.html");
  7519. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7520. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7521. Request req;
  7522. req.method = "PROPFIND";
  7523. req.path = "/dir/index.html";
  7524. auto res = cli_.send(req);
  7525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7526. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7527. }
  7528. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7529. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7530. cli_.set_keep_alive(true);
  7531. for (auto i = 0; i < 2; i++) {
  7532. Request req;
  7533. req.method = "PROPFIND";
  7534. req.path = "/dav/dir";
  7535. req.body = xml;
  7536. auto res = cli_.send(req);
  7537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7538. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7539. EXPECT_EQ(xml, res->body);
  7540. EXPECT_TRUE(cli_.is_socket_open());
  7541. }
  7542. // A built-in method must still be served on the same connection.
  7543. cli_.set_keep_alive(false);
  7544. auto res = cli_.Get("/hi");
  7545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7546. EXPECT_EQ(StatusCode::OK_200, res->status);
  7547. EXPECT_EQ("close", res->get_header_value("Connection"));
  7548. }
  7549. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7550. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7551. Request req;
  7552. req.method = "PROPFIND";
  7553. req.path = "/dav/dir";
  7554. req.set_header("Expect", "100-continue");
  7555. req.body = xml;
  7556. auto res = cli_.send(req);
  7557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7558. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7559. EXPECT_EQ(xml, res->body);
  7560. }
  7561. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7562. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7563. TEST_F(ServerTest, Gzip) {
  7564. Headers headers;
  7565. headers.emplace("Accept-Encoding", "gzip, deflate");
  7566. auto res = cli_.Get("/compress", headers);
  7567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7568. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7569. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7570. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7571. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7572. "7890123456789012345678901234567890",
  7573. res->body);
  7574. EXPECT_EQ(StatusCode::OK_200, res->status);
  7575. }
  7576. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7577. Headers headers;
  7578. headers.emplace("Accept-Encoding", "gzip, deflate");
  7579. auto res = cli_.Get("/compress-with-charset", headers);
  7580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7581. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7582. EXPECT_EQ("application/json; charset=utf-8",
  7583. res->get_header_value("Content-Type"));
  7584. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7585. "7890123456789012345678901234567890",
  7586. res->body);
  7587. EXPECT_EQ(StatusCode::OK_200, res->status);
  7588. }
  7589. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7590. Headers headers;
  7591. headers.emplace("Accept-Encoding", "");
  7592. auto res = cli_.Get("/compress", headers);
  7593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7594. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7595. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7596. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7597. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7598. "7890123456789012345678901234567890",
  7599. res->body);
  7600. EXPECT_EQ(StatusCode::OK_200, res->status);
  7601. }
  7602. TEST_F(ServerTest, GzipWithContentReceiver) {
  7603. Headers headers;
  7604. headers.emplace("Accept-Encoding", "gzip, deflate");
  7605. std::string body;
  7606. auto res = cli_.Get("/compress", headers,
  7607. [&](const char *data, uint64_t data_length) {
  7608. EXPECT_EQ(100U, data_length);
  7609. body.append(data, data_length);
  7610. return true;
  7611. });
  7612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7613. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7614. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7615. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7616. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7617. "7890123456789012345678901234567890",
  7618. body);
  7619. EXPECT_EQ(StatusCode::OK_200, res->status);
  7620. }
  7621. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7622. Headers headers;
  7623. headers.emplace("Accept-Encoding", "gzip, deflate");
  7624. cli_.set_decompress(false);
  7625. auto res = cli_.Get("/compress", headers);
  7626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7627. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7628. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7629. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7630. EXPECT_EQ(33U, res->body.size());
  7631. EXPECT_EQ(StatusCode::OK_200, res->status);
  7632. }
  7633. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7634. Headers headers;
  7635. headers.emplace("Accept-Encoding", "");
  7636. std::string body;
  7637. auto res = cli_.Get("/compress", headers,
  7638. [&](const char *data, uint64_t data_length) {
  7639. EXPECT_EQ(100U, data_length);
  7640. body.append(data, data_length);
  7641. return true;
  7642. });
  7643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7644. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7645. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7646. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7647. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7648. "7890123456789012345678901234567890",
  7649. body);
  7650. EXPECT_EQ(StatusCode::OK_200, res->status);
  7651. }
  7652. TEST_F(ServerTest, NoGzip) {
  7653. Headers headers;
  7654. headers.emplace("Accept-Encoding", "gzip, deflate");
  7655. auto res = cli_.Get("/nocompress", headers);
  7656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7657. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7658. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7659. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7660. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7661. "7890123456789012345678901234567890",
  7662. res->body);
  7663. EXPECT_EQ(StatusCode::OK_200, res->status);
  7664. }
  7665. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7666. Headers headers;
  7667. headers.emplace("Accept-Encoding", "gzip, deflate");
  7668. std::string body;
  7669. auto res = cli_.Get("/nocompress", headers,
  7670. [&](const char *data, uint64_t data_length) {
  7671. EXPECT_EQ(100U, data_length);
  7672. body.append(data, data_length);
  7673. return true;
  7674. });
  7675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7676. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7677. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7678. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7679. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7680. "7890123456789012345678901234567890",
  7681. body);
  7682. EXPECT_EQ(StatusCode::OK_200, res->status);
  7683. }
  7684. TEST_F(ServerTest, MultipartFormDataGzip) {
  7685. UploadFormDataItems items = {
  7686. {"key1", "test", "", ""},
  7687. {"key2", "--abcdefg123", "", ""},
  7688. };
  7689. cli_.set_compress(true);
  7690. auto res = cli_.Post("/compress-multipart", items);
  7691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7692. EXPECT_EQ(StatusCode::OK_200, res->status);
  7693. }
  7694. #endif
  7695. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7696. // Static file compression is opt-in, so these run their own server rather than
  7697. // flipping it on for the shared ServerTest fixture, which would silently
  7698. // rewrite what every other static file test is asserting.
  7699. class StaticFileCompressionTest : public ::testing::Test {
  7700. protected:
  7701. void TearDown() override {
  7702. if (t_.joinable()) {
  7703. svr_.stop();
  7704. t_.join();
  7705. }
  7706. }
  7707. int start(const std::function<void(Server &)> &configure = nullptr) {
  7708. // Serves the same tree as a directory of build-time compressed assets
  7709. // would be served: the mount point names the coding the files are already
  7710. // stored in. Registered before "/" so it is the one that matches.
  7711. svr_.set_mount_point("/pre-encoded", "./www",
  7712. {{"Content-Encoding", "gzip"}});
  7713. svr_.set_mount_point("/", "./www");
  7714. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7715. res.set_file_content("./www/dir/index.html", "text/html");
  7716. });
  7717. svr_.Get("/pre-encoded-file-content",
  7718. [](const Request & /*req*/, Response &res) {
  7719. res.set_header("Content-Encoding", "gzip");
  7720. res.set_file_content("./www/dir/index.html", "text/html");
  7721. });
  7722. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7723. res.set_content_provider(
  7724. 6, "text/plain",
  7725. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7726. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7727. return true;
  7728. });
  7729. });
  7730. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7731. res.set_content_provider(
  7732. 1000, "text/plain",
  7733. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7734. if (offset < 100) {
  7735. std::string data(100, 'A');
  7736. sink.write(data.data(), data.size());
  7737. return true;
  7738. }
  7739. std::this_thread::sleep_for(std::chrono::seconds(2));
  7740. std::string data(900, 'B');
  7741. sink.write(data.data(), data.size());
  7742. return true;
  7743. });
  7744. });
  7745. if (configure) { configure(svr_); }
  7746. auto port = svr_.bind_to_any_port(HOST);
  7747. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7748. svr_.wait_until_ready();
  7749. return port;
  7750. }
  7751. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7752. // Every file under ./www except 1MB.txt is smaller than the default
  7753. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7754. // it out of the way.
  7755. static void enable_without_floor(Server &svr) {
  7756. svr.set_static_file_compression(true);
  7757. svr.set_static_file_compression_min_length(0);
  7758. }
  7759. Server svr_;
  7760. std::thread t_;
  7761. };
  7762. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7763. auto port = start();
  7764. Client cli(HOST, port);
  7765. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7767. EXPECT_EQ(StatusCode::OK_200, res->status);
  7768. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7769. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7770. EXPECT_EQ(1048576U, res->body.size());
  7771. }
  7772. TEST_F(StaticFileCompressionTest, MountPoint) {
  7773. auto port = start(enable);
  7774. Client cli(HOST, port);
  7775. cli.set_decompress(false);
  7776. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7778. EXPECT_EQ(StatusCode::OK_200, res->status);
  7779. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7780. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7781. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7782. // The response stays self-delimiting: a length, not a chunked body.
  7783. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7784. EXPECT_EQ(std::to_string(res->body.size()),
  7785. res->get_header_value("Content-Length"));
  7786. EXPECT_LT(res->body.size(), 1048576U);
  7787. EXPECT_FALSE(res->body.empty());
  7788. }
  7789. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7790. auto port = start(enable);
  7791. Client cli(HOST, port);
  7792. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7794. EXPECT_EQ(StatusCode::OK_200, res->status);
  7795. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7796. EXPECT_EQ(1048576U, res->body.size());
  7797. }
  7798. TEST_F(StaticFileCompressionTest, FileContent) {
  7799. auto port = start(enable_without_floor);
  7800. Client cli(HOST, port);
  7801. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7803. EXPECT_EQ(StatusCode::OK_200, res->status);
  7804. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7805. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7806. EXPECT_EQ(104U, res->body.size());
  7807. }
  7808. // A handler that serves an already-encoded file names the coding itself. The
  7809. // file-backed path decided its coding from Accept-Encoding and the content
  7810. // type alone, so it compressed the stored bytes a second time and appended a
  7811. // second Content-Encoding field line.
  7812. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  7813. auto port = start(enable_without_floor);
  7814. Client cli(HOST, port);
  7815. cli.set_decompress(false);
  7816. auto res = cli.Get("/pre-encoded-file-content",
  7817. Headers{{"Accept-Encoding", "gzip"}});
  7818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7819. EXPECT_EQ(StatusCode::OK_200, res->status);
  7820. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7821. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7822. // Vary belongs to a coding the server chose, and it chose none here.
  7823. EXPECT_FALSE(res->has_header("Vary"));
  7824. // The file travels exactly as it is stored on disk.
  7825. EXPECT_EQ(104U, res->body.size());
  7826. }
  7827. // The 1MB file clears the default floor, so this one runs the configuration a
  7828. // deployment would actually have.
  7829. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  7830. auto port = start(enable);
  7831. Client cli(HOST, port);
  7832. cli.set_decompress(false);
  7833. auto res =
  7834. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7836. EXPECT_EQ(StatusCode::OK_200, res->status);
  7837. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7838. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7839. EXPECT_FALSE(res->has_header("Vary"));
  7840. EXPECT_EQ(1048576U, res->body.size());
  7841. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7842. }
  7843. TEST_F(StaticFileCompressionTest, Head) {
  7844. auto port = start(enable);
  7845. Client cli(HOST, port);
  7846. cli.set_decompress(false);
  7847. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7848. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  7849. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7851. EXPECT_EQ(StatusCode::OK_200, res->status);
  7852. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7853. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7854. // HEAD still reports the size a GET would return.
  7855. EXPECT_EQ(get->get_header_value("Content-Length"),
  7856. res->get_header_value("Content-Length"));
  7857. EXPECT_TRUE(res->body.empty());
  7858. }
  7859. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  7860. auto port = start(enable);
  7861. Client cli(HOST, port);
  7862. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  7863. {"Accept-Encoding", "gzip"}});
  7864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7865. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7866. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7867. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7868. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7869. EXPECT_EQ("cd", res->body);
  7870. }
  7871. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  7872. auto port = start(enable);
  7873. Client cli(HOST, port);
  7874. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  7875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7876. EXPECT_EQ(StatusCode::OK_200, res->status);
  7877. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7878. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7879. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7880. }
  7881. TEST_F(StaticFileCompressionTest, EmptyFile) {
  7882. auto port = start(enable);
  7883. Client cli(HOST, port);
  7884. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  7885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7886. EXPECT_EQ(StatusCode::OK_200, res->status);
  7887. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7888. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7889. EXPECT_TRUE(res->body.empty());
  7890. }
  7891. TEST_F(StaticFileCompressionTest, MinLength) {
  7892. auto port = start(enable);
  7893. Client cli(HOST, port);
  7894. // 104 bytes, well under the default floor. Compressing it would add the
  7895. // gzip header and trailer to a body that already fits in one packet.
  7896. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7898. EXPECT_EQ(StatusCode::OK_200, res->status);
  7899. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7900. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  7901. }
  7902. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  7903. auto port = start([](Server &svr) {
  7904. svr.set_static_file_compression(true);
  7905. svr.set_static_file_compression_min_length(1);
  7906. });
  7907. Client cli(HOST, port);
  7908. cli.set_decompress(false);
  7909. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  7910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7911. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7912. // A 9-byte file comes back larger than it went in, because gzip's header and
  7913. // trailer outweigh anything deflate can save. That is the end of the range
  7914. // the floor exists to keep out.
  7915. EXPECT_GT(res->body.size(), 9U);
  7916. }
  7917. TEST_F(StaticFileCompressionTest, MaxLength) {
  7918. auto port = start([](Server &svr) {
  7919. svr.set_static_file_compression(true);
  7920. svr.set_static_file_compression_min_length(0);
  7921. svr.set_static_file_compression_max_length(1024);
  7922. });
  7923. Client cli(HOST, port);
  7924. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  7925. // defines `small` as a macro on Windows.
  7926. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7927. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  7928. EXPECT_FALSE(over->has_header("Content-Encoding"));
  7929. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  7930. // Under it: compressed.
  7931. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7932. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  7933. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  7934. }
  7935. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  7936. auto port = start(enable_without_floor);
  7937. Client cli(HOST, port);
  7938. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  7939. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  7940. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  7941. auto identity_etag = identity->get_header_value("ETag");
  7942. ASSERT_FALSE(identity_etag.empty());
  7943. auto gzipped =
  7944. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7945. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  7946. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  7947. auto gzip_etag = gzipped->get_header_value("ETag");
  7948. ASSERT_FALSE(gzip_etag.empty());
  7949. // Two representations, two validators.
  7950. EXPECT_NE(identity_etag, gzip_etag);
  7951. // Each one revalidates against the request that would produce it...
  7952. auto fresh =
  7953. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  7954. {"If-None-Match", gzip_etag}});
  7955. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  7956. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  7957. auto fresh_identity =
  7958. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  7959. {"If-None-Match", identity_etag}});
  7960. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  7961. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  7962. // ...and not against the other representation.
  7963. auto crossed =
  7964. cli.Get("/dir/index.html",
  7965. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  7966. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  7967. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  7968. }
  7969. // The opt-in covers responses the server reads off disk itself. A caller's own
  7970. // known-length provider keeps its Content-Length and, more importantly, keeps
  7971. // delivering incrementally: routing it through a compressor would hold every
  7972. // write back until zlib's window filled.
  7973. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  7974. auto port = start(enable);
  7975. Client cli(HOST, port);
  7976. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  7977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7978. EXPECT_EQ(StatusCode::OK_200, res->status);
  7979. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7980. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7981. EXPECT_EQ("aaabbb", res->body);
  7982. }
  7983. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  7984. auto port = start(enable);
  7985. Client cli(HOST, port);
  7986. cli.set_read_timeout(1, 0);
  7987. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  7988. Headers{{"Accept-Encoding", "gzip"}});
  7989. ASSERT_TRUE(handle.is_valid());
  7990. // The provider writes 100 bytes and then stalls for longer than the read
  7991. // timeout. Those first bytes have to arrive anyway: run the response through
  7992. // a compressor and zlib holds them until its window fills, so the read would
  7993. // come back empty instead.
  7994. char buf[256];
  7995. auto n = handle.read(buf, sizeof(buf));
  7996. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  7997. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  7998. }
  7999. #endif
  8000. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8001. TEST_F(ServerTest, Brotli) {
  8002. Headers headers;
  8003. headers.emplace("Accept-Encoding", "br");
  8004. auto res = cli_.Get("/compress", headers);
  8005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8006. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8007. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8008. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8009. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8010. "7890123456789012345678901234567890",
  8011. res->body);
  8012. EXPECT_EQ(StatusCode::OK_200, res->status);
  8013. }
  8014. #endif
  8015. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8016. TEST_F(ServerTest, Zstd) {
  8017. Headers headers;
  8018. headers.emplace("Accept-Encoding", "zstd");
  8019. auto res = cli_.Get("/compress", headers);
  8020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8021. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8022. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8023. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8024. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8025. "7890123456789012345678901234567890",
  8026. res->body);
  8027. EXPECT_EQ(StatusCode::OK_200, res->status);
  8028. }
  8029. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8030. Headers headers;
  8031. headers.emplace("Accept-Encoding", "");
  8032. auto res = cli_.Get("/compress", headers);
  8033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8034. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8035. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8036. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8037. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8038. "7890123456789012345678901234567890",
  8039. res->body);
  8040. EXPECT_EQ(StatusCode::OK_200, res->status);
  8041. }
  8042. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8043. Headers headers;
  8044. headers.emplace("Accept-Encoding", "zstd");
  8045. std::string body;
  8046. auto res = cli_.Get("/compress", headers,
  8047. [&](const char *data, uint64_t data_length) {
  8048. EXPECT_EQ(100U, data_length);
  8049. body.append(data, data_length);
  8050. return true;
  8051. });
  8052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8053. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8054. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8055. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8056. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8057. "7890123456789012345678901234567890",
  8058. body);
  8059. EXPECT_EQ(StatusCode::OK_200, res->status);
  8060. }
  8061. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8062. Headers headers;
  8063. headers.emplace("Accept-Encoding", "zstd");
  8064. cli_.set_decompress(false);
  8065. auto res = cli_.Get("/compress", headers);
  8066. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8067. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8068. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8069. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8071. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8072. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8073. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8074. EXPECT_EQ(StatusCode::OK_200, res->status);
  8075. ASSERT_EQ(26U, res->body.size());
  8076. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8077. 0);
  8078. }
  8079. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8080. Headers headers;
  8081. headers.emplace("Accept-Encoding", "");
  8082. std::string body;
  8083. auto res = cli_.Get("/compress", headers,
  8084. [&](const char *data, uint64_t data_length) {
  8085. EXPECT_EQ(100U, data_length);
  8086. body.append(data, data_length);
  8087. return true;
  8088. });
  8089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8090. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8091. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8092. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8093. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8094. "7890123456789012345678901234567890",
  8095. body);
  8096. EXPECT_EQ(StatusCode::OK_200, res->status);
  8097. }
  8098. TEST_F(ServerTest, NoZstd) {
  8099. Headers headers;
  8100. headers.emplace("Accept-Encoding", "zstd");
  8101. auto res = cli_.Get("/nocompress", headers);
  8102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8103. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8104. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8105. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8106. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8107. "7890123456789012345678901234567890",
  8108. res->body);
  8109. EXPECT_EQ(StatusCode::OK_200, res->status);
  8110. }
  8111. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8112. Headers headers;
  8113. headers.emplace("Accept-Encoding", "zstd");
  8114. std::string body;
  8115. auto res = cli_.Get("/nocompress", headers,
  8116. [&](const char *data, uint64_t data_length) {
  8117. EXPECT_EQ(100U, data_length);
  8118. body.append(data, data_length);
  8119. return true;
  8120. });
  8121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8122. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8123. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8124. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8125. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8126. "7890123456789012345678901234567890",
  8127. body);
  8128. EXPECT_EQ(StatusCode::OK_200, res->status);
  8129. }
  8130. // TODO: How to enable zstd ??
  8131. TEST_F(ServerTest, MultipartFormDataZstd) {
  8132. UploadFormDataItems items = {
  8133. {"key1", "test", "", ""},
  8134. {"key2", "--abcdefg123", "", ""},
  8135. };
  8136. Headers headers;
  8137. headers.emplace("Accept-Encoding", "zstd");
  8138. cli_.set_compress(true);
  8139. auto res = cli_.Post("/compress-multipart", headers, items);
  8140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8141. EXPECT_EQ(StatusCode::OK_200, res->status);
  8142. }
  8143. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8144. Headers headers;
  8145. headers.emplace("Accept-Encoding", "zstd");
  8146. cli_.set_compress(true);
  8147. auto res = cli_.Put(
  8148. "/put", headers, 3,
  8149. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8150. sink.os << "PUT";
  8151. return true;
  8152. },
  8153. "text/plain");
  8154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8155. EXPECT_EQ(StatusCode::OK_200, res->status);
  8156. EXPECT_EQ("PUT", res->body);
  8157. }
  8158. // Pre-compression logging tests
  8159. TEST_F(ServerTest, PreCompressionLogging) {
  8160. // Test data for compression (matches the actual /compress endpoint content)
  8161. const std::string test_content =
  8162. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8163. "3456789012345678901234567890";
  8164. // Variables to capture logging data
  8165. std::string pre_compression_body;
  8166. std::string pre_compression_content_type;
  8167. std::string pre_compression_content_encoding;
  8168. std::string post_compression_body;
  8169. std::string post_compression_content_type;
  8170. std::string post_compression_content_encoding;
  8171. // Set up pre-compression logger
  8172. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8173. const Response &res) {
  8174. pre_compression_body = res.body;
  8175. pre_compression_content_type = res.get_header_value("Content-Type");
  8176. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8177. });
  8178. // Set up post-compression logger
  8179. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8180. post_compression_body = res.body;
  8181. post_compression_content_type = res.get_header_value("Content-Type");
  8182. post_compression_content_encoding =
  8183. res.get_header_value("Content-Encoding");
  8184. });
  8185. // Test with gzip compression
  8186. Headers headers;
  8187. headers.emplace("Accept-Encoding", "gzip");
  8188. auto res = cli_.Get("/compress", headers);
  8189. // Verify response was compressed
  8190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8191. EXPECT_EQ(StatusCode::OK_200, res->status);
  8192. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8193. // Verify pre-compression logger captured uncompressed content
  8194. EXPECT_EQ(test_content, pre_compression_body);
  8195. EXPECT_EQ("text/plain", pre_compression_content_type);
  8196. EXPECT_TRUE(pre_compression_content_encoding
  8197. .empty()); // No encoding header before compression
  8198. // Verify post-compression logger captured compressed content
  8199. EXPECT_NE(test_content,
  8200. post_compression_body); // Should be different after compression
  8201. EXPECT_EQ("text/plain", post_compression_content_type);
  8202. EXPECT_EQ("gzip", post_compression_content_encoding);
  8203. // Verify compressed content is smaller
  8204. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8205. }
  8206. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8207. const std::string test_content =
  8208. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8209. "3456789012345678901234567890";
  8210. std::string pre_compression_body;
  8211. std::string post_compression_body;
  8212. svr_.set_pre_compression_logger(
  8213. [&](const Request & /*req*/, const Response &res) {
  8214. pre_compression_body = res.body;
  8215. });
  8216. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8217. post_compression_body = res.body;
  8218. });
  8219. Headers headers;
  8220. headers.emplace("Accept-Encoding", "br");
  8221. auto res = cli_.Get("/compress", headers);
  8222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8223. EXPECT_EQ(StatusCode::OK_200, res->status);
  8224. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8225. // Verify pre-compression content is uncompressed
  8226. EXPECT_EQ(test_content, pre_compression_body);
  8227. // Verify post-compression content is compressed
  8228. EXPECT_NE(test_content, post_compression_body);
  8229. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8230. }
  8231. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8232. const std::string test_content =
  8233. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8234. "3456789012345678901234567890";
  8235. std::string pre_compression_body;
  8236. std::string post_compression_body;
  8237. svr_.set_pre_compression_logger(
  8238. [&](const Request & /*req*/, const Response &res) {
  8239. pre_compression_body = res.body;
  8240. });
  8241. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8242. post_compression_body = res.body;
  8243. });
  8244. // Request without compression (use /nocompress endpoint)
  8245. Headers headers;
  8246. auto res = cli_.Get("/nocompress", headers);
  8247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8248. EXPECT_EQ(StatusCode::OK_200, res->status);
  8249. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8250. // Pre-compression logger should not be called when no compression is applied
  8251. EXPECT_TRUE(
  8252. pre_compression_body.empty()); // Pre-compression logger not called
  8253. EXPECT_EQ(
  8254. test_content,
  8255. post_compression_body); // Post-compression logger captures final content
  8256. }
  8257. TEST_F(ServerTest, LoggerSeesContentLength) {
  8258. size_t logged_content_length = 0;
  8259. std::string logged_content_length_header;
  8260. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8261. logged_content_length = res.content_length_;
  8262. logged_content_length_header = res.get_header_value("Content-Length");
  8263. });
  8264. auto res = cli_.Get("/nocompress");
  8265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8266. EXPECT_EQ(StatusCode::OK_200, res->status);
  8267. EXPECT_EQ(res->body.size(), logged_content_length);
  8268. EXPECT_EQ(std::to_string(logged_content_length),
  8269. logged_content_length_header);
  8270. }
  8271. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8272. const std::string test_content =
  8273. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8274. "3456789012345678901234567890";
  8275. std::string pre_compression_body;
  8276. bool pre_logger_called = false;
  8277. // Set only pre-compression logger
  8278. svr_.set_pre_compression_logger(
  8279. [&](const Request & /*req*/, const Response &res) {
  8280. pre_compression_body = res.body;
  8281. pre_logger_called = true;
  8282. });
  8283. Headers headers;
  8284. headers.emplace("Accept-Encoding", "gzip");
  8285. auto res = cli_.Get("/compress", headers);
  8286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8287. EXPECT_EQ(StatusCode::OK_200, res->status);
  8288. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8289. // Verify pre-compression logger was called
  8290. EXPECT_TRUE(pre_logger_called);
  8291. EXPECT_EQ(test_content, pre_compression_body);
  8292. }
  8293. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8294. {
  8295. // Test with Expect: 100-continue header - success case
  8296. // Server returns 100 Continue, client sends body, server returns 200 OK
  8297. Request req;
  8298. req.method = "POST";
  8299. req.path = "/post-large";
  8300. req.set_header("Expect", "100-continue");
  8301. req.body = LARGE_DATA;
  8302. Response res;
  8303. auto error = Error::Success;
  8304. cli_.set_keep_alive(true);
  8305. auto ret = cli_.send(req, res, error);
  8306. EXPECT_TRUE(ret);
  8307. EXPECT_EQ(StatusCode::OK_200, res.status);
  8308. EXPECT_EQ(LARGE_DATA, res.body);
  8309. }
  8310. {
  8311. // Test with Expect: 100-continue header - error case
  8312. // Client should not send the body when server returns an error
  8313. Request req;
  8314. req.method = "POST";
  8315. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8316. req.set_header("Expect", "100-continue");
  8317. req.body = LARGE_DATA;
  8318. Response res;
  8319. auto error = Error::Success;
  8320. auto start = std::chrono::high_resolution_clock::now();
  8321. cli_.set_keep_alive(true);
  8322. auto ret = cli_.send(req, res, error);
  8323. auto end = std::chrono::high_resolution_clock::now();
  8324. auto elapsed =
  8325. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8326. .count();
  8327. // With Expect: 100-continue, request completes successfully but with error
  8328. EXPECT_TRUE(ret);
  8329. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8330. EXPECT_EQ("close", res.get_header_value("Connection"));
  8331. EXPECT_FALSE(cli_.is_socket_open());
  8332. EXPECT_LE(elapsed, 2000);
  8333. }
  8334. {
  8335. // Send an extra GET request to ensure error recovery without hanging
  8336. Request req;
  8337. req.method = "GET";
  8338. req.path = "/hi";
  8339. auto start = std::chrono::high_resolution_clock::now();
  8340. auto res = cli_.send(req);
  8341. auto end = std::chrono::high_resolution_clock::now();
  8342. auto elapsed =
  8343. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8344. .count();
  8345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8346. EXPECT_EQ(StatusCode::OK_200, res->status);
  8347. EXPECT_EQ("Hello World!", res->body);
  8348. EXPECT_LE(elapsed, 500);
  8349. }
  8350. }
  8351. TEST(ZstdDecompressor, ChunkedDecompression) {
  8352. std::string data;
  8353. for (size_t i = 0; i < 32 * 1024; ++i) {
  8354. data.push_back(static_cast<char>('a' + i % 26));
  8355. }
  8356. std::string compressed_data;
  8357. {
  8358. httplib::detail::zstd_compressor compressor;
  8359. bool result = compressor.compress(
  8360. data.data(), data.size(),
  8361. /*last=*/true,
  8362. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8363. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8364. compressed_data_size);
  8365. return true;
  8366. });
  8367. ASSERT_TRUE(result);
  8368. }
  8369. std::string decompressed_data;
  8370. {
  8371. httplib::detail::zstd_decompressor decompressor;
  8372. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8373. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8374. size_t chunk_size = 130;
  8375. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8376. chunk_begin += chunk_size) {
  8377. size_t current_chunk_size =
  8378. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8379. bool result = decompressor.decompress(
  8380. compressed_data.data() + chunk_begin, current_chunk_size,
  8381. [&](const char *decompressed_data_chunk,
  8382. size_t decompressed_data_chunk_size) {
  8383. decompressed_data.insert(decompressed_data.size(),
  8384. decompressed_data_chunk,
  8385. decompressed_data_chunk_size);
  8386. return true;
  8387. });
  8388. ASSERT_TRUE(result);
  8389. }
  8390. }
  8391. ASSERT_EQ(data, decompressed_data);
  8392. }
  8393. TEST(ZstdDecompressor, Decompress) {
  8394. std::string original_text = "Compressed with ZSTD";
  8395. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8396. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8397. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8398. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8399. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8400. std::string decompressed_data;
  8401. {
  8402. httplib::detail::zstd_decompressor decompressor;
  8403. bool result = decompressor.decompress(
  8404. compressed_data.data(), compressed_data.size(),
  8405. [&](const char *decompressed_data_chunk,
  8406. size_t decompressed_data_chunk_size) {
  8407. decompressed_data.insert(decompressed_data.size(),
  8408. decompressed_data_chunk,
  8409. decompressed_data_chunk_size);
  8410. return true;
  8411. });
  8412. ASSERT_TRUE(result);
  8413. }
  8414. ASSERT_EQ(original_text, decompressed_data);
  8415. }
  8416. #endif
  8417. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8418. // separate chunks so that the server sees each part in its own read(). Used to
  8419. // place a read boundary at a specific offset of a request body.
  8420. static bool send_request_in_parts(time_t read_timeout_sec,
  8421. const std::vector<std::string> &parts,
  8422. std::string *resp = nullptr,
  8423. int port = PORT) {
  8424. auto error = Error::Success;
  8425. auto client_sock = detail::create_client_socket(
  8426. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8427. /*connection_timeout_sec=*/5, 0,
  8428. /*read_timeout_sec=*/5, 0,
  8429. /*write_timeout_sec=*/5, 0, std::string(), error);
  8430. if (client_sock == INVALID_SOCKET) { return false; }
  8431. auto ret = detail::process_client_socket(
  8432. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8433. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8434. for (size_t i = 0; i < parts.size(); i++) {
  8435. const auto &part = parts[i];
  8436. if (part.size() !=
  8437. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8438. return false;
  8439. }
  8440. if (i + 1 < parts.size()) {
  8441. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8442. }
  8443. }
  8444. char buf[512];
  8445. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8446. while (line_reader.getline()) {
  8447. if (resp) { *resp += line_reader.ptr(); }
  8448. }
  8449. return true;
  8450. });
  8451. detail::close_socket(client_sock);
  8452. return ret;
  8453. }
  8454. // Sends a raw request to a server listening at HOST:PORT.
  8455. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8456. std::string *resp = nullptr, int port = PORT) {
  8457. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8458. }
  8459. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8460. Server svr;
  8461. std::string header_value;
  8462. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8463. header_value = req.get_header_value("foo");
  8464. res.set_content("ok", "text/plain");
  8465. });
  8466. thread t = thread([&] { svr.listen(HOST, PORT); });
  8467. auto se = detail::scope_exit([&] {
  8468. svr.stop();
  8469. t.join();
  8470. ASSERT_FALSE(svr.is_running());
  8471. });
  8472. svr.wait_until_ready();
  8473. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8474. // like characters are not treated the same - use vertical tab and escape.
  8475. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8476. "foo: \t \v bar \x1B\t \r\n"
  8477. "Connection: close\r\n"
  8478. "\r\n";
  8479. std::string res;
  8480. ASSERT_TRUE(send_request(5, req, &res));
  8481. EXPECT_EQ(header_value, "");
  8482. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8483. }
  8484. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8485. Server svr;
  8486. std::string received;
  8487. svr.Get("/order", [&](const Request &req, Response &res) {
  8488. received = entries_to_string(req.headers);
  8489. res.set_content("ok", "text/plain");
  8490. });
  8491. auto port = svr.bind_to_any_port(HOST);
  8492. thread t = thread([&] { svr.listen_after_bind(); });
  8493. auto se = detail::scope_exit([&] {
  8494. svr.stop();
  8495. t.join();
  8496. ASSERT_FALSE(svr.is_running());
  8497. });
  8498. svr.wait_until_ready();
  8499. const std::string req = "GET /order HTTP/1.1\r\n"
  8500. "X-First: 1\r\n"
  8501. "X-Dup: a\r\n"
  8502. "X-Second: 2\r\n"
  8503. "X-Dup: b\r\n"
  8504. "Connection: close\r\n"
  8505. "\r\n";
  8506. std::string res;
  8507. ASSERT_TRUE(send_request(5, req, &res, port));
  8508. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8509. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8510. }
  8511. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8512. Server svr;
  8513. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8514. res.set_header("Set-Cookie", "first=1");
  8515. res.set_header("X-Between", "y");
  8516. res.set_header("Set-Cookie", "second=2");
  8517. res.set_content("ok", "text/plain");
  8518. });
  8519. auto port = svr.bind_to_any_port(HOST);
  8520. thread t = thread([&] { svr.listen_after_bind(); });
  8521. auto se = detail::scope_exit([&] {
  8522. svr.stop();
  8523. t.join();
  8524. ASSERT_FALSE(svr.is_running());
  8525. });
  8526. svr.wait_until_ready();
  8527. Client cli(HOST, port);
  8528. auto res = cli.Get("/cookies");
  8529. ASSERT_TRUE(res);
  8530. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8531. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8532. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8533. }
  8534. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8535. Server svr;
  8536. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8537. auto i = new int(0);
  8538. res.set_header("Trailer", "X-Safe, X-Reflected");
  8539. res.set_chunked_content_provider(
  8540. "text/plain",
  8541. [i](size_t /*offset*/, DataSink &sink) {
  8542. if (*i == 0) {
  8543. sink.os << "body";
  8544. } else {
  8545. Headers trailer;
  8546. // A valid trailer that must survive.
  8547. trailer.emplace("X-Safe", "safe");
  8548. // Attacker-controlled value carrying CR/LF (response splitting).
  8549. trailer.emplace("X-Reflected",
  8550. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8551. // Attacker-controlled name carrying CR/LF.
  8552. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8553. sink.done_with_trailer(trailer);
  8554. }
  8555. (*i)++;
  8556. return true;
  8557. },
  8558. [i](bool /*success*/) { delete i; });
  8559. });
  8560. thread t = thread([&] { svr.listen(HOST, PORT); });
  8561. auto se = detail::scope_exit([&] {
  8562. svr.stop();
  8563. t.join();
  8564. ASSERT_FALSE(svr.is_running());
  8565. });
  8566. svr.wait_until_ready();
  8567. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8568. "Host: " + HOST +
  8569. "\r\n"
  8570. "Connection: close\r\n"
  8571. "\r\n";
  8572. std::string res;
  8573. ASSERT_TRUE(send_request(5, req, &res));
  8574. // The injected fields must not appear anywhere in the raw response.
  8575. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8576. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8577. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8578. // Invalid trailers are dropped entirely, matching set_header().
  8579. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8580. // The valid trailer still passes through.
  8581. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8582. }
  8583. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8584. Server svr;
  8585. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8586. // res.headers is a public field an application can populate directly,
  8587. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8588. // A valid header that must survive.
  8589. res.headers.emplace("X-Safe", "safe");
  8590. // Attacker-controlled value carrying CR/LF (response splitting).
  8591. res.headers.emplace("X-Reflected",
  8592. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8593. // Attacker-controlled name carrying CR/LF.
  8594. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8595. res.set_content("body", "text/plain");
  8596. });
  8597. thread t = thread([&] { svr.listen(HOST, PORT); });
  8598. auto se = detail::scope_exit([&] {
  8599. svr.stop();
  8600. t.join();
  8601. ASSERT_FALSE(svr.is_running());
  8602. });
  8603. svr.wait_until_ready();
  8604. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8605. "Host: " + HOST +
  8606. "\r\n"
  8607. "Connection: close\r\n"
  8608. "\r\n";
  8609. std::string res;
  8610. ASSERT_TRUE(send_request(5, req, &res));
  8611. // The injected fields must not appear anywhere in the raw response.
  8612. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8613. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8614. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8615. // Invalid headers are dropped entirely, matching set_header().
  8616. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8617. // The valid header still passes through.
  8618. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8619. }
  8620. // Forward declaration: in split builds split.py strips `inline` and moves the
  8621. // definition into httplib.cc, so detail::write_request_line is not visible from
  8622. // the public httplib.h. Re-declaring it here lets the tests link against the
  8623. // symbol in both header-only and split builds.
  8624. namespace httplib {
  8625. namespace detail {
  8626. ssize_t write_request_line(Stream &strm, const std::string &method,
  8627. const std::string &path);
  8628. } // namespace detail
  8629. } // namespace httplib
  8630. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8631. // A well-formed target is written verbatim.
  8632. {
  8633. detail::BufferStream strm;
  8634. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8635. EXPECT_GT(n, 0);
  8636. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8637. }
  8638. // A target carrying CR/LF, SP or other control octets must be rejected
  8639. // before anything reaches the wire, otherwise it splits the request line and
  8640. // injects a header or a whole request.
  8641. const std::string evil_targets[] = {
  8642. "/a\r\nInjected: pwned",
  8643. "/a\rInjected",
  8644. "/a\nInjected",
  8645. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8646. "/a b",
  8647. "/a\tb",
  8648. "/a\x7f",
  8649. };
  8650. for (const auto &evil : evil_targets) {
  8651. detail::BufferStream strm;
  8652. auto n = detail::write_request_line(strm, "GET", evil);
  8653. EXPECT_LT(n, 0);
  8654. EXPECT_TRUE(strm.get_buffer().empty());
  8655. }
  8656. }
  8657. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8658. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8659. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8660. // target reaches write_request. The client must fail cleanly with
  8661. // Error::Write instead of putting a request-line-less, header-injecting
  8662. // request on the wire.
  8663. Server svr;
  8664. svr.Get("/a", [](const Request &, Response &res) {
  8665. res.set_content("ok", "text/plain");
  8666. });
  8667. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8668. auto se = detail::scope_exit([&] {
  8669. svr.stop();
  8670. thread.join();
  8671. ASSERT_FALSE(svr.is_running());
  8672. });
  8673. svr.wait_until_ready();
  8674. {
  8675. Client cli(HOST, PORT);
  8676. cli.set_path_encode(false);
  8677. // The request is rejected before anything is written, so the connection
  8678. // stays silent and the subsequent response read would otherwise block for
  8679. // the full default read timeout. Shorten it -- the assertion is on the
  8680. // error, not the timeout.
  8681. cli.set_read_timeout(1, 0);
  8682. auto res = cli.Get("/a\r\nInjected: pwned");
  8683. EXPECT_FALSE(res);
  8684. EXPECT_EQ(Error::Write, res.error());
  8685. }
  8686. }
  8687. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8688. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8689. // including extension methods.
  8690. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8691. for (const auto &method : good_methods) {
  8692. detail::BufferStream strm;
  8693. auto n = detail::write_request_line(strm, method, "/");
  8694. EXPECT_GT(n, 0);
  8695. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8696. }
  8697. // A method carrying CR/LF would split the request line and smuggle a whole
  8698. // request ahead of the real one. A space or an empty method corrupts the
  8699. // request line. All must be rejected before anything reaches the wire.
  8700. const std::string evil_methods[] = {
  8701. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8702. "GET\r\nInjected: pwned",
  8703. "GET\r",
  8704. "GET\n",
  8705. "GE T",
  8706. "",
  8707. };
  8708. for (const auto &evil : evil_methods) {
  8709. detail::BufferStream strm;
  8710. auto n = detail::write_request_line(strm, evil, "/");
  8711. EXPECT_LT(n, 0);
  8712. EXPECT_TRUE(strm.get_buffer().empty());
  8713. }
  8714. }
  8715. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  8716. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  8717. // through Client::send must fail with Error::Write and no request, neither
  8718. // the smuggled one nor the real one, may reach the server.
  8719. Server svr;
  8720. std::atomic<int> request_count(0);
  8721. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  8722. request_count++;
  8723. res.status = StatusCode::OK_200;
  8724. return Server::HandlerResponse::Handled;
  8725. });
  8726. auto port = svr.bind_to_any_port(HOST);
  8727. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8728. auto se = detail::scope_exit([&] {
  8729. svr.stop();
  8730. thread.join();
  8731. ASSERT_FALSE(svr.is_running());
  8732. });
  8733. svr.wait_until_ready();
  8734. {
  8735. Client cli(HOST, port);
  8736. const std::string evil_methods[] = {
  8737. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8738. "GE T",
  8739. "",
  8740. };
  8741. for (const auto &evil : evil_methods) {
  8742. Request req;
  8743. req.method = evil;
  8744. req.path = "/";
  8745. auto res = cli.send(req);
  8746. EXPECT_FALSE(res);
  8747. EXPECT_EQ(Error::Write, res.error());
  8748. }
  8749. auto handle =
  8750. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  8751. EXPECT_FALSE(handle.is_valid());
  8752. EXPECT_EQ(Error::Write, handle.error);
  8753. // A valid request on the same client still goes through.
  8754. auto res = cli.Get("/");
  8755. ASSERT_TRUE(res);
  8756. EXPECT_EQ(StatusCode::OK_200, res->status);
  8757. }
  8758. EXPECT_EQ(1, request_count.load());
  8759. }
  8760. // Sends a raw request and verifies that there isn't a crash or exception.
  8761. static void test_raw_request(const std::string &req,
  8762. std::string *out = nullptr) {
  8763. Server svr;
  8764. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8765. res.set_content("ok", "text/plain");
  8766. });
  8767. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8768. res.set_content("ok", "text/plain");
  8769. });
  8770. svr.Get("/header_field_value_check",
  8771. [&](const Request & /*req*/, Response &res) {
  8772. res.set_content("ok", "text/plain");
  8773. });
  8774. svr.CustomRoute("PROPFIND", "/dav",
  8775. [&](const Request & /*req*/, Response &res) {
  8776. res.status = StatusCode::MultiStatus_207;
  8777. });
  8778. // Server read timeout must be longer than the client read timeout for the
  8779. // bug to reproduce, probably to force the server to process a request
  8780. // without a trailing blank line.
  8781. const time_t client_read_timeout_sec = 1;
  8782. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8783. bool listen_thread_ok = false;
  8784. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8785. auto se = detail::scope_exit([&] {
  8786. svr.stop();
  8787. t.join();
  8788. ASSERT_FALSE(svr.is_running());
  8789. EXPECT_TRUE(listen_thread_ok);
  8790. });
  8791. svr.wait_until_ready();
  8792. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8793. }
  8794. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8795. // A certain header line causes an exception if the header property is parsed
  8796. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8797. test_raw_request(
  8798. "GET /hi HTTP/1.1\r\n"
  8799. " : "
  8800. " "
  8801. " ");
  8802. }
  8803. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8804. // A certain header line causes an exception if the header property *name* is
  8805. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8806. // greedy matcher and requires backtracking when there are a lot of ":"
  8807. // characters.
  8808. // This occurs with libc++ but not libstdc++.
  8809. test_raw_request(
  8810. "GET /hi HTTP/1.1\r\n"
  8811. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8812. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8813. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8814. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8815. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8816. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8817. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8818. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8819. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8820. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8821. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8822. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8823. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8824. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8825. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8826. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8827. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8828. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8829. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8830. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8831. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8832. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8833. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8834. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8835. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8836. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8837. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8838. "&&&%%%");
  8839. }
  8840. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8841. // Make sure this doesn't crash the server.
  8842. // In a previous version of the header line regex, the "\r" rendered the line
  8843. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8844. // a new position where the leading white space ended and the field value
  8845. // began.
  8846. // The crash occurs with libc++ but not libstdc++.
  8847. test_raw_request("GET /hi HTTP/1.1\r\n"
  8848. "a:" +
  8849. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8850. "\r\n"
  8851. "\r\n");
  8852. }
  8853. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8854. std::string out;
  8855. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8856. "Content-Type: text/plain\r\n"
  8857. "Transfer-Encoding: chunked\r\n"
  8858. "\r\n"
  8859. "nothex\r\n",
  8860. &out);
  8861. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8862. }
  8863. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8864. std::string out;
  8865. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8866. "Content-Type: text/plain\r\n"
  8867. "Transfer-Encoding: chunked\r\n"
  8868. "\r\n"
  8869. "3\r\n"
  8870. "xyz\r\n"
  8871. "NaN\r\n",
  8872. &out);
  8873. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8874. }
  8875. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8876. std::string out;
  8877. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8878. "Content-Type: text/plain\r\n"
  8879. "Transfer-Encoding: chunked\r\n"
  8880. "\r\n"
  8881. // Length is too large for 64 bits.
  8882. "1ffffffffffffffff\r\n"
  8883. "xyz\r\n",
  8884. &out);
  8885. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8886. }
  8887. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8888. test_raw_request("GET /hi HTTP/1.1\r\n"
  8889. "Content-Type: text/plain\r\n\r");
  8890. }
  8891. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8892. std::string out;
  8893. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8894. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8895. }
  8896. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  8897. for (auto target : {"/h\ri", "/h\x7fi"}) {
  8898. std::string out;
  8899. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  8900. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  8901. }
  8902. }
  8903. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  8904. std::string out;
  8905. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  8906. "Connection: close\r\n\r\n",
  8907. &out);
  8908. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8909. }
  8910. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8911. Server svr;
  8912. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8913. EXPECT_TRUE(!req.remote_addr.empty());
  8914. });
  8915. thread t = thread([&] { svr.listen(HOST, PORT); });
  8916. auto se = detail::scope_exit([&] {
  8917. svr.stop();
  8918. t.join();
  8919. ASSERT_FALSE(svr.is_running());
  8920. });
  8921. svr.wait_until_ready();
  8922. // Send an invalid request line to trigger Bad Request
  8923. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8924. std::string out;
  8925. ASSERT_TRUE(send_request(5, bad_req, &out));
  8926. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8927. }
  8928. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8929. // answered right away rather than blocking on a read that waits for EOF.
  8930. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  8931. std::string out;
  8932. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  8933. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  8934. }
  8935. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  8936. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  8937. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  8938. for (const auto *method : methods) {
  8939. Server svr;
  8940. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8941. EXPECT_FALSE(svr.is_valid()) << method;
  8942. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  8943. }
  8944. }
  8945. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  8946. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  8947. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  8948. for (const auto *method : methods) {
  8949. Server svr;
  8950. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8951. EXPECT_FALSE(svr.is_valid()) << method;
  8952. }
  8953. }
  8954. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  8955. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  8956. "COPY", "MOVE", "LOCK",
  8957. "UNLOCK", "REPORT", "SUBSCRIBE"};
  8958. Server svr;
  8959. for (const auto *method : methods) {
  8960. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8961. }
  8962. EXPECT_TRUE(svr.is_valid());
  8963. }
  8964. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  8965. Server svr;
  8966. svr.CustomRoute("POST", "/x",
  8967. [](const Request &, Response &, const ContentReader &) {});
  8968. EXPECT_FALSE(svr.is_valid());
  8969. }
  8970. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  8971. Server svr;
  8972. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  8973. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  8974. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  8975. EXPECT_FALSE(svr.is_valid());
  8976. }
  8977. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  8978. Server svr;
  8979. auto captured = Error::Success;
  8980. svr.set_error_logger(
  8981. [&](const Error &err, const Request * /*req*/) { captured = err; });
  8982. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  8983. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  8984. }
  8985. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  8986. std::string out;
  8987. std::string request(
  8988. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  8989. test_raw_request(request, &out);
  8990. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8991. }
  8992. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  8993. std::string out;
  8994. std::string request(
  8995. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  8996. test_raw_request(request, &out);
  8997. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8998. }
  8999. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9000. std::string out;
  9001. std::string request(
  9002. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9003. test_raw_request(request, &out);
  9004. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9005. }
  9006. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9007. std::string out;
  9008. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9009. "Test: \r\n\r\n",
  9010. &out);
  9011. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9012. }
  9013. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9014. Server svr;
  9015. std::string x_custom;
  9016. std::string cookie;
  9017. std::string xff;
  9018. std::string x_unicode;
  9019. std::string x_iis;
  9020. svr.Get("/check", [&](const Request &req, Response &res) {
  9021. x_custom = req.get_header_value("X-Custom");
  9022. cookie = req.get_header_value("Cookie");
  9023. xff = req.get_header_value("X-Forwarded-For");
  9024. x_unicode = req.get_header_value("X-Unicode");
  9025. x_iis = req.get_header_value("X-IIS");
  9026. res.set_content("ok", "text/plain");
  9027. });
  9028. thread t = thread([&] { svr.listen(HOST, PORT); });
  9029. auto se = detail::scope_exit([&] {
  9030. svr.stop();
  9031. t.join();
  9032. ASSERT_FALSE(svr.is_running());
  9033. });
  9034. svr.wait_until_ready();
  9035. const std::string req = "GET /check HTTP/1.1\r\n"
  9036. "Host: localhost\r\n"
  9037. "X-Custom: a%0D%0AInjected: b\r\n"
  9038. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9039. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9040. "X-Unicode: %E3%81%82\r\n"
  9041. "X-IIS: %u00E9\r\n"
  9042. "Connection: close\r\n"
  9043. "\r\n";
  9044. std::string res;
  9045. ASSERT_TRUE(send_request(5, req, &res));
  9046. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9047. // Every value must be returned verbatim (wire form), with no decoding.
  9048. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9049. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9050. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9051. EXPECT_EQ("%E3%81%82", x_unicode);
  9052. EXPECT_EQ("%u00E9", x_iis);
  9053. }
  9054. // Applications that previously relied on automatic percent-decoding can
  9055. // reproduce the old behavior by explicitly calling decode_path_component()
  9056. // or, for RFC 3986 conformance, decode_uri_component().
  9057. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9058. Server svr;
  9059. std::string decoded;
  9060. svr.Get("/check", [&](const Request &req, Response &res) {
  9061. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9062. res.set_content("ok", "text/plain");
  9063. });
  9064. thread t = thread([&] { svr.listen(HOST, PORT); });
  9065. auto se = detail::scope_exit([&] {
  9066. svr.stop();
  9067. t.join();
  9068. ASSERT_FALSE(svr.is_running());
  9069. });
  9070. svr.wait_until_ready();
  9071. const std::string req = "GET /check HTTP/1.1\r\n"
  9072. "Host: localhost\r\n"
  9073. "X-Custom: hello%20world\r\n"
  9074. "Connection: close\r\n"
  9075. "\r\n";
  9076. std::string res;
  9077. ASSERT_TRUE(send_request(5, req, &res));
  9078. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9079. EXPECT_EQ("hello world", decoded);
  9080. }
  9081. // Regression test for #2033. Browsers send Referer values that include
  9082. // percent-encoded characters such as %0A inside the URL. Decoding the
  9083. // header value would either trip the post-decode CR/LF/NUL guard (the
  9084. // original bug, returning 400) or, after that guard was relaxed, silently
  9085. // store a literal LF — both unacceptable. The wire form must round-trip.
  9086. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9087. Server svr;
  9088. std::string referer;
  9089. svr.Get("/check", [&](const Request &req, Response &res) {
  9090. referer = req.get_header_value("Referer");
  9091. res.set_content("ok", "text/plain");
  9092. });
  9093. thread t = thread([&] { svr.listen(HOST, PORT); });
  9094. auto se = detail::scope_exit([&] {
  9095. svr.stop();
  9096. t.join();
  9097. ASSERT_FALSE(svr.is_running());
  9098. });
  9099. svr.wait_until_ready();
  9100. const std::string req = "GET /check HTTP/1.1\r\n"
  9101. "Host: localhost\r\n"
  9102. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9103. "Connection: close\r\n"
  9104. "\r\n";
  9105. std::string res;
  9106. ASSERT_TRUE(send_request(5, req, &res));
  9107. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9108. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9109. }
  9110. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9111. Server svr;
  9112. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9113. res.set_header("Cache-Control", "no-cache");
  9114. res.set_chunked_content_provider(
  9115. "text/event-stream", [](size_t offset, DataSink &sink) {
  9116. std::string s = "data:";
  9117. s += std::to_string(offset);
  9118. s += "\n\n";
  9119. auto ret = sink.write(s.data(), s.size());
  9120. EXPECT_TRUE(ret);
  9121. std::this_thread::sleep_for(std::chrono::seconds(1));
  9122. return true;
  9123. });
  9124. });
  9125. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9126. svr.wait_until_ready();
  9127. Client client(HOST, PORT);
  9128. const Headers headers = {{"Accept", "text/event-stream"}};
  9129. auto get_thread = std::thread([&client, &headers]() {
  9130. auto res = client.Get(
  9131. "/events", headers,
  9132. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9133. });
  9134. auto se = detail::scope_exit([&] {
  9135. svr.stop();
  9136. get_thread.join();
  9137. listen_thread.join();
  9138. ASSERT_FALSE(svr.is_running());
  9139. });
  9140. // Give GET time to get a few messages.
  9141. std::this_thread::sleep_for(std::chrono::seconds(2));
  9142. }
  9143. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9144. httplib::Server svr;
  9145. svr.Post("/hi",
  9146. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9147. res.status = StatusCode::OK_200;
  9148. });
  9149. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9150. svr.wait_until_ready();
  9151. Client cli(HOST, PORT);
  9152. auto res = cli.Post("/hi", "data", "text/plain");
  9153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9154. EXPECT_EQ(StatusCode::OK_200, res->status);
  9155. svr.stop();
  9156. thread.join();
  9157. ASSERT_FALSE(svr.is_running());
  9158. res = cli.Post("/hi", "data", "text/plain");
  9159. ASSERT_FALSE(res);
  9160. }
  9161. TEST(ServerStopTest, ListenFailure) {
  9162. Server svr;
  9163. auto t = thread([&]() {
  9164. auto ret = svr.listen("????", PORT);
  9165. EXPECT_FALSE(ret);
  9166. });
  9167. svr.wait_until_ready();
  9168. svr.stop();
  9169. t.join();
  9170. }
  9171. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9172. TEST(ServerStopTest, Decommision) {
  9173. Server svr;
  9174. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9175. for (int i = 0; i < 4; i++) {
  9176. auto is_even = !(i % 2);
  9177. std::thread t{[&] {
  9178. try {
  9179. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9180. if (is_even) {
  9181. throw std::runtime_error("Some thing that happens to go wrong.");
  9182. }
  9183. svr.listen(HOST, PORT);
  9184. } catch (...) { svr.decommission(); }
  9185. }};
  9186. svr.wait_until_ready();
  9187. // Server is up
  9188. {
  9189. Client cli(HOST, PORT);
  9190. auto res = cli.Get("/hi");
  9191. if (is_even) {
  9192. EXPECT_FALSE(res);
  9193. } else {
  9194. EXPECT_TRUE(res);
  9195. EXPECT_EQ("hi...", res->body);
  9196. }
  9197. }
  9198. svr.stop();
  9199. t.join();
  9200. // Server is down...
  9201. {
  9202. Client cli(HOST, PORT);
  9203. auto res = cli.Get("/hi");
  9204. EXPECT_FALSE(res);
  9205. }
  9206. }
  9207. }
  9208. #endif
  9209. // Helper function for string body upload progress tests
  9210. template <typename SetupHandler, typename ClientCall>
  9211. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9212. ClientCall &&client_call,
  9213. const string &body) {
  9214. Server svr;
  9215. setup_handler(svr);
  9216. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9217. auto se = detail::scope_exit([&] {
  9218. svr.stop();
  9219. t.join();
  9220. });
  9221. svr.wait_until_ready();
  9222. Client cli(HOST, PORT);
  9223. vector<uint64_t> progress_values;
  9224. bool progress_called = false;
  9225. auto res =
  9226. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9227. progress_values.push_back(current);
  9228. progress_called = true;
  9229. return true;
  9230. });
  9231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9232. EXPECT_EQ(200, res->status);
  9233. EXPECT_TRUE(progress_called);
  9234. }
  9235. TEST(UploadProgressTest, PostStringBodyBasic) {
  9236. TestStringBodyUploadProgress(
  9237. [](Server &svr) {
  9238. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9239. res.set_content("received", "text/plain");
  9240. });
  9241. },
  9242. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9243. return cli.Post("/test", body, "text/plain", progress_callback);
  9244. },
  9245. "test data for upload progress");
  9246. }
  9247. TEST(UploadProgressTest, PutStringBodyBasic) {
  9248. TestStringBodyUploadProgress(
  9249. [](Server &svr) {
  9250. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9251. res.set_content("put received", "text/plain");
  9252. });
  9253. },
  9254. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9255. return cli.Put("/test", body, "text/plain", progress_callback);
  9256. },
  9257. "put test data for upload progress");
  9258. }
  9259. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9260. TestStringBodyUploadProgress(
  9261. [](Server &svr) {
  9262. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9263. res.set_content("patch received", "text/plain");
  9264. });
  9265. },
  9266. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9267. return cli.Patch("/test", body, "text/plain", progress_callback);
  9268. },
  9269. "patch test data for upload progress");
  9270. }
  9271. // Helper function for content provider upload progress tests
  9272. template <typename SetupHandler, typename ClientCall>
  9273. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9274. ClientCall &&client_call) {
  9275. Server svr;
  9276. setup_handler(svr);
  9277. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9278. auto se = detail::scope_exit([&] {
  9279. svr.stop();
  9280. t.join();
  9281. });
  9282. svr.wait_until_ready();
  9283. Client cli(HOST, PORT);
  9284. vector<uint64_t> progress_values;
  9285. auto res =
  9286. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9287. progress_values.push_back(current);
  9288. return true;
  9289. });
  9290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9291. EXPECT_EQ(200, res->status);
  9292. EXPECT_FALSE(progress_values.empty());
  9293. }
  9294. TEST(UploadProgressTest, PostContentProviderProgress) {
  9295. TestContentProviderUploadProgress(
  9296. [](Server &svr) {
  9297. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9298. res.set_content("provider received", "text/plain");
  9299. });
  9300. },
  9301. [](Client &cli, UploadProgress progress_callback) {
  9302. return cli.Post(
  9303. "/test", 10,
  9304. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9305. sink.os << "test data";
  9306. return true;
  9307. },
  9308. "text/plain", progress_callback);
  9309. });
  9310. }
  9311. // Helper function for multipart upload progress tests
  9312. template <typename SetupHandler, typename ClientCall>
  9313. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9314. ClientCall &&client_call,
  9315. const string &endpoint) {
  9316. Server svr;
  9317. setup_handler(svr);
  9318. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9319. auto se = detail::scope_exit([&] {
  9320. svr.stop();
  9321. t.join();
  9322. });
  9323. svr.wait_until_ready();
  9324. Client cli(HOST, PORT);
  9325. vector<uint64_t> progress_values;
  9326. UploadFormDataItems items = {
  9327. {"field1", "value1", "", ""},
  9328. {"field2", "longer value for progress tracking test", "", ""},
  9329. {"file1", "file content data for upload progress", "test.txt",
  9330. "text/plain"}};
  9331. auto res = client_call(cli, endpoint, items,
  9332. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9333. progress_values.push_back(current);
  9334. return true;
  9335. });
  9336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9337. EXPECT_EQ(200, res->status);
  9338. EXPECT_FALSE(progress_values.empty());
  9339. }
  9340. TEST(UploadProgressTest, PostMultipartProgress) {
  9341. TestMultipartUploadProgress(
  9342. [](Server &svr) {
  9343. svr.Post("/multipart", [](const Request &req, Response &res) {
  9344. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9345. res.set_content("multipart received", "text/plain");
  9346. });
  9347. },
  9348. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9349. UploadProgress progress_callback) {
  9350. return cli.Post(endpoint, items, progress_callback);
  9351. },
  9352. "/multipart");
  9353. }
  9354. // Helper function for basic download progress tests
  9355. template <typename SetupHandler, typename ClientCall>
  9356. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9357. ClientCall &&client_call, const string &endpoint,
  9358. size_t expected_content_size) {
  9359. Server svr;
  9360. setup_handler(svr);
  9361. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9362. auto se = detail::scope_exit([&] {
  9363. svr.stop();
  9364. t.join();
  9365. });
  9366. svr.wait_until_ready();
  9367. Client cli(HOST, PORT);
  9368. vector<uint64_t> progress_values;
  9369. auto res = client_call(cli, endpoint,
  9370. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9371. progress_values.push_back(current);
  9372. return true;
  9373. });
  9374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9375. EXPECT_EQ(200, res->status);
  9376. EXPECT_FALSE(progress_values.empty());
  9377. EXPECT_EQ(expected_content_size, res->body.size());
  9378. }
  9379. TEST(DownloadProgressTest, GetBasic) {
  9380. TestBasicDownloadProgress(
  9381. [](Server &svr) {
  9382. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9383. string content(1000, 'D');
  9384. res.set_content(content, "text/plain");
  9385. });
  9386. },
  9387. [](Client &cli, const string &endpoint,
  9388. DownloadProgress progress_callback) {
  9389. return cli.Get(endpoint, progress_callback);
  9390. },
  9391. "/download", 1000u);
  9392. }
  9393. // Helper function for content receiver download progress tests
  9394. template <typename SetupHandler, typename ClientCall>
  9395. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9396. ClientCall &&client_call,
  9397. const string &endpoint,
  9398. size_t expected_content_size) {
  9399. Server svr;
  9400. setup_handler(svr);
  9401. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9402. auto se = detail::scope_exit([&] {
  9403. svr.stop();
  9404. t.join();
  9405. });
  9406. svr.wait_until_ready();
  9407. Client cli(HOST, PORT);
  9408. vector<uint64_t> progress_values;
  9409. string received_body;
  9410. auto res = client_call(
  9411. cli, endpoint,
  9412. [&](const char *data, size_t data_length) -> bool {
  9413. received_body.append(data, data_length);
  9414. return true;
  9415. },
  9416. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9417. progress_values.push_back(current);
  9418. return true;
  9419. });
  9420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9421. EXPECT_EQ(200, res->status);
  9422. EXPECT_FALSE(progress_values.empty());
  9423. EXPECT_EQ(expected_content_size, received_body.size());
  9424. EXPECT_TRUE(res->body.empty());
  9425. }
  9426. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9427. TestContentReceiverDownloadProgress(
  9428. [](Server &svr) {
  9429. svr.Get("/download-receiver",
  9430. [](const Request & /*req*/, Response &res) {
  9431. string content(2000, 'R');
  9432. res.set_content(content, "text/plain");
  9433. });
  9434. },
  9435. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9436. DownloadProgress progress_callback) {
  9437. return cli.Get(endpoint, content_receiver, progress_callback);
  9438. },
  9439. "/download-receiver", 2000u);
  9440. }
  9441. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9442. // A provider reaching a pass with nothing to hand over - an empty buffer
  9443. // popped off a queue, say - must not be taken to mean the body is finished.
  9444. // It used to end the loop with the terminating chunk unwritten while the
  9445. // server still considered the response complete, so the peer waited for an
  9446. // end that never arrived.
  9447. Server svr;
  9448. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9449. auto step = std::make_shared<int>(0);
  9450. res.set_chunked_content_provider("text/plain",
  9451. [step](size_t /*offset*/, DataSink &sink) {
  9452. switch ((*step)++) {
  9453. case 0: sink.write("", 0); break;
  9454. case 1: sink.write("hello", 5); break;
  9455. default: sink.done(); break;
  9456. }
  9457. return true;
  9458. });
  9459. });
  9460. auto port = svr.bind_to_any_port(HOST);
  9461. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9462. auto listen_se = detail::scope_exit([&] {
  9463. svr.stop();
  9464. listen_thread.join();
  9465. ASSERT_FALSE(svr.is_running());
  9466. });
  9467. svr.wait_until_ready();
  9468. Client cli(HOST, port);
  9469. // Without the fix the body is never terminated, so bound the wait rather
  9470. // than letting the test hang on the default read timeout.
  9471. cli.set_read_timeout(5, 0);
  9472. auto res = cli.Get("/stream");
  9473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9474. EXPECT_EQ(StatusCode::OK_200, res->status);
  9475. EXPECT_EQ("hello", res->body);
  9476. }
  9477. TEST(StreamingTest, NoContentLengthStreaming) {
  9478. Server svr;
  9479. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9480. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9481. if (offset < 6) {
  9482. sink.os << (offset < 3 ? "a" : "b");
  9483. } else {
  9484. sink.done();
  9485. }
  9486. return true;
  9487. });
  9488. });
  9489. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9490. auto listen_se = detail::scope_exit([&] {
  9491. svr.stop();
  9492. listen_thread.join();
  9493. ASSERT_FALSE(svr.is_running());
  9494. });
  9495. svr.wait_until_ready();
  9496. Client client(HOST, PORT);
  9497. auto get_thread = std::thread([&client]() {
  9498. std::string s;
  9499. auto res =
  9500. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9501. s += std::string(data, len);
  9502. return true;
  9503. });
  9504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9505. EXPECT_EQ(StatusCode::OK_200, res->status);
  9506. EXPECT_EQ("aaabbb", s);
  9507. });
  9508. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9509. // Give GET time to get a few messages.
  9510. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9511. }
  9512. TEST(MountTest, Unmount) {
  9513. Server svr;
  9514. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9515. auto se = detail::scope_exit([&] {
  9516. svr.stop();
  9517. listen_thread.join();
  9518. ASSERT_FALSE(svr.is_running());
  9519. });
  9520. svr.wait_until_ready();
  9521. Client cli("localhost", PORT);
  9522. svr.set_mount_point("/mount2", "./www2");
  9523. auto res = cli.Get("/");
  9524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9525. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9526. res = cli.Get("/mount2/dir/test.html");
  9527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9528. EXPECT_EQ(StatusCode::OK_200, res->status);
  9529. svr.set_mount_point("/", "./www");
  9530. res = cli.Get("/dir/");
  9531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9532. EXPECT_EQ(StatusCode::OK_200, res->status);
  9533. svr.remove_mount_point("/");
  9534. res = cli.Get("/dir/");
  9535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9536. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9537. svr.remove_mount_point("/mount2");
  9538. res = cli.Get("/mount2/dir/test.html");
  9539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9540. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9541. }
  9542. TEST(MountTest, PathSegmentBoundary) {
  9543. Server svr;
  9544. svr.set_mount_point("/mount2", "./www2");
  9545. svr.set_mount_point("/", "./www");
  9546. auto port = svr.bind_to_any_port(HOST);
  9547. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9548. auto se = detail::scope_exit([&] {
  9549. svr.stop();
  9550. listen_thread.join();
  9551. ASSERT_FALSE(svr.is_running());
  9552. });
  9553. svr.wait_until_ready();
  9554. Client cli(HOST, port);
  9555. auto res = cli.Get("/mount2/dir/test.html");
  9556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9557. EXPECT_EQ(StatusCode::OK_200, res->status);
  9558. // "/mount2" must not match part-way through a path segment.
  9559. res = cli.Get("/mount2dir/test.html");
  9560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9561. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9562. // A mount point ending in '/' keeps matching every path below it.
  9563. res = cli.Get("/dir/test.html");
  9564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9565. EXPECT_EQ(StatusCode::OK_200, res->status);
  9566. }
  9567. TEST(MountTest, Redicect) {
  9568. Server svr;
  9569. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9570. auto se = detail::scope_exit([&] {
  9571. svr.stop();
  9572. listen_thread.join();
  9573. ASSERT_FALSE(svr.is_running());
  9574. });
  9575. svr.set_mount_point("/", "./www");
  9576. svr.wait_until_ready();
  9577. Client cli("localhost", PORT);
  9578. auto res = cli.Get("/dir/");
  9579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9580. EXPECT_EQ(StatusCode::OK_200, res->status);
  9581. res = cli.Get("/dir");
  9582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9583. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9584. res = cli.Get("/file");
  9585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9586. EXPECT_EQ(StatusCode::OK_200, res->status);
  9587. res = cli.Get("/file/");
  9588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9589. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9590. cli.set_follow_location(true);
  9591. res = cli.Get("/dir");
  9592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9593. EXPECT_EQ(StatusCode::OK_200, res->status);
  9594. }
  9595. TEST(MountTest, MultibytesPathName) {
  9596. Server svr;
  9597. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9598. auto se = detail::scope_exit([&] {
  9599. svr.stop();
  9600. listen_thread.join();
  9601. ASSERT_FALSE(svr.is_running());
  9602. });
  9603. svr.set_mount_point("/", "./www");
  9604. svr.wait_until_ready();
  9605. Client cli("localhost", PORT);
  9606. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9608. EXPECT_EQ(StatusCode::OK_200, res->status);
  9609. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9610. }
  9611. #ifdef _WIN32
  9612. // Issue #2435: mmap::open() must succeed even when another handle holds
  9613. // the file open for writing (e.g. an active log file).
  9614. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9615. const char *path = "mmap_concurrent_writer_test.txt";
  9616. const char *content = "hello";
  9617. {
  9618. std::ofstream f(path, std::ios::binary);
  9619. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9620. }
  9621. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9622. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9623. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9624. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9625. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9626. detail::mmap m(path);
  9627. ASSERT_TRUE(m.is_open());
  9628. EXPECT_EQ(strlen(content), m.size());
  9629. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9630. }
  9631. #endif
  9632. #ifndef _WIN32
  9633. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9634. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9635. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9636. TEST(MmapTest, FailedMappingIsNotOpen) {
  9637. const char *path = "./mmap_failed_mapping_test_dir";
  9638. ASSERT_EQ(0, ::mkdir(path, 0755));
  9639. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9640. detail::mmap m(path);
  9641. EXPECT_FALSE(m.is_open());
  9642. EXPECT_EQ(0U, m.size());
  9643. EXPECT_NE(static_cast<const void *>(m.data()),
  9644. static_cast<const void *>(MAP_FAILED));
  9645. }
  9646. #endif
  9647. TEST(KeepAliveTest, ReadTimeout) {
  9648. Server svr;
  9649. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9650. std::this_thread::sleep_for(std::chrono::seconds(2));
  9651. res.set_content("a", "text/plain");
  9652. });
  9653. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9654. res.set_content("b", "text/plain");
  9655. });
  9656. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9657. auto se = detail::scope_exit([&] {
  9658. svr.stop();
  9659. listen_thread.join();
  9660. ASSERT_FALSE(svr.is_running());
  9661. });
  9662. svr.wait_until_ready();
  9663. Client cli("localhost", PORT);
  9664. cli.set_keep_alive(true);
  9665. cli.set_read_timeout(std::chrono::seconds(1));
  9666. auto resa = cli.Get("/a");
  9667. ASSERT_FALSE(resa);
  9668. EXPECT_EQ(Error::Read, resa.error());
  9669. auto resb = cli.Get("/b");
  9670. ASSERT_TRUE(resb);
  9671. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9672. EXPECT_EQ("b", resb->body);
  9673. }
  9674. TEST(KeepAliveTest, MaxCount) {
  9675. size_t keep_alive_max_count = 3;
  9676. Server svr;
  9677. svr.set_keep_alive_max_count(keep_alive_max_count);
  9678. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9679. res.set_content("Hello World!", "text/plain");
  9680. });
  9681. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9682. auto se = detail::scope_exit([&] {
  9683. svr.stop();
  9684. listen_thread.join();
  9685. ASSERT_FALSE(svr.is_running());
  9686. });
  9687. svr.wait_until_ready();
  9688. Client cli(HOST, PORT);
  9689. cli.set_keep_alive(true);
  9690. for (size_t i = 0; i < 5; i++) {
  9691. auto result = cli.Get("/hi");
  9692. ASSERT_TRUE(result);
  9693. EXPECT_EQ(StatusCode::OK_200, result->status);
  9694. if (i == keep_alive_max_count - 1) {
  9695. EXPECT_EQ("close", result->get_header_value("Connection"));
  9696. } else {
  9697. EXPECT_FALSE(result->has_header("Connection"));
  9698. }
  9699. }
  9700. }
  9701. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  9702. // can pull the next one into the server's buffer. The server must serve it
  9703. // without waiting for the socket to become readable again. The keep-alive
  9704. // timeout outlasts the client's read timeout, so a request left waiting for it
  9705. // shows up as a missing response.
  9706. static void serve_pipelining_routes(Server &svr,
  9707. const std::function<void(int)> &client) {
  9708. svr.set_keep_alive_timeout(5);
  9709. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  9710. res.set_content("hi " + req.matches[1].str(), "text/plain");
  9711. });
  9712. svr.Post("/echo", [](const Request &req, Response &res) {
  9713. res.set_content("echo " + req.body, "text/plain");
  9714. });
  9715. auto port = svr.bind_to_any_port(HOST);
  9716. thread t = thread([&] { svr.listen_after_bind(); });
  9717. auto se = detail::scope_exit([&] {
  9718. svr.stop();
  9719. t.join();
  9720. });
  9721. svr.wait_until_ready();
  9722. client(port);
  9723. }
  9724. static std::string
  9725. send_pipelined_requests(const std::vector<std::string> &parts) {
  9726. Server svr;
  9727. std::string res;
  9728. serve_pipelining_routes(svr, [&](int port) {
  9729. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  9730. });
  9731. return res;
  9732. }
  9733. static void expect_in_order(const std::string &res,
  9734. const std::vector<std::string> &bodies) {
  9735. size_t pos = 0;
  9736. for (const auto &body : bodies) {
  9737. pos = res.find(body, pos);
  9738. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  9739. pos += body.size();
  9740. }
  9741. }
  9742. TEST(KeepAliveTest, PipelinedRequests) {
  9743. auto res = send_pipelined_requests(
  9744. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9745. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9746. "Content-Length: 4\r\n\r\nbody"
  9747. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9748. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  9749. }
  9750. // The second request starts in the server's buffer and ends on the socket.
  9751. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  9752. auto res =
  9753. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9754. "GET /hi/2 HTTP/1.1\r\nHo",
  9755. "st: localhost\r\nConnection: close\r\n\r\n"});
  9756. expect_in_order(res, {"hi 1", "hi 2"});
  9757. }
  9758. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  9759. // CRLF after a body does not turn into a 400 for the next request.
  9760. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  9761. auto res = send_pipelined_requests(
  9762. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9763. "Content-Length: 4\r\n\r\nbody\r\n"
  9764. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9765. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  9766. expect_in_order(res, {"echo body", "hi 2"});
  9767. }
  9768. // Where an unparsable request ends is unknown, so what follows it in the buffer
  9769. // must not be served as the next request.
  9770. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  9771. auto res = send_pipelined_requests(
  9772. {"INVALID REQUEST LINE\r\n\r\n"
  9773. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  9774. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9775. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  9776. }
  9777. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9778. // Over TLS, the next request is held by the TLS library as already decrypted
  9779. // data rather than on the socket.
  9780. TEST(KeepAliveTest, SSLPipelinedRequests) {
  9781. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9782. std::string res;
  9783. serve_pipelining_routes(svr, [&](int port) {
  9784. auto error = Error::Success;
  9785. auto sock = detail::create_client_socket(
  9786. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9787. /*connection_timeout_sec=*/5, 0,
  9788. /*read_timeout_sec=*/2, 0,
  9789. /*write_timeout_sec=*/5, 0, std::string(), error);
  9790. ASSERT_NE(INVALID_SOCKET, sock);
  9791. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9792. auto ctx = SSL_CTX_new(TLS_client_method());
  9793. auto ssl = SSL_new(ctx);
  9794. auto ssl_se = detail::scope_exit([&] {
  9795. SSL_free(ssl);
  9796. SSL_CTX_free(ctx);
  9797. });
  9798. SSL_set_fd(ssl, static_cast<int>(sock));
  9799. ASSERT_EQ(1, SSL_connect(ssl));
  9800. // One write, so all three requests arrive in one TLS record
  9801. const std::string req =
  9802. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9803. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9804. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  9805. ASSERT_EQ(static_cast<int>(req.size()),
  9806. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  9807. char buf[512];
  9808. int n;
  9809. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9810. res.append(buf, static_cast<size_t>(n));
  9811. }
  9812. });
  9813. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  9814. }
  9815. #endif
  9816. TEST(KeepAliveTest, Issue1041) {
  9817. Server svr;
  9818. svr.set_keep_alive_timeout(3);
  9819. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9820. res.set_content("Hello World!", "text/plain");
  9821. });
  9822. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9823. auto se = detail::scope_exit([&] {
  9824. svr.stop();
  9825. listen_thread.join();
  9826. ASSERT_FALSE(svr.is_running());
  9827. });
  9828. svr.wait_until_ready();
  9829. Client cli(HOST, PORT);
  9830. cli.set_keep_alive(true);
  9831. auto result = cli.Get("/hi");
  9832. ASSERT_TRUE(result);
  9833. EXPECT_EQ(StatusCode::OK_200, result->status);
  9834. std::this_thread::sleep_for(std::chrono::seconds(5));
  9835. result = cli.Get("/hi");
  9836. ASSERT_TRUE(result);
  9837. EXPECT_EQ(StatusCode::OK_200, result->status);
  9838. }
  9839. TEST(KeepAliveTest, Issue1959) {
  9840. Server svr;
  9841. svr.set_keep_alive_timeout(5);
  9842. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9843. res.set_content("a", "text/plain");
  9844. });
  9845. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9846. auto se = detail::scope_exit([&] {
  9847. if (!svr.is_running()) return;
  9848. svr.stop();
  9849. listen_thread.join();
  9850. ASSERT_FALSE(svr.is_running());
  9851. });
  9852. svr.wait_until_ready();
  9853. Client cli("localhost", PORT);
  9854. cli.set_keep_alive(true);
  9855. using namespace std::chrono;
  9856. auto start = steady_clock::now();
  9857. cli.Get("/a");
  9858. svr.stop();
  9859. listen_thread.join();
  9860. auto end = steady_clock::now();
  9861. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9862. EXPECT_LT(elapsed, 5000);
  9863. }
  9864. #ifdef CPPHTTPLIB_SSL_ENABLED
  9865. TEST(KeepAliveTest, SSLClientReconnection) {
  9866. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9867. ASSERT_TRUE(svr.is_valid());
  9868. svr.set_keep_alive_timeout(1);
  9869. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9870. res.set_content("Hello World!", "text/plain");
  9871. });
  9872. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9873. auto se = detail::scope_exit([&] {
  9874. svr.stop();
  9875. listen_thread.join();
  9876. ASSERT_FALSE(svr.is_running());
  9877. });
  9878. svr.wait_until_ready();
  9879. SSLClient cli(HOST, PORT);
  9880. cli.enable_server_certificate_verification(false);
  9881. cli.set_keep_alive(true);
  9882. auto result = cli.Get("/hi");
  9883. ASSERT_TRUE(result);
  9884. EXPECT_EQ(StatusCode::OK_200, result->status);
  9885. result = cli.Get("/hi");
  9886. ASSERT_TRUE(result);
  9887. EXPECT_EQ(StatusCode::OK_200, result->status);
  9888. std::this_thread::sleep_for(std::chrono::seconds(2));
  9889. // Recoonect
  9890. result = cli.Get("/hi");
  9891. ASSERT_TRUE(result);
  9892. EXPECT_EQ(StatusCode::OK_200, result->status);
  9893. result = cli.Get("/hi");
  9894. ASSERT_TRUE(result);
  9895. EXPECT_EQ(StatusCode::OK_200, result->status);
  9896. }
  9897. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9898. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9899. ASSERT_TRUE(svr.is_valid());
  9900. svr.set_keep_alive_timeout(1);
  9901. std::string content = "reconnect";
  9902. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9903. res.set_content("Hello World!", "text/plain");
  9904. });
  9905. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9906. auto se = detail::scope_exit([&] {
  9907. svr.stop();
  9908. listen_thread.join();
  9909. ASSERT_FALSE(svr.is_running());
  9910. });
  9911. svr.wait_until_ready();
  9912. SSLClient cli(HOST, PORT);
  9913. cli.enable_server_certificate_verification(false);
  9914. cli.set_keep_alive(true);
  9915. auto result = cli.Post(
  9916. "/hi", content.size(),
  9917. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9918. sink.write(content.c_str(), content.size());
  9919. return true;
  9920. },
  9921. "text/plain");
  9922. ASSERT_TRUE(result);
  9923. EXPECT_EQ(200, result->status);
  9924. std::this_thread::sleep_for(std::chrono::seconds(2));
  9925. // Recoonect
  9926. result = cli.Post(
  9927. "/hi", content.size(),
  9928. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9929. sink.write(content.c_str(), content.size());
  9930. return true;
  9931. },
  9932. "text/plain");
  9933. ASSERT_TRUE(result);
  9934. EXPECT_EQ(200, result->status);
  9935. result = cli.Post(
  9936. "/hi", content.size(),
  9937. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9938. sink.write(content.c_str(), content.size());
  9939. return true;
  9940. },
  9941. "text/plain");
  9942. ASSERT_TRUE(result);
  9943. EXPECT_EQ(200, result->status);
  9944. }
  9945. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  9946. using namespace httplib::tls;
  9947. {
  9948. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9949. ASSERT_TRUE(svr.is_valid());
  9950. svr.Get("/sni", [&](const Request &req, Response &res) {
  9951. std::string expected = req.sni();
  9952. EXPECT_EQ(expected, req.get_param_value("expected"));
  9953. res.set_content("ok", "text/plain");
  9954. });
  9955. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9956. auto se = detail::scope_exit([&] {
  9957. svr.stop();
  9958. listen_thread.join();
  9959. ASSERT_FALSE(svr.is_running());
  9960. });
  9961. svr.wait_until_ready();
  9962. {
  9963. SSLClient cli("localhost", PORT);
  9964. cli.enable_server_certificate_verification(false);
  9965. auto res = cli.Get("/sni?expected=localhost");
  9966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9967. }
  9968. {
  9969. SSLClient cli("::1", PORT);
  9970. cli.enable_server_certificate_verification(false);
  9971. auto res = cli.Get("/sni?expected=");
  9972. // NOTE: This may fail if the server is listening on IPv4 only
  9973. // (e.g., when localhost resolves to 127.0.0.1 only)
  9974. if (res) {
  9975. EXPECT_EQ(StatusCode::OK_200, res->status);
  9976. } else {
  9977. EXPECT_EQ(Error::Connection, res.error());
  9978. }
  9979. }
  9980. }
  9981. }
  9982. #endif
  9983. TEST(ClientProblemDetectionTest, ContentProvider) {
  9984. Server svr;
  9985. size_t content_length = 1024 * 1024;
  9986. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9987. res.set_content_provider(
  9988. content_length, "text/plain",
  9989. [&](size_t offset, size_t length, DataSink &sink) {
  9990. auto out_len = std::min(length, static_cast<size_t>(1024));
  9991. std::string out(out_len, '@');
  9992. sink.write(out.data(), out_len);
  9993. return offset < 4096;
  9994. },
  9995. [](bool success) { ASSERT_FALSE(success); });
  9996. });
  9997. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  9998. res.set_content_provider(
  9999. 0, "text/plain",
  10000. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10001. EXPECT_TRUE(false);
  10002. return true;
  10003. },
  10004. [](bool success) { ASSERT_FALSE(success); });
  10005. });
  10006. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10007. auto se = detail::scope_exit([&] {
  10008. svr.stop();
  10009. listen_thread.join();
  10010. ASSERT_FALSE(svr.is_running());
  10011. });
  10012. svr.wait_until_ready();
  10013. Client cli("localhost", PORT);
  10014. {
  10015. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10016. size_t /*data_length*/) { return false; });
  10017. ASSERT_FALSE(res);
  10018. }
  10019. {
  10020. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10021. size_t /*data_length*/) { return false; });
  10022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10023. }
  10024. }
  10025. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10026. // A provider that reports success without writing anything and without
  10027. // calling done() used to be handed the same offset and length again on every
  10028. // pass, so it spun for as long as the peer stayed connected.
  10029. Server svr;
  10030. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10031. res.set_content("ok", "text/plain");
  10032. });
  10033. auto port = svr.bind_to_any_port(HOST);
  10034. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10035. auto se = detail::scope_exit([&] {
  10036. svr.stop();
  10037. listen_thread.join();
  10038. ASSERT_FALSE(svr.is_running());
  10039. });
  10040. svr.wait_until_ready();
  10041. std::atomic<int> call_count{0};
  10042. Client cli(HOST, port);
  10043. auto res = cli.Post(
  10044. "/", 1024,
  10045. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10046. // Give up after enough passes to show the spin, so that losing the
  10047. // check below fails this test instead of hanging it.
  10048. return ++call_count < 100;
  10049. },
  10050. "text/plain");
  10051. ASSERT_FALSE(res);
  10052. EXPECT_EQ(Error::Write, res.error());
  10053. EXPECT_EQ(1, call_count.load());
  10054. }
  10055. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10056. // A writer only has to assign `write`. The other three used to be left as
  10057. // empty std::functions, so a provider calling one threw
  10058. // std::bad_function_call out of the thread running it and took the whole
  10059. // process down.
  10060. DataSink sink;
  10061. std::string written;
  10062. sink.write = [&](const char *data, size_t data_len) {
  10063. written.append(data, data_len);
  10064. return true;
  10065. };
  10066. EXPECT_TRUE(sink.is_writable());
  10067. sink.done();
  10068. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10069. EXPECT_TRUE(written.empty());
  10070. }
  10071. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10072. // A sink that cannot carry trailers still has to finish.
  10073. DataSink sink;
  10074. auto done_count = 0;
  10075. sink.done = [&]() { done_count++; };
  10076. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10077. EXPECT_EQ(1, done_count);
  10078. }
  10079. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10080. Server svr;
  10081. const std::string body(4096, 'x');
  10082. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10083. res.set_content_provider(body.size(), "text/plain",
  10084. [&](size_t offset, size_t length, DataSink &sink) {
  10085. sink.write(body.data() + offset, length);
  10086. sink.done();
  10087. return true;
  10088. });
  10089. });
  10090. auto port = svr.bind_to_any_port(HOST);
  10091. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10092. auto se = detail::scope_exit([&] {
  10093. svr.stop();
  10094. listen_thread.join();
  10095. ASSERT_FALSE(svr.is_running());
  10096. });
  10097. svr.wait_until_ready();
  10098. Client cli(HOST, port);
  10099. auto res = cli.Get("/");
  10100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10101. EXPECT_EQ(StatusCode::OK_200, res->status);
  10102. EXPECT_EQ(body, res->body);
  10103. }
  10104. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10105. Server svr;
  10106. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10107. res.set_content_provider(
  10108. 1024, "text/plain",
  10109. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10110. sink.write("hello", 5);
  10111. sink.done(); // short of the 1024 bytes the response promised
  10112. return true;
  10113. });
  10114. });
  10115. auto port = svr.bind_to_any_port(HOST);
  10116. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10117. auto se = detail::scope_exit([&] {
  10118. svr.stop();
  10119. listen_thread.join();
  10120. ASSERT_FALSE(svr.is_running());
  10121. });
  10122. svr.wait_until_ready();
  10123. Client cli(HOST, port);
  10124. cli.set_read_timeout(5, 0);
  10125. // The response is short of its Content-Length, so the client cannot read a
  10126. // complete body. What matters is that this returns at all: a no-op done()
  10127. // would leave the writer looping over a provider that never makes progress.
  10128. auto res = cli.Get("/");
  10129. EXPECT_FALSE(res);
  10130. }
  10131. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10132. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10133. // The compressed path builds the whole body before connecting, so this
  10134. // fails client-side and never reaches a server.
  10135. Client cli(HOST, PORT);
  10136. cli.set_compress(true);
  10137. auto res = cli.Post(
  10138. "/", 1024,
  10139. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10140. sink.write("hello", 5);
  10141. sink.done(); // short of the 1024 bytes the request announced
  10142. return true;
  10143. },
  10144. "text/plain");
  10145. ASSERT_FALSE(res);
  10146. EXPECT_EQ(Error::Write, res.error());
  10147. }
  10148. #endif
  10149. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10150. Server svr;
  10151. svr.set_error_handler([](Request const &, Response &res) -> void {
  10152. res.set_chunked_content_provider(
  10153. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10154. sink.os << "hello";
  10155. sink.os << "world";
  10156. sink.done();
  10157. return true;
  10158. });
  10159. });
  10160. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10161. auto se = detail::scope_exit([&] {
  10162. svr.stop();
  10163. listen_thread.join();
  10164. ASSERT_FALSE(svr.is_running());
  10165. });
  10166. svr.wait_until_ready();
  10167. Client cli("localhost", PORT);
  10168. auto res = cli.Get("/");
  10169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10170. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10171. EXPECT_EQ("helloworld", res->body);
  10172. }
  10173. TEST(LongPollingTest, ClientCloseDetection) {
  10174. Server svr;
  10175. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10176. res.set_chunked_content_provider(
  10177. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10178. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10179. sink.os << "hello";
  10180. auto count = 10;
  10181. while (count > 0 && sink.is_writable()) {
  10182. this_thread::sleep_for(chrono::milliseconds(10));
  10183. count--;
  10184. }
  10185. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10186. return true;
  10187. });
  10188. });
  10189. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10190. auto se = detail::scope_exit([&] {
  10191. svr.stop();
  10192. listen_thread.join();
  10193. ASSERT_FALSE(svr.is_running());
  10194. });
  10195. svr.wait_until_ready();
  10196. Client cli("localhost", PORT);
  10197. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10198. EXPECT_EQ("hello", string(data, data_length));
  10199. return false; // close the socket immediately.
  10200. });
  10201. ASSERT_FALSE(res);
  10202. }
  10203. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10204. Server svr;
  10205. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10206. res.set_chunked_content_provider(
  10207. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10208. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10209. sink.os << "hello";
  10210. EXPECT_TRUE(sink.os.good());
  10211. // Wait for the client to close the connection
  10212. auto count = 10;
  10213. while (count > 0 && sink.is_writable()) {
  10214. this_thread::sleep_for(chrono::milliseconds(10));
  10215. count--;
  10216. }
  10217. // After client disconnect, write repeatedly until the socket
  10218. // write actually fails (small writes may be absorbed by the
  10219. // kernel buffer)
  10220. std::string chunk(1024, 'x');
  10221. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10222. sink.os << chunk;
  10223. }
  10224. EXPECT_TRUE(sink.os.fail());
  10225. return true;
  10226. });
  10227. });
  10228. auto port = svr.bind_to_any_port("localhost");
  10229. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10230. auto se = detail::scope_exit([&] {
  10231. svr.stop();
  10232. listen_thread.join();
  10233. ASSERT_FALSE(svr.is_running());
  10234. });
  10235. svr.wait_until_ready();
  10236. Client cli("localhost", port);
  10237. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10238. EXPECT_EQ("hello", string(data, data_length));
  10239. return false; // close the socket immediately.
  10240. });
  10241. ASSERT_FALSE(res);
  10242. }
  10243. TEST(GetWithParametersTest, GetWithParameters) {
  10244. Server svr;
  10245. svr.Get("/", [&](const Request &req, Response &) {
  10246. EXPECT_EQ("world", req.get_param_value("hello"));
  10247. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10248. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10249. });
  10250. svr.Get("/params", [&](const Request &req, Response &) {
  10251. EXPECT_EQ("world", req.get_param_value("hello"));
  10252. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10253. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10254. });
  10255. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10256. EXPECT_EQ("resource-id", req.matches[1]);
  10257. EXPECT_EQ("foo", req.get_param_value("param1"));
  10258. EXPECT_EQ("bar", req.get_param_value("param2"));
  10259. });
  10260. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10261. EXPECT_EQ("user-id", req.path_params.at("id"));
  10262. EXPECT_EQ("foo", req.get_param_value("param1"));
  10263. EXPECT_EQ("bar", req.get_param_value("param2"));
  10264. });
  10265. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10266. auto se = detail::scope_exit([&] {
  10267. svr.stop();
  10268. listen_thread.join();
  10269. ASSERT_FALSE(svr.is_running());
  10270. });
  10271. svr.wait_until_ready();
  10272. {
  10273. Client cli(HOST, PORT);
  10274. Params params;
  10275. params.emplace("hello", "world");
  10276. params.emplace("hello2", "world2");
  10277. params.emplace("hello3", "world3");
  10278. auto res = cli.Get("/", params, Headers{});
  10279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10280. EXPECT_EQ(StatusCode::OK_200, res->status);
  10281. }
  10282. {
  10283. Client cli(HOST, PORT);
  10284. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10286. EXPECT_EQ(StatusCode::OK_200, res->status);
  10287. }
  10288. {
  10289. Client cli(HOST, PORT);
  10290. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10292. EXPECT_EQ(StatusCode::OK_200, res->status);
  10293. }
  10294. {
  10295. Client cli(HOST, PORT);
  10296. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10298. EXPECT_EQ(StatusCode::OK_200, res->status);
  10299. }
  10300. }
  10301. TEST(GetWithParametersTest, GetWithParameters2) {
  10302. Server svr;
  10303. svr.Get("/", [&](const Request &req, Response &res) {
  10304. auto text = req.get_param_value("hello");
  10305. res.set_content(text, "text/plain");
  10306. });
  10307. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10308. auto se = detail::scope_exit([&] {
  10309. svr.stop();
  10310. listen_thread.join();
  10311. ASSERT_FALSE(svr.is_running());
  10312. });
  10313. svr.wait_until_ready();
  10314. Client cli("localhost", PORT);
  10315. Params params;
  10316. params.emplace("hello", "world");
  10317. std::string body;
  10318. auto res = cli.Get("/", params, Headers{},
  10319. [&](const char *data, size_t data_length) {
  10320. body.append(data, data_length);
  10321. return true;
  10322. });
  10323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10324. EXPECT_EQ(StatusCode::OK_200, res->status);
  10325. EXPECT_EQ("world", body);
  10326. }
  10327. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10328. Server svr;
  10329. svr.Get("/search", [&](const Request &req, Response &res) {
  10330. auto q = req.get_param_value("q");
  10331. res.set_content(q, "text/plain");
  10332. });
  10333. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10334. auto se = detail::scope_exit([&] {
  10335. svr.stop();
  10336. listen_thread.join();
  10337. ASSERT_FALSE(svr.is_running());
  10338. });
  10339. svr.wait_until_ready();
  10340. Client cli("localhost", PORT);
  10341. // Verify that Get(path, params) works without requiring Headers argument
  10342. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10344. EXPECT_EQ(StatusCode::OK_200, res->status);
  10345. EXPECT_EQ("cpp-httplib", res->body);
  10346. }
  10347. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10348. auto host = "httpbingo.org";
  10349. auto path = std::string{"/range/32"};
  10350. #ifdef CPPHTTPLIB_SSL_ENABLED
  10351. SSLClient cli(host);
  10352. #else
  10353. Client cli(host);
  10354. #endif
  10355. cli.set_default_headers({make_range_header({{1, 10}})});
  10356. cli.set_connection_timeout(5);
  10357. {
  10358. auto res = cli.Get(path);
  10359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10360. EXPECT_EQ("bcdefghijk", res->body);
  10361. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10362. }
  10363. {
  10364. auto res = cli.Get(path);
  10365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10366. EXPECT_EQ("bcdefghijk", res->body);
  10367. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10368. }
  10369. }
  10370. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10371. Server svr;
  10372. svr.set_default_headers({{"Hello", "World"}});
  10373. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10374. res.set_content("ok", "text/plain");
  10375. });
  10376. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10377. auto se = detail::scope_exit([&] {
  10378. svr.stop();
  10379. listen_thread.join();
  10380. ASSERT_FALSE(svr.is_running());
  10381. });
  10382. svr.wait_until_ready();
  10383. Client cli("localhost", PORT);
  10384. auto res = cli.Get("/");
  10385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10386. EXPECT_EQ(StatusCode::OK_200, res->status);
  10387. EXPECT_EQ("ok", res->body);
  10388. EXPECT_EQ("World", res->get_header_value("Hello"));
  10389. }
  10390. #ifdef CPPHTTPLIB_SSL_ENABLED
  10391. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10392. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10393. ASSERT_TRUE(svr.is_valid());
  10394. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10395. std::this_thread::sleep_for(std::chrono::seconds(2));
  10396. res.set_content("a", "text/plain");
  10397. });
  10398. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10399. res.set_content("b", "text/plain");
  10400. });
  10401. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10402. auto se = detail::scope_exit([&] {
  10403. svr.stop();
  10404. listen_thread.join();
  10405. ASSERT_FALSE(svr.is_running());
  10406. });
  10407. svr.wait_until_ready();
  10408. SSLClient cli("localhost", PORT);
  10409. cli.enable_server_certificate_verification(false);
  10410. cli.set_keep_alive(true);
  10411. cli.set_read_timeout(std::chrono::seconds(1));
  10412. auto resa = cli.Get("/a");
  10413. ASSERT_TRUE(!resa);
  10414. EXPECT_EQ(Error::Read, resa.error());
  10415. auto resb = cli.Get("/b");
  10416. ASSERT_TRUE(resb);
  10417. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10418. EXPECT_EQ("b", resb->body);
  10419. }
  10420. // Closing an idle keep-alive connection sends close_notify and returns. The
  10421. // server must not wait for the client's close_notify: an idle client never
  10422. // sends one, so the worker would be held until the read timeout expires, and
  10423. // stop() would wait for it.
  10424. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10425. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10426. ASSERT_TRUE(svr.is_valid());
  10427. svr.set_keep_alive_timeout(1);
  10428. svr.set_read_timeout(10, 0);
  10429. svr.Get("/", [](const Request &, Response &res) {
  10430. res.set_content("ok", "text/plain");
  10431. });
  10432. auto port = svr.bind_to_any_port(HOST);
  10433. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10434. auto se = detail::scope_exit([&] {
  10435. if (listen_thread.joinable()) {
  10436. svr.stop();
  10437. listen_thread.join();
  10438. }
  10439. });
  10440. svr.wait_until_ready();
  10441. SSLClient cli(HOST, port);
  10442. cli.enable_server_certificate_verification(false);
  10443. cli.set_keep_alive(true);
  10444. auto res = cli.Get("/");
  10445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10446. EXPECT_EQ(StatusCode::OK_200, res->status);
  10447. // Stay idle past the keep-alive timeout so the server closes the connection.
  10448. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10449. auto start = std::chrono::steady_clock::now();
  10450. svr.stop();
  10451. listen_thread.join();
  10452. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10453. std::chrono::steady_clock::now() - start)
  10454. .count();
  10455. EXPECT_LT(elapsed, 3000);
  10456. }
  10457. #endif
  10458. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10459. protected:
  10460. ServerTestWithAI_PASSIVE()
  10461. : cli_(HOST, PORT)
  10462. #ifdef CPPHTTPLIB_SSL_ENABLED
  10463. ,
  10464. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10465. #endif
  10466. {
  10467. #ifdef CPPHTTPLIB_SSL_ENABLED
  10468. cli_.enable_server_certificate_verification(false);
  10469. #endif
  10470. }
  10471. virtual void SetUp() {
  10472. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10473. res.set_content("Hello World!", "text/plain");
  10474. });
  10475. t_ = thread(
  10476. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10477. svr_.wait_until_ready();
  10478. }
  10479. virtual void TearDown() {
  10480. svr_.stop();
  10481. t_.join();
  10482. }
  10483. #ifdef CPPHTTPLIB_SSL_ENABLED
  10484. SSLClient cli_;
  10485. SSLServer svr_;
  10486. #else
  10487. Client cli_;
  10488. Server svr_;
  10489. #endif
  10490. thread t_;
  10491. };
  10492. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10493. auto res = cli_.Get("/hi");
  10494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10495. EXPECT_EQ(StatusCode::OK_200, res->status);
  10496. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10497. EXPECT_EQ("Hello World!", res->body);
  10498. }
  10499. class ServerUpDownTest : public ::testing::Test {
  10500. protected:
  10501. ServerUpDownTest() : cli_(HOST, PORT) {}
  10502. virtual void SetUp() {
  10503. t_ = thread([&]() {
  10504. svr_.bind_to_any_port(HOST);
  10505. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10506. ASSERT_TRUE(svr_.listen_after_bind());
  10507. });
  10508. svr_.wait_until_ready();
  10509. }
  10510. virtual void TearDown() {
  10511. svr_.stop();
  10512. t_.join();
  10513. }
  10514. Client cli_;
  10515. Server svr_;
  10516. thread t_;
  10517. };
  10518. TEST_F(ServerUpDownTest, QuickStartStop) {
  10519. // Should not crash, especially when run with
  10520. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10521. }
  10522. class PayloadMaxLengthTest : public ::testing::Test {
  10523. protected:
  10524. PayloadMaxLengthTest()
  10525. : cli_(HOST, PORT)
  10526. #ifdef CPPHTTPLIB_SSL_ENABLED
  10527. ,
  10528. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10529. #endif
  10530. {
  10531. #ifdef CPPHTTPLIB_SSL_ENABLED
  10532. cli_.enable_server_certificate_verification(false);
  10533. #endif
  10534. }
  10535. virtual void SetUp() {
  10536. svr_.set_payload_max_length(8);
  10537. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10538. res.set_content("test", "text/plain");
  10539. });
  10540. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10541. svr_.wait_until_ready();
  10542. }
  10543. virtual void TearDown() {
  10544. svr_.stop();
  10545. t_.join();
  10546. }
  10547. #ifdef CPPHTTPLIB_SSL_ENABLED
  10548. SSLClient cli_;
  10549. SSLServer svr_;
  10550. #else
  10551. Client cli_;
  10552. Server svr_;
  10553. #endif
  10554. thread t_;
  10555. };
  10556. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10557. auto res = cli_.Post("/test", "123456789", "text/plain");
  10558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10559. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10560. res = cli_.Post("/test", "12345678", "text/plain");
  10561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10562. EXPECT_EQ(StatusCode::OK_200, res->status);
  10563. }
  10564. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10565. // Test chunked encoding with payload exceeding the 8-byte limit
  10566. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10567. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10569. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10570. }
  10571. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10572. // Test chunked encoding with payload within the 8-byte limit
  10573. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10574. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10576. EXPECT_EQ(StatusCode::OK_200, res->status);
  10577. }
  10578. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10579. // Test using send_request to send chunked data exceeding payload limit
  10580. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10581. "Host: " +
  10582. std::string(HOST) + ":" + std::to_string(PORT) +
  10583. "\r\n"
  10584. "Transfer-Encoding: chunked\r\n"
  10585. "Connection: close\r\n"
  10586. "\r\n"
  10587. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10588. "0123456789\r\n"
  10589. "0\r\n" // End chunk
  10590. "\r\n";
  10591. std::string response;
  10592. bool result = send_request(1, chunked_request, &response);
  10593. if (!result) {
  10594. // If send_request fails, it might be because the server closed the
  10595. // connection due to payload limit enforcement, which is acceptable
  10596. SUCCEED()
  10597. << "Server rejected oversized chunked request (connection closed)";
  10598. } else {
  10599. // If we got a response, check if it's an error response or connection was
  10600. // closed early Short response length indicates connection was closed due to
  10601. // payload limit
  10602. if (response.length() <= 10) {
  10603. SUCCEED() << "Server closed connection for oversized chunked request";
  10604. } else {
  10605. // Check for error status codes
  10606. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10607. response.find("Payload Too Large") != std::string::npos ||
  10608. response.find("400") != std::string::npos);
  10609. }
  10610. }
  10611. }
  10612. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10613. // Test request without Content-Length header exceeding payload limit
  10614. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10615. "Host: " +
  10616. std::string(HOST) + ":" +
  10617. std::to_string(PORT) +
  10618. "\r\n"
  10619. "Connection: close\r\n"
  10620. "\r\n";
  10621. // Add payload exceeding the 8-byte limit
  10622. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10623. request_without_content_length += large_payload;
  10624. std::string response;
  10625. bool result = send_request(1, request_without_content_length, &response);
  10626. if (!result) {
  10627. // If send_request fails, server likely closed connection due to payload
  10628. // limit
  10629. SUCCEED() << "Server rejected oversized request without Content-Length "
  10630. "(connection closed)";
  10631. } else {
  10632. // Check if server responded with error or closed connection early
  10633. if (response.length() <= 10) {
  10634. SUCCEED() << "Server closed connection for oversized request without "
  10635. "Content-Length";
  10636. } else {
  10637. // Check for error status codes
  10638. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10639. response.find("Payload Too Large") != std::string::npos ||
  10640. response.find("400") != std::string::npos);
  10641. }
  10642. }
  10643. }
  10644. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  10645. // Test request without Content-Length header within payload limit
  10646. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10647. "Host: " +
  10648. std::string(HOST) + ":" +
  10649. std::to_string(PORT) +
  10650. "\r\n"
  10651. "Connection: close\r\n"
  10652. "\r\n";
  10653. // Add payload within the 8-byte limit
  10654. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  10655. request_without_content_length += small_payload;
  10656. std::string response;
  10657. bool result = send_request(1, request_without_content_length, &response);
  10658. // For requests without Content-Length, the server may have different behavior
  10659. // The key is that it should not reject due to payload limit for small
  10660. // payloads
  10661. if (result) {
  10662. // Check for any HTTP response (success or error, but not connection closed)
  10663. if (response.length() > 10) {
  10664. SUCCEED()
  10665. << "Server processed request without Content-Length within limit";
  10666. } else {
  10667. // Short response might indicate connection closed, which is acceptable
  10668. SUCCEED() << "Server closed connection for request without "
  10669. "Content-Length (acceptable behavior)";
  10670. }
  10671. } else {
  10672. // Connection failure might be due to protocol requirements
  10673. SUCCEED() << "Connection issue with request without Content-Length "
  10674. "(environment-specific)";
  10675. }
  10676. }
  10677. class LargePayloadMaxLengthTest : public ::testing::Test {
  10678. protected:
  10679. LargePayloadMaxLengthTest()
  10680. : cli_(HOST, PORT)
  10681. #ifdef CPPHTTPLIB_SSL_ENABLED
  10682. ,
  10683. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10684. #endif
  10685. {
  10686. #ifdef CPPHTTPLIB_SSL_ENABLED
  10687. cli_.enable_server_certificate_verification(false);
  10688. #endif
  10689. }
  10690. virtual void SetUp() {
  10691. // Set 10MB payload limit
  10692. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  10693. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  10694. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10695. res.set_content("Large payload test", "text/plain");
  10696. });
  10697. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10698. svr_.wait_until_ready();
  10699. }
  10700. virtual void TearDown() {
  10701. svr_.stop();
  10702. t_.join();
  10703. }
  10704. #ifdef CPPHTTPLIB_SSL_ENABLED
  10705. SSLClient cli_;
  10706. SSLServer svr_;
  10707. #else
  10708. Client cli_;
  10709. Server svr_;
  10710. #endif
  10711. thread t_;
  10712. };
  10713. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  10714. // Test chunked encoding with payload within 10MB limit
  10715. std::string medium_payload(5 * 1024 * 1024,
  10716. 'A'); // 5MB payload, within 10MB limit
  10717. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  10718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10719. EXPECT_EQ(StatusCode::OK_200, res->status);
  10720. }
  10721. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  10722. // Test chunked encoding with payload exceeding 10MB limit
  10723. std::string large_payload(12 * 1024 * 1024,
  10724. 'B'); // 12MB payload, exceeds 10MB limit
  10725. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  10726. // Server may either return 413 or close the connection
  10727. if (res) {
  10728. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10729. } else {
  10730. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  10731. }
  10732. }
  10733. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  10734. // Test request without Content-Length header within 10MB limit
  10735. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10736. "Host: " +
  10737. std::string(HOST) + ":" +
  10738. std::to_string(PORT) +
  10739. "\r\n"
  10740. "Connection: close\r\n"
  10741. "\r\n";
  10742. // Add 1MB payload (within 10MB limit)
  10743. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  10744. request_without_content_length += medium_payload;
  10745. std::string response;
  10746. bool result = send_request(5, request_without_content_length, &response);
  10747. if (result) {
  10748. // Should get a proper HTTP response for payloads within limit
  10749. if (response.length() > 10) {
  10750. SUCCEED() << "Server processed 1MB request without Content-Length within "
  10751. "10MB limit";
  10752. } else {
  10753. SUCCEED() << "Server closed connection (acceptable behavior for no "
  10754. "Content-Length)";
  10755. }
  10756. } else {
  10757. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  10758. }
  10759. }
  10760. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  10761. // Test request without Content-Length header exceeding 10MB limit
  10762. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10763. "Host: " +
  10764. std::string(HOST) + ":" +
  10765. std::to_string(PORT) +
  10766. "\r\n"
  10767. "Connection: close\r\n"
  10768. "\r\n";
  10769. // Add 12MB payload (exceeds 10MB limit)
  10770. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  10771. request_without_content_length += large_payload;
  10772. std::string response;
  10773. bool result = send_request(10, request_without_content_length, &response);
  10774. if (!result) {
  10775. // Server should close connection due to payload limit
  10776. SUCCEED() << "Server rejected 12MB request without Content-Length "
  10777. "(connection closed)";
  10778. } else {
  10779. // Check for error response
  10780. if (response.length() <= 10) {
  10781. SUCCEED()
  10782. << "Server closed connection for 12MB request exceeding 10MB limit";
  10783. } else {
  10784. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10785. response.find("Payload Too Large") != std::string::npos ||
  10786. response.find("400") != std::string::npos);
  10787. }
  10788. }
  10789. }
  10790. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10791. // `payload_max_length` is not enforced on decompressed body in ContentReader
  10792. // path.
  10793. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  10794. Server svr;
  10795. const size_t LIMIT = 64 * 1024; // 64KB
  10796. svr.set_payload_max_length(LIMIT);
  10797. size_t total = 0;
  10798. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10799. const ContentReader &content_reader) {
  10800. content_reader([&](const char * /*data*/, size_t len) {
  10801. total += len;
  10802. return true;
  10803. });
  10804. res.status = 200;
  10805. res.set_content("stream_ok", "text/plain");
  10806. });
  10807. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10808. auto se = detail::scope_exit([&] {
  10809. svr.stop();
  10810. thread.join();
  10811. ASSERT_FALSE(svr.is_running());
  10812. });
  10813. svr.wait_until_ready();
  10814. // Prepare 256KB raw data and gzip-compress it
  10815. std::string raw(256 * 1024, 'A');
  10816. std::string gz;
  10817. {
  10818. z_stream zs{};
  10819. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  10820. Z_DEFAULT_STRATEGY);
  10821. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  10822. zs.avail_in = static_cast<uInt>(raw.size());
  10823. char outbuf[4096];
  10824. int ret;
  10825. do {
  10826. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  10827. zs.avail_out = sizeof(outbuf);
  10828. ret = deflate(&zs, Z_FINISH);
  10829. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  10830. } while (ret != Z_STREAM_END);
  10831. deflateEnd(&zs);
  10832. }
  10833. Client cli(HOST, PORT);
  10834. cli.set_connection_timeout(std::chrono::seconds(5));
  10835. Headers headers = {{"Content-Encoding", "gzip"}};
  10836. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  10837. "application/octet-stream");
  10838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10839. // Server must reject oversized decompressed payloads with 413.
  10840. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10841. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10842. EXPECT_LE(total, LIMIT);
  10843. }
  10844. #ifndef CPPHTTPLIB_SSL_ENABLED
  10845. // For a request with neither Content-Length nor Transfer-Encoding, the
  10846. // non-SSL raw-socket fallback in read_content_core() used to hand the
  10847. // compressed wire bytes straight to the ContentReader without ever routing
  10848. // them through the decompressor, so payload_max_length_ only bounded the
  10849. // compressed size on the wire, not the decompressed size.
  10850. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  10851. Server svr;
  10852. const size_t LIMIT = 64 * 1024; // 64KB
  10853. svr.set_payload_max_length(LIMIT);
  10854. size_t total = 0;
  10855. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10856. const ContentReader &content_reader) {
  10857. content_reader([&](const char * /*data*/, size_t len) {
  10858. total += len;
  10859. return true;
  10860. });
  10861. res.status = 200;
  10862. res.set_content("stream_ok", "text/plain");
  10863. });
  10864. auto port = svr.bind_to_any_port(HOST);
  10865. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10866. auto se = detail::scope_exit([&] {
  10867. svr.stop();
  10868. thread.join();
  10869. ASSERT_FALSE(svr.is_running());
  10870. });
  10871. svr.wait_until_ready();
  10872. // Prepare 256KB raw data and gzip-compress it, same payload as the
  10873. // StreamingGzipDecompression test above.
  10874. std::string raw(256 * 1024, 'A');
  10875. std::string gz;
  10876. {
  10877. httplib::detail::gzip_compressor compressor;
  10878. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  10879. [&](const char *chunk, size_t len) {
  10880. gz.append(chunk, len);
  10881. return true;
  10882. });
  10883. ASSERT_TRUE(result);
  10884. }
  10885. // Send the gzip body over raw TCP with neither Content-Length nor
  10886. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  10887. // kicks in.
  10888. std::string req = "POST /stream HTTP/1.1\r\n"
  10889. "Host: " +
  10890. std::string(HOST) + ":" + std::to_string(port) +
  10891. "\r\n"
  10892. "Content-Encoding: gzip\r\n"
  10893. "Connection: close\r\n"
  10894. "\r\n" +
  10895. gz;
  10896. std::string response;
  10897. ASSERT_TRUE(send_request(5, req, &response, port));
  10898. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10899. EXPECT_LE(total, LIMIT);
  10900. }
  10901. #endif
  10902. #endif
  10903. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  10904. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  10905. // the payload must be passed through untouched instead of being rejected.
  10906. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  10907. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10908. Server svr;
  10909. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  10910. res.set_content(body, "image/jpeg");
  10911. res.set_header("Content-Encoding", "UTF-8");
  10912. });
  10913. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  10914. res.set_content(body, "image/jpeg");
  10915. res.set_header("Content-Encoding", "identity");
  10916. });
  10917. svr.Post("/echo", [](const Request &req, Response &res) {
  10918. res.set_content(req.body, "image/jpeg");
  10919. });
  10920. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10921. auto se = detail::scope_exit([&] {
  10922. svr.stop();
  10923. t.join();
  10924. ASSERT_FALSE(svr.is_running());
  10925. });
  10926. svr.wait_until_ready();
  10927. Client cli(HOST, PORT);
  10928. {
  10929. auto res = cli.Get("/image");
  10930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10931. EXPECT_EQ(StatusCode::OK_200, res->status);
  10932. EXPECT_EQ(body, res->body);
  10933. }
  10934. {
  10935. auto res = cli.Get("/identity");
  10936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10937. EXPECT_EQ(StatusCode::OK_200, res->status);
  10938. EXPECT_EQ(body, res->body);
  10939. }
  10940. {
  10941. // The same applies to a request body reaching the server.
  10942. Headers headers = {{"Content-Encoding", "UTF-8"}};
  10943. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  10944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10945. EXPECT_EQ(StatusCode::OK_200, res->status);
  10946. EXPECT_EQ(body, res->body);
  10947. }
  10948. }
  10949. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  10950. // gzip-encoded response even when the build has no zlib support.
  10951. static const char GZIPPED_HELLO_WORLD[] = {
  10952. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  10953. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  10954. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  10955. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  10956. // A content coding is a whole token, not something the field value merely
  10957. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  10958. // as "fibre" look like Brotli, and turned a multi-coding value like
  10959. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  10960. // it was never meant to see.
  10961. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  10962. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10963. Server svr;
  10964. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  10965. res.set_content(body, "image/jpeg");
  10966. res.set_header("Content-Encoding", "fibre");
  10967. });
  10968. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  10969. res.set_content(body, "image/jpeg");
  10970. res.set_header("Content-Encoding", "gzip, br");
  10971. });
  10972. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  10973. res.set_content(body, "image/jpeg");
  10974. res.set_header("Content-Encoding", "x-zstd-ish");
  10975. });
  10976. auto port = svr.bind_to_any_port(HOST);
  10977. thread t = thread([&]() { svr.listen_after_bind(); });
  10978. auto se = detail::scope_exit([&] {
  10979. svr.stop();
  10980. t.join();
  10981. ASSERT_FALSE(svr.is_running());
  10982. });
  10983. svr.wait_until_ready();
  10984. Client cli(HOST, port);
  10985. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  10986. auto res = cli.Get(path);
  10987. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10988. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10989. // Not a coding we recognize, so the payload comes back untouched
  10990. EXPECT_EQ(body, res->body) << path;
  10991. }
  10992. }
  10993. // A content coding cpp-httplib recognizes but was not built with must be
  10994. // reported as such. Handing the still-compressed payload back to the caller
  10995. // would silently corrupt it.
  10996. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  10997. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10998. Server svr;
  10999. // "image/jpeg" keeps the server from applying a content coding of its own,
  11000. // so the hand-crafted Content-Encoding below survives.
  11001. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11002. res.set_content(gzipped, "image/jpeg");
  11003. res.set_header("Content-Encoding", "gzip");
  11004. });
  11005. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11006. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11007. res.set_content(gzipped, "image/jpeg");
  11008. res.set_header("Content-Encoding", "GZIP");
  11009. });
  11010. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11011. auto se = detail::scope_exit([&] {
  11012. svr.stop();
  11013. t.join();
  11014. ASSERT_FALSE(svr.is_running());
  11015. });
  11016. svr.wait_until_ready();
  11017. Client cli(HOST, PORT);
  11018. {
  11019. auto res = cli.Get("/gzipped");
  11020. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11022. EXPECT_EQ("Hello World!", res->body);
  11023. #else
  11024. ASSERT_FALSE(res);
  11025. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11026. #endif
  11027. }
  11028. {
  11029. // open_stream() must behave the same way.
  11030. auto handle = cli.open_stream("GET", "/gzipped");
  11031. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11032. ASSERT_TRUE(handle.is_valid());
  11033. std::string received;
  11034. char buf[256];
  11035. ssize_t n;
  11036. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11037. received.append(buf, static_cast<size_t>(n));
  11038. }
  11039. EXPECT_EQ("Hello World!", received);
  11040. #else
  11041. EXPECT_FALSE(handle.is_valid());
  11042. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11043. #endif
  11044. }
  11045. {
  11046. // A differently-cased coding must not be mistaken for an unknown one, or
  11047. // the body would be handed back still compressed.
  11048. auto res = cli.Get("/gzipped-uppercase");
  11049. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11051. EXPECT_EQ("Hello World!", res->body);
  11052. #else
  11053. ASSERT_FALSE(res);
  11054. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11055. #endif
  11056. }
  11057. }
  11058. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11059. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11060. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11061. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11062. // body a second time and appending a second Content-Encoding field line, so
  11063. // clients that decode one coding per listed value handed back raw gzip bytes.
  11064. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11065. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11066. Server svr;
  11067. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11068. // keeps the server from applying a coding of its own.
  11069. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11070. res.set_content(gzipped, "text/plain");
  11071. res.set_header("Content-Encoding", "gzip");
  11072. });
  11073. auto port = svr.bind_to_any_port(HOST);
  11074. thread t = thread([&]() { svr.listen_after_bind(); });
  11075. auto se = detail::scope_exit([&] {
  11076. svr.stop();
  11077. t.join();
  11078. ASSERT_FALSE(svr.is_running());
  11079. });
  11080. svr.wait_until_ready();
  11081. Client cli(HOST, port);
  11082. Headers headers = {{"Accept-Encoding", "gzip"}};
  11083. auto res = cli.Get("/pre-gzipped", headers);
  11084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11085. EXPECT_EQ(StatusCode::OK_200, res->status);
  11086. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11087. EXPECT_EQ("Hello World!", res->body);
  11088. }
  11089. // A chunked provider settles its coding where the headers are written and
  11090. // reuses it at write time. Both ends of that have to hold: a handler's own
  11091. // Content-Encoding suppresses the coding, and a response without one is still
  11092. // compressed as it always was.
  11093. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11094. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11095. const std::string plain = "Hello World! Hello World! Hello World!";
  11096. Server svr;
  11097. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11098. res.set_header("Content-Encoding", "gzip");
  11099. res.set_chunked_content_provider(
  11100. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11101. sink.write(gzipped.data(), gzipped.size());
  11102. sink.done();
  11103. return true;
  11104. });
  11105. });
  11106. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11107. res.set_chunked_content_provider(
  11108. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11109. sink.write(plain.data(), plain.size());
  11110. sink.done();
  11111. return true;
  11112. });
  11113. });
  11114. auto port = svr.bind_to_any_port(HOST);
  11115. thread t = thread([&]() { svr.listen_after_bind(); });
  11116. auto se = detail::scope_exit([&] {
  11117. svr.stop();
  11118. t.join();
  11119. ASSERT_FALSE(svr.is_running());
  11120. });
  11121. svr.wait_until_ready();
  11122. Client cli(HOST, port);
  11123. Headers headers = {{"Accept-Encoding", "gzip"}};
  11124. {
  11125. auto res = cli.Get("/pre-gzipped", headers);
  11126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11127. EXPECT_EQ(StatusCode::OK_200, res->status);
  11128. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11129. EXPECT_EQ("Hello World!", res->body);
  11130. }
  11131. {
  11132. auto res = cli.Get("/negotiated", headers);
  11133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11134. EXPECT_EQ(StatusCode::OK_200, res->status);
  11135. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11136. EXPECT_EQ(plain, res->body);
  11137. }
  11138. }
  11139. #endif
  11140. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11141. // the same message as the comma-joined one, so both have to be read the same
  11142. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11143. // single gzip coding, and a body the sender says was encoded twice was handed
  11144. // back after one pass, still compressed but presented as decoded.
  11145. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11146. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11147. Server svr;
  11148. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11149. res.set_content(body, "image/jpeg");
  11150. res.headers.emplace("Content-Encoding", "gzip");
  11151. res.headers.emplace("Content-Encoding", "gzip");
  11152. });
  11153. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11154. res.set_content(body, "image/jpeg");
  11155. res.set_header("Content-Encoding", "gzip, gzip");
  11156. });
  11157. auto port = svr.bind_to_any_port(HOST);
  11158. thread t = thread([&]() { svr.listen_after_bind(); });
  11159. auto se = detail::scope_exit([&] {
  11160. svr.stop();
  11161. t.join();
  11162. ASSERT_FALSE(svr.is_running());
  11163. });
  11164. svr.wait_until_ready();
  11165. Client cli(HOST, port);
  11166. // Two codings is not something cpp-httplib decodes, so both representations
  11167. // take the pass-through path rather than one of them being gunzipped once.
  11168. for (const char *path : {"/split", "/joined"}) {
  11169. auto res = cli.Get(path);
  11170. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11171. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11172. EXPECT_EQ(body, res->body) << path;
  11173. }
  11174. }
  11175. // Regression test for DoS vulnerability: a malicious server sending a response
  11176. // without Content-Length header must not cause unbounded memory consumption on
  11177. // the client side. The client should stop reading after a reasonable limit,
  11178. // similar to the server-side set_payload_max_length protection.
  11179. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11180. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11181. #ifndef _WIN32
  11182. signal(SIGPIPE, SIG_IGN);
  11183. #endif
  11184. auto server_thread = std::thread([] {
  11185. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11186. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11187. default_socket_options(srv);
  11188. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11189. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11190. sockaddr_in addr{};
  11191. addr.sin_family = AF_INET;
  11192. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11193. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11194. int opt = 1;
  11195. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11196. #ifdef _WIN32
  11197. reinterpret_cast<const char *>(&opt),
  11198. #else
  11199. &opt,
  11200. #endif
  11201. sizeof(opt));
  11202. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11203. ::listen(srv, 1);
  11204. sockaddr_in cli_addr{};
  11205. socklen_t cli_len = sizeof(cli_addr);
  11206. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11207. if (cli != INVALID_SOCKET) {
  11208. char buf[4096];
  11209. ::recv(cli, buf, sizeof(buf), 0);
  11210. // Malicious response: no Content-Length, no chunked encoding
  11211. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11212. "Connection: close\r\n"
  11213. "\r\n";
  11214. ::send(cli,
  11215. #ifdef _WIN32
  11216. static_cast<const char *>(response_header.c_str()),
  11217. static_cast<int>(response_header.size()),
  11218. #else
  11219. response_header.c_str(), response_header.size(),
  11220. #endif
  11221. 0);
  11222. // Send 10MB of data
  11223. std::string chunk(64 * 1024, 'A');
  11224. size_t total_sent = 0;
  11225. while (total_sent < MALICIOUS_DATA_SIZE) {
  11226. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11227. auto sent = ::send(cli,
  11228. #ifdef _WIN32
  11229. static_cast<const char *>(chunk.c_str()),
  11230. static_cast<int>(to_send),
  11231. #else
  11232. chunk.c_str(), to_send,
  11233. #endif
  11234. 0);
  11235. if (sent <= 0) break;
  11236. total_sent += static_cast<size_t>(sent);
  11237. }
  11238. detail::close_socket(cli);
  11239. }
  11240. detail::close_socket(srv);
  11241. });
  11242. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11243. size_t total_read = 0;
  11244. {
  11245. Client cli("127.0.0.1", PORT + 2);
  11246. cli.set_read_timeout(5, 0);
  11247. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11248. auto stream = cli.open_stream("GET", "/malicious");
  11249. ASSERT_TRUE(stream.is_valid());
  11250. char buffer[64 * 1024];
  11251. ssize_t n;
  11252. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11253. total_read += static_cast<size_t>(n);
  11254. }
  11255. } // StreamHandle and Client destroyed here, closing the socket
  11256. server_thread.join();
  11257. // With set_payload_max_length, the client must stop reading before consuming
  11258. // all 10MB. The read loop should be cut off at or near the configured limit.
  11259. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11260. << "Client read " << total_read << " bytes, exceeding the configured "
  11261. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11262. }
  11263. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11264. // the entire response body without truncation.
  11265. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11266. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11267. #ifndef _WIN32
  11268. signal(SIGPIPE, SIG_IGN);
  11269. #endif
  11270. auto server_thread = std::thread([] {
  11271. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11272. default_socket_options(srv);
  11273. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11274. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11275. sockaddr_in addr{};
  11276. addr.sin_family = AF_INET;
  11277. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11278. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11279. int opt = 1;
  11280. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11281. #ifdef _WIN32
  11282. reinterpret_cast<const char *>(&opt),
  11283. #else
  11284. &opt,
  11285. #endif
  11286. sizeof(opt));
  11287. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11288. ::listen(srv, 1);
  11289. sockaddr_in cli_addr{};
  11290. socklen_t cli_len = sizeof(cli_addr);
  11291. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11292. if (cli != INVALID_SOCKET) {
  11293. char buf[4096];
  11294. ::recv(cli, buf, sizeof(buf), 0);
  11295. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11296. "Connection: close\r\n"
  11297. "\r\n";
  11298. ::send(cli,
  11299. #ifdef _WIN32
  11300. static_cast<const char *>(response_header.c_str()),
  11301. static_cast<int>(response_header.size()),
  11302. #else
  11303. response_header.c_str(), response_header.size(),
  11304. #endif
  11305. 0);
  11306. std::string chunk(64 * 1024, 'A');
  11307. size_t total_sent = 0;
  11308. while (total_sent < DATA_SIZE) {
  11309. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11310. auto sent = ::send(cli,
  11311. #ifdef _WIN32
  11312. static_cast<const char *>(chunk.c_str()),
  11313. static_cast<int>(to_send),
  11314. #else
  11315. chunk.c_str(), to_send,
  11316. #endif
  11317. 0);
  11318. if (sent <= 0) break;
  11319. total_sent += static_cast<size_t>(sent);
  11320. }
  11321. #ifdef _WIN32
  11322. ::shutdown(cli, SD_SEND);
  11323. #else
  11324. ::shutdown(cli, SHUT_WR);
  11325. #endif
  11326. // Drain until the client closes its end, ensuring all data is delivered
  11327. char drain[1024];
  11328. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11329. detail::close_socket(cli);
  11330. }
  11331. detail::close_socket(srv);
  11332. });
  11333. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11334. size_t total_read = 0;
  11335. {
  11336. Client cli("127.0.0.1", PORT + 2);
  11337. cli.set_read_timeout(5, 0);
  11338. cli.set_payload_max_length(0); // 0 means no limit
  11339. auto stream = cli.open_stream("GET", "/data");
  11340. ASSERT_TRUE(stream.is_valid());
  11341. char buffer[64 * 1024];
  11342. ssize_t n;
  11343. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11344. total_read += static_cast<size_t>(n);
  11345. }
  11346. }
  11347. server_thread.join();
  11348. EXPECT_EQ(total_read, DATA_SIZE)
  11349. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11350. << " bytes without truncation, but only read " << total_read << " bytes.";
  11351. }
  11352. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11353. // enormous Content-Length must not cause the client to pre-allocate a huge
  11354. // response body buffer. The reservation is capped at payload_max_length_, and
  11355. // the read itself fails when the body exceeds the limit.
  11356. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11357. #ifndef _WIN32
  11358. signal(SIGPIPE, SIG_IGN);
  11359. #endif
  11360. auto server_thread = std::thread([] {
  11361. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11362. default_socket_options(srv);
  11363. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11364. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11365. sockaddr_in addr{};
  11366. addr.sin_family = AF_INET;
  11367. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11368. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11369. int opt = 1;
  11370. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11371. #ifdef _WIN32
  11372. reinterpret_cast<const char *>(&opt),
  11373. #else
  11374. &opt,
  11375. #endif
  11376. sizeof(opt));
  11377. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11378. ::listen(srv, 1);
  11379. sockaddr_in cli_addr{};
  11380. socklen_t cli_len = sizeof(cli_addr);
  11381. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11382. if (cli != INVALID_SOCKET) {
  11383. char buf[4096];
  11384. ::recv(cli, buf, sizeof(buf), 0);
  11385. // Malicious response: claim a 20GB body but send only a tiny payload.
  11386. std::string response = "HTTP/1.1 200 OK\r\n"
  11387. "Content-Length: 20000000000\r\n"
  11388. "\r\n"
  11389. "abc";
  11390. ::send(cli,
  11391. #ifdef _WIN32
  11392. static_cast<const char *>(response.c_str()),
  11393. static_cast<int>(response.size()),
  11394. #else
  11395. response.c_str(), response.size(),
  11396. #endif
  11397. 0);
  11398. detail::close_socket(cli);
  11399. }
  11400. detail::close_socket(srv);
  11401. });
  11402. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11403. {
  11404. Client cli("127.0.0.1", PORT + 2);
  11405. cli.set_read_timeout(5, 0);
  11406. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11407. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11408. // (server claims more bytes than payload_max_length permits), but it must
  11409. // not exhaust memory before getting there.
  11410. auto res = cli.Get("/malicious");
  11411. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11412. }
  11413. server_thread.join();
  11414. }
  11415. // Verify that content_receiver bypasses the default payload_max_length,
  11416. // allowing streaming downloads larger than 100MB without requiring an explicit
  11417. // set_payload_max_length call.
  11418. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11419. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11420. #ifndef _WIN32
  11421. signal(SIGPIPE, SIG_IGN);
  11422. #endif
  11423. auto server_thread = std::thread([] {
  11424. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11425. default_socket_options(srv);
  11426. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11427. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11428. sockaddr_in addr{};
  11429. addr.sin_family = AF_INET;
  11430. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11431. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11432. int opt = 1;
  11433. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11434. #ifdef _WIN32
  11435. reinterpret_cast<const char *>(&opt),
  11436. #else
  11437. &opt,
  11438. #endif
  11439. sizeof(opt));
  11440. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11441. ::listen(srv, 1);
  11442. sockaddr_in cli_addr{};
  11443. socklen_t cli_len = sizeof(cli_addr);
  11444. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11445. if (cli != INVALID_SOCKET) {
  11446. char buf[4096];
  11447. ::recv(cli, buf, sizeof(buf), 0);
  11448. // Response with Content-Length larger than default 100MB limit
  11449. auto content_length = std::to_string(DATA_SIZE);
  11450. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11451. "Content-Length: " +
  11452. content_length +
  11453. "\r\n"
  11454. "Connection: close\r\n"
  11455. "\r\n";
  11456. ::send(cli,
  11457. #ifdef _WIN32
  11458. static_cast<const char *>(response_header.c_str()),
  11459. static_cast<int>(response_header.size()),
  11460. #else
  11461. response_header.c_str(), response_header.size(),
  11462. #endif
  11463. 0);
  11464. std::string chunk(64 * 1024, 'A');
  11465. size_t total_sent = 0;
  11466. while (total_sent < DATA_SIZE) {
  11467. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11468. auto sent = ::send(cli,
  11469. #ifdef _WIN32
  11470. static_cast<const char *>(chunk.c_str()),
  11471. static_cast<int>(to_send),
  11472. #else
  11473. chunk.c_str(), to_send,
  11474. #endif
  11475. 0);
  11476. if (sent <= 0) break;
  11477. total_sent += static_cast<size_t>(sent);
  11478. }
  11479. detail::close_socket(cli);
  11480. }
  11481. detail::close_socket(srv);
  11482. });
  11483. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11484. size_t total_received = 0;
  11485. {
  11486. Client cli("127.0.0.1", PORT + 2);
  11487. cli.set_read_timeout(10, 0);
  11488. // Do NOT call set_payload_max_length — use the default 100MB limit
  11489. auto res =
  11490. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11491. total_received += data_length;
  11492. return true;
  11493. });
  11494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11495. EXPECT_EQ(StatusCode::OK_200, res->status);
  11496. }
  11497. server_thread.join();
  11498. EXPECT_EQ(total_received, DATA_SIZE)
  11499. << "With content_receiver, the client should read all " << DATA_SIZE
  11500. << " bytes despite the default 100MB payload_max_length, but only read "
  11501. << total_received << " bytes.";
  11502. }
  11503. // Verify that an explicit set_payload_max_length smaller than the response is
  11504. // enforced even when a content_receiver is used.
  11505. TEST(ClientVulnerabilityTest,
  11506. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11507. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11508. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11509. #ifndef _WIN32
  11510. signal(SIGPIPE, SIG_IGN);
  11511. #endif
  11512. auto server_thread = std::thread([] {
  11513. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11514. default_socket_options(srv);
  11515. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11516. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11517. sockaddr_in addr{};
  11518. addr.sin_family = AF_INET;
  11519. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11520. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11521. int opt = 1;
  11522. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11523. #ifdef _WIN32
  11524. reinterpret_cast<const char *>(&opt),
  11525. #else
  11526. &opt,
  11527. #endif
  11528. sizeof(opt));
  11529. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11530. ::listen(srv, 1);
  11531. sockaddr_in cli_addr{};
  11532. socklen_t cli_len = sizeof(cli_addr);
  11533. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11534. if (cli != INVALID_SOCKET) {
  11535. char buf[4096];
  11536. ::recv(cli, buf, sizeof(buf), 0);
  11537. auto content_length = std::to_string(DATA_SIZE);
  11538. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11539. "Content-Length: " +
  11540. content_length +
  11541. "\r\n"
  11542. "Connection: close\r\n"
  11543. "\r\n";
  11544. ::send(cli,
  11545. #ifdef _WIN32
  11546. static_cast<const char *>(response_header.c_str()),
  11547. static_cast<int>(response_header.size()),
  11548. #else
  11549. response_header.c_str(), response_header.size(),
  11550. #endif
  11551. 0);
  11552. std::string chunk(64 * 1024, 'A');
  11553. size_t total_sent = 0;
  11554. while (total_sent < DATA_SIZE) {
  11555. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11556. auto sent = ::send(cli,
  11557. #ifdef _WIN32
  11558. static_cast<const char *>(chunk.c_str()),
  11559. static_cast<int>(to_send),
  11560. #else
  11561. chunk.c_str(), to_send,
  11562. #endif
  11563. 0);
  11564. if (sent <= 0) break;
  11565. total_sent += static_cast<size_t>(sent);
  11566. }
  11567. detail::close_socket(cli);
  11568. }
  11569. detail::close_socket(srv);
  11570. });
  11571. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11572. size_t total_received = 0;
  11573. {
  11574. Client cli("127.0.0.1", PORT + 2);
  11575. cli.set_read_timeout(10, 0);
  11576. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11577. auto res =
  11578. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11579. total_received += data_length;
  11580. return true;
  11581. });
  11582. // Should fail because 200MB exceeds the explicit 150MB limit
  11583. EXPECT_FALSE(res);
  11584. }
  11585. server_thread.join();
  11586. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11587. << "Client with content_receiver should respect the explicit "
  11588. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11589. << total_received << " bytes.";
  11590. }
  11591. // Verify that an explicit set_payload_max_length larger than the response
  11592. // allows the content_receiver to read all data successfully.
  11593. TEST(ClientVulnerabilityTest,
  11594. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11595. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11596. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11597. #ifndef _WIN32
  11598. signal(SIGPIPE, SIG_IGN);
  11599. #endif
  11600. auto server_thread = std::thread([] {
  11601. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11602. default_socket_options(srv);
  11603. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11604. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11605. sockaddr_in addr{};
  11606. addr.sin_family = AF_INET;
  11607. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11608. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11609. int opt = 1;
  11610. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11611. #ifdef _WIN32
  11612. reinterpret_cast<const char *>(&opt),
  11613. #else
  11614. &opt,
  11615. #endif
  11616. sizeof(opt));
  11617. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11618. ::listen(srv, 1);
  11619. sockaddr_in cli_addr{};
  11620. socklen_t cli_len = sizeof(cli_addr);
  11621. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11622. if (cli != INVALID_SOCKET) {
  11623. char buf[4096];
  11624. ::recv(cli, buf, sizeof(buf), 0);
  11625. auto content_length = std::to_string(DATA_SIZE);
  11626. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11627. "Content-Length: " +
  11628. content_length +
  11629. "\r\n"
  11630. "Connection: close\r\n"
  11631. "\r\n";
  11632. ::send(cli,
  11633. #ifdef _WIN32
  11634. static_cast<const char *>(response_header.c_str()),
  11635. static_cast<int>(response_header.size()),
  11636. #else
  11637. response_header.c_str(), response_header.size(),
  11638. #endif
  11639. 0);
  11640. std::string chunk(64 * 1024, 'A');
  11641. size_t total_sent = 0;
  11642. while (total_sent < DATA_SIZE) {
  11643. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11644. auto sent = ::send(cli,
  11645. #ifdef _WIN32
  11646. static_cast<const char *>(chunk.c_str()),
  11647. static_cast<int>(to_send),
  11648. #else
  11649. chunk.c_str(), to_send,
  11650. #endif
  11651. 0);
  11652. if (sent <= 0) break;
  11653. total_sent += static_cast<size_t>(sent);
  11654. }
  11655. #ifdef _WIN32
  11656. ::shutdown(cli, SD_SEND);
  11657. #else
  11658. ::shutdown(cli, SHUT_WR);
  11659. #endif
  11660. char drain[1024];
  11661. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11662. detail::close_socket(cli);
  11663. }
  11664. detail::close_socket(srv);
  11665. });
  11666. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11667. size_t total_received = 0;
  11668. {
  11669. Client cli("127.0.0.1", PORT + 2);
  11670. cli.set_read_timeout(10, 0);
  11671. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  11672. auto res =
  11673. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11674. total_received += data_length;
  11675. return true;
  11676. });
  11677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11678. EXPECT_EQ(StatusCode::OK_200, res->status);
  11679. }
  11680. server_thread.join();
  11681. EXPECT_EQ(total_received, DATA_SIZE)
  11682. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  11683. << " bytes (larger than " << DATA_SIZE
  11684. << " bytes response), content_receiver should read all data, but only "
  11685. "read "
  11686. << total_received << " bytes.";
  11687. }
  11688. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  11689. // Regression test for "zip bomb" attack on the client side: a malicious server
  11690. // sends a small gzip-compressed response that decompresses to a huge payload.
  11691. // The client must enforce payload_max_length on the decompressed size.
  11692. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  11693. constexpr size_t DECOMPRESSED_SIZE =
  11694. 10 * 1024 * 1024; // 10MB after decompression
  11695. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11696. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  11697. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  11698. std::string compressed;
  11699. {
  11700. httplib::detail::gzip_compressor compressor;
  11701. bool ok =
  11702. compressor.compress(uncompressed.data(), uncompressed.size(),
  11703. /*last=*/true, [&](const char *buf, size_t len) {
  11704. compressed.append(buf, len);
  11705. return true;
  11706. });
  11707. ASSERT_TRUE(ok);
  11708. }
  11709. // Sanity: compressed data should be much smaller than the decompressed size
  11710. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  11711. #ifndef _WIN32
  11712. signal(SIGPIPE, SIG_IGN);
  11713. #endif
  11714. // Set up the listening socket in the main thread so the server is guaranteed
  11715. // to be ready before the client connects (eliminates race condition).
  11716. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11717. default_socket_options(srv);
  11718. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11719. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11720. sockaddr_in addr{};
  11721. addr.sin_family = AF_INET;
  11722. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  11723. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11724. int opt = 1;
  11725. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11726. #ifdef _WIN32
  11727. reinterpret_cast<const char *>(&opt),
  11728. #else
  11729. &opt,
  11730. #endif
  11731. sizeof(opt));
  11732. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11733. ASSERT_EQ(0, ::listen(srv, 1));
  11734. auto server_thread = std::thread([&compressed, srv] {
  11735. sockaddr_in cli_addr{};
  11736. socklen_t cli_len = sizeof(cli_addr);
  11737. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11738. if (cli != INVALID_SOCKET) {
  11739. // Read the full HTTP request (until \r\n\r\n)
  11740. char buf[4096];
  11741. size_t total = 0;
  11742. while (total < sizeof(buf)) {
  11743. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  11744. if (n <= 0) break;
  11745. total += static_cast<size_t>(n);
  11746. // Check for end of headers
  11747. if (total >= 4) {
  11748. std::string req(buf, total);
  11749. if (req.find("\r\n\r\n") != std::string::npos) break;
  11750. }
  11751. }
  11752. // Malicious response: gzip-compressed body, no Content-Length
  11753. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11754. "Content-Encoding: gzip\r\n"
  11755. "Connection: close\r\n"
  11756. "\r\n";
  11757. ::send(cli,
  11758. #ifdef _WIN32
  11759. static_cast<const char *>(response_header.c_str()),
  11760. static_cast<int>(response_header.size()),
  11761. #else
  11762. response_header.c_str(), response_header.size(),
  11763. #endif
  11764. 0);
  11765. // Send the compressed payload (small on the wire, huge when decompressed)
  11766. size_t total_sent = 0;
  11767. while (total_sent < compressed.size()) {
  11768. auto to_send = std::min(compressed.size() - total_sent,
  11769. static_cast<size_t>(64 * 1024));
  11770. auto sent =
  11771. ::send(cli,
  11772. #ifdef _WIN32
  11773. static_cast<const char *>(compressed.c_str() + total_sent),
  11774. static_cast<int>(to_send),
  11775. #else
  11776. compressed.c_str() + total_sent, to_send,
  11777. #endif
  11778. 0);
  11779. if (sent <= 0) break;
  11780. total_sent += static_cast<size_t>(sent);
  11781. }
  11782. detail::close_socket(cli);
  11783. }
  11784. });
  11785. auto se = detail::scope_exit([&] {
  11786. detail::close_socket(srv);
  11787. server_thread.join();
  11788. });
  11789. size_t total_decompressed = 0;
  11790. {
  11791. Client cli("127.0.0.1", PORT + 3);
  11792. cli.set_read_timeout(5, 0);
  11793. cli.set_decompress(true);
  11794. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11795. auto stream = cli.open_stream("GET", "/zipbomb");
  11796. ASSERT_TRUE(stream.is_valid());
  11797. char buffer[64 * 1024];
  11798. ssize_t n;
  11799. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11800. total_decompressed += static_cast<size_t>(n);
  11801. }
  11802. }
  11803. // The decompressed size must be capped by payload_max_length. Without
  11804. // protection, the client would decompress the full 10MB from a tiny
  11805. // compressed payload, enabling a zip bomb DoS attack.
  11806. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  11807. << "Client decompressed " << total_decompressed
  11808. << " bytes from a gzip response. The decompressed size should be "
  11809. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  11810. }
  11811. #endif
  11812. TEST(HostAndPortPropertiesTest, NoSSL) {
  11813. httplib::Client cli("www.google.com", 1234);
  11814. ASSERT_EQ("www.google.com", cli.host());
  11815. ASSERT_EQ(1234, cli.port());
  11816. }
  11817. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  11818. httplib::Client cli("www.google.com:1234");
  11819. ASSERT_EQ("www.google.com", cli.host());
  11820. ASSERT_EQ(1234, cli.port());
  11821. }
  11822. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  11823. // Port number that overflows int — should not crash, client becomes invalid
  11824. httplib::Client cli("http://www.google.com:99999999999999999999");
  11825. ASSERT_FALSE(cli.is_valid());
  11826. }
  11827. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  11828. // Port 99999 exceeds valid range (1-65535) — should not crash
  11829. httplib::Client cli("http://www.google.com:99999");
  11830. ASSERT_FALSE(cli.is_valid());
  11831. }
  11832. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  11833. httplib::Client cli("http://www.google.com:80abc");
  11834. ASSERT_FALSE(cli.is_valid());
  11835. }
  11836. #ifdef CPPHTTPLIB_SSL_ENABLED
  11837. TEST(HostAndPortPropertiesTest, SSL) {
  11838. httplib::SSLClient cli("www.google.com");
  11839. ASSERT_EQ("www.google.com", cli.host());
  11840. ASSERT_EQ(443, cli.port());
  11841. }
  11842. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  11843. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  11844. std::string cert;
  11845. read_file(CA_CERT_FILE, cert);
  11846. httplib::SSLClient httplib_client("www.google.com");
  11847. // Load CA store first time
  11848. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11849. // Load CA store second time (update)
  11850. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11851. // Verify client is still valid and can make connections
  11852. httplib_client.enable_server_certificate_verification(true);
  11853. auto res = httplib_client.Get("/");
  11854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11855. // Google may return 200 or 301 depending on various factors
  11856. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  11857. res->status == StatusCode::MovedPermanently_301);
  11858. }
  11859. TEST(SSLClientTest, ServerNameIndication_Online) {
  11860. auto host = "httpbingo.org";
  11861. auto path = std::string{"/get"};
  11862. SSLClient cli(host, 443);
  11863. auto res = cli.Get(path);
  11864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11865. ASSERT_EQ(StatusCode::OK_200, res->status);
  11866. }
  11867. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  11868. // Use a site that will cause SSL verification failure due to self-signed cert
  11869. SSLClient cli("self-signed.badssl.com", 443);
  11870. cli.enable_server_certificate_verification(true);
  11871. auto res = cli.Get("/");
  11872. ASSERT_TRUE(!res);
  11873. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11874. // Verify backend error is captured for SSLServerVerification
  11875. // This occurs when certificate verification fails
  11876. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  11877. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  11878. EXPECT_NE(0UL, res.ssl_backend_error());
  11879. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11880. // For OpenSSL, ssl_error is 0 for verification errors
  11881. EXPECT_EQ(0, res.ssl_error());
  11882. #if !defined(_WIN32) || \
  11883. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11884. // On non-Windows or when Windows Schannel is disabled, the error comes
  11885. // from OpenSSL's verification
  11886. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  11887. res.ssl_backend_error());
  11888. #endif
  11889. #endif
  11890. }
  11891. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  11892. // Use a site where hostname doesn't match the certificate
  11893. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  11894. SSLClient cli("wrong.host.badssl.com", 443);
  11895. cli.enable_server_certificate_verification(true);
  11896. cli.enable_server_hostname_verification(true);
  11897. auto res = cli.Get("/");
  11898. ASSERT_TRUE(!res);
  11899. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  11900. // Verify backend error is captured for hostname verification failure
  11901. EXPECT_NE(0UL, res.ssl_backend_error());
  11902. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11903. // For OpenSSL, ssl_error is 0 for verification errors
  11904. EXPECT_EQ(0, res.ssl_error());
  11905. #if !defined(_WIN32) || \
  11906. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11907. // On non-Windows or when Windows Schannel is disabled, the error comes
  11908. // from OpenSSL's hostname verification
  11909. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  11910. res.ssl_backend_error());
  11911. #endif
  11912. #endif
  11913. }
  11914. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  11915. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11916. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  11917. SSLClient cli("www.google.com", 443);
  11918. cli.enable_server_certificate_verification(true);
  11919. auto res = cli.Get("/");
  11920. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11921. }
  11922. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  11923. SSLClient cli("www.google.com", 443);
  11924. cli.enable_server_certificate_verification(true);
  11925. cli.enable_windows_certificate_verification(false);
  11926. auto res = cli.Get("/");
  11927. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11928. }
  11929. // The server sends an intermediate cross-signed by a root Windows trusts,
  11930. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  11931. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  11932. SSLClient cli("accounts.spotify.com", 443);
  11933. auto res = cli.Get("/");
  11934. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  11935. << " ssl_backend_error=" << res.ssl_backend_error();
  11936. }
  11937. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  11938. // policy status, which no backend reports for a self-signed certificate.
  11939. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  11940. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11941. ASSERT_TRUE(svr.is_valid());
  11942. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11943. auto se = detail::scope_exit([&] {
  11944. svr.stop();
  11945. t.join();
  11946. ASSERT_FALSE(svr.is_running());
  11947. });
  11948. svr.wait_until_ready();
  11949. SSLClient cli("127.0.0.1", PORT);
  11950. cli.set_connection_timeout(30);
  11951. auto res = cli.Get("/");
  11952. ASSERT_FALSE(res);
  11953. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11954. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  11955. }
  11956. #endif
  11957. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  11958. Client cli("https://google.com");
  11959. auto res = cli.Get("/");
  11960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11961. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11962. }
  11963. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  11964. SSLClient cli("google.com");
  11965. cli.set_ca_cert_path(CA_CERT_FILE);
  11966. auto res = cli.Get("/");
  11967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11968. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11969. }
  11970. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  11971. SSLClient cli("google.com");
  11972. cli.enable_server_certificate_verification(true);
  11973. cli.set_ca_cert_path("hello");
  11974. auto res = cli.Get("/");
  11975. ASSERT_TRUE(!res);
  11976. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  11977. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  11978. // should be set
  11979. EXPECT_EQ(0, res.ssl_error());
  11980. // Verify backend error is captured for SSLLoadingCerts
  11981. // This error occurs when loading CA certificates fails
  11982. EXPECT_NE(0UL, res.ssl_backend_error());
  11983. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11984. // OpenSSL specific error codes:
  11985. // > openssl errstr 0x80000002
  11986. // error:80000002:system library::No such file or directory
  11987. // > openssl errstr 0xA000126
  11988. // error:0A000126:SSL routines::unexpected eof while reading
  11989. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  11990. res.ssl_backend_error() == 0xA000126);
  11991. #endif
  11992. }
  11993. TEST(SSLClientTest, ServerCertificateVerification4) {
  11994. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11995. ASSERT_TRUE(svr.is_valid());
  11996. svr.Get("/test", [&](const Request &, Response &res) {
  11997. res.set_content("test", "text/plain");
  11998. svr.stop();
  11999. ASSERT_TRUE(true);
  12000. });
  12001. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12002. auto se = detail::scope_exit([&] {
  12003. t.join();
  12004. ASSERT_FALSE(svr.is_running());
  12005. });
  12006. svr.wait_until_ready();
  12007. SSLClient cli("127.0.0.1", PORT);
  12008. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12009. cli.enable_server_certificate_verification(true);
  12010. cli.set_connection_timeout(30);
  12011. auto res = cli.Get("/test");
  12012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12013. ASSERT_EQ(StatusCode::OK_200, res->status);
  12014. }
  12015. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12016. std::string cert;
  12017. read_file(CA_CERT_FILE, cert);
  12018. SSLClient cli("google.com");
  12019. cli.load_ca_cert_store(cert.data(), cert.size());
  12020. const auto res = cli.Get("/");
  12021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12022. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12023. }
  12024. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12025. // clang-format off
  12026. static constexpr char cert[] =
  12027. "GlobalSign Root CA\n"
  12028. "==================\n"
  12029. "-----BEGIN CERTIFICATE-----\n"
  12030. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12031. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12032. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12033. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12034. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12035. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12036. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12037. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12038. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12039. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12040. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12041. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12042. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12043. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12044. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12045. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12046. "-----END CERTIFICATE-----\n";
  12047. // clang-format on
  12048. SSLClient cli("google.com");
  12049. cli.load_ca_cert_store(cert, sizeof(cert));
  12050. const auto res = cli.Get("/");
  12051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12052. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12053. }
  12054. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12055. SSLClient cli("www.youtube.com");
  12056. cli.set_ca_cert_path(CA_CERT_FILE);
  12057. cli.enable_server_certificate_verification(true);
  12058. cli.set_follow_location(true);
  12059. auto res = cli.Get("/");
  12060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12061. ASSERT_EQ(StatusCode::OK_200, res->status);
  12062. }
  12063. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12064. SSLClient cli("wWw.YouTube.Com");
  12065. cli.set_ca_cert_path(CA_CERT_FILE);
  12066. cli.enable_server_certificate_verification(true);
  12067. cli.enable_server_hostname_verification(true);
  12068. cli.set_follow_location(true);
  12069. auto res = cli.Get("/");
  12070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12071. ASSERT_EQ(StatusCode::OK_200, res->status);
  12072. }
  12073. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12074. SSLClient cli("gOoGlE.COm");
  12075. cli.enable_server_certificate_verification(true);
  12076. cli.enable_server_hostname_verification(true);
  12077. cli.set_follow_location(true);
  12078. auto res = cli.Get("/");
  12079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12080. ASSERT_EQ(StatusCode::OK_200, res->status);
  12081. }
  12082. TEST(SSLClientTest, Issue2004_Online) {
  12083. Client client("https://google.com");
  12084. client.set_follow_location(true);
  12085. auto res = client.Get("/");
  12086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12087. ASSERT_EQ(StatusCode::OK_200, res->status);
  12088. auto body = res->body;
  12089. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12090. }
  12091. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12092. // Create SSLClient with invalid cert/key to make is_valid() return false
  12093. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12094. "nonexistent_key.pem");
  12095. // is_valid() should be false due to cert loading failure
  12096. ASSERT_FALSE(cli.is_valid());
  12097. auto res = cli.Get("/");
  12098. ASSERT_FALSE(res);
  12099. EXPECT_EQ(Error::SSLConnection, res.error());
  12100. }
  12101. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12102. // Test for Issue #2251: SSL error not properly reported when client cert
  12103. // and key paths are swapped or mismatched
  12104. // This simulates the scenario where user accidentally swaps the cert and key
  12105. // files
  12106. // Using client cert file as private key and vice versa (completely wrong)
  12107. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12108. // Should fail validation due to cert/key mismatch
  12109. ASSERT_FALSE(cli.is_valid());
  12110. // Attempt to make a request should fail with proper error
  12111. auto res = cli.Get("/");
  12112. ASSERT_FALSE(res);
  12113. EXPECT_EQ(Error::SSLConnection, res.error());
  12114. // SSL error should be recorded in the Result object (this is the key fix for
  12115. // Issue #2251)
  12116. auto backend_error = res.ssl_backend_error();
  12117. EXPECT_NE(0u, backend_error);
  12118. }
  12119. // Tests cert/key mismatch detection at the TLS context level
  12120. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12121. // Test that using mismatched cert/key causes connection failure.
  12122. // We verify this at the SSLClient level rather than through internal
  12123. // TLS API functions.
  12124. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12125. cli.enable_server_certificate_verification(false);
  12126. cli.set_connection_timeout(2);
  12127. // The mismatch should cause a connection or handshake error
  12128. auto res = cli.Get("/test");
  12129. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12130. // Either way, the request should fail
  12131. EXPECT_FALSE(res);
  12132. }
  12133. #endif
  12134. #if 0
  12135. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12136. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12137. ASSERT_TRUE(cli != nullptr);
  12138. cli->set_address_family(AF_INET6);
  12139. cli->set_interface("en0");
  12140. auto res = cli->Get("/get");
  12141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12142. ASSERT_EQ(StatusCode::OK_200, res->status);
  12143. }
  12144. #endif
  12145. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12146. #ifdef CPPHTTPLIB_SSL_ENABLED
  12147. void ClientCertPresent(
  12148. const std::string &client_cert_file,
  12149. const std::string &client_private_key_file,
  12150. const std::string &client_encrypted_private_key_pass = std::string()) {
  12151. using namespace httplib::tls;
  12152. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12153. CLIENT_CA_CERT_DIR);
  12154. ASSERT_TRUE(svr.is_valid());
  12155. svr.Get("/test", [&](const Request &req, Response &res) {
  12156. res.set_content("test", "text/plain");
  12157. auto cert = req.peer_cert();
  12158. ASSERT_TRUE(static_cast<bool>(cert));
  12159. std::string common_name = cert.subject_cn();
  12160. EXPECT_EQ("Common Name", common_name);
  12161. });
  12162. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12163. auto se = detail::scope_exit([&] {
  12164. svr.stop();
  12165. t.join();
  12166. ASSERT_FALSE(svr.is_running());
  12167. });
  12168. svr.wait_until_ready();
  12169. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12170. client_encrypted_private_key_pass);
  12171. cli.enable_server_certificate_verification(false);
  12172. cli.set_connection_timeout(30);
  12173. auto res = cli.Get("/test");
  12174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12175. ASSERT_EQ(StatusCode::OK_200, res->status);
  12176. }
  12177. TEST(SSLClientServerTest, ClientCertPresent) {
  12178. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12179. }
  12180. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12181. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12182. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12183. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12184. }
  12185. // PEM memory-based constructor tests (works with all TLS backends)
  12186. void PemMemoryClientCertPresent(
  12187. const std::string &client_cert_file,
  12188. const std::string &client_private_key_file,
  12189. const std::string &client_encrypted_private_key_pass = std::string()) {
  12190. // Read PEM files into memory
  12191. std::string server_cert_pem, server_key_pem;
  12192. std::string client_ca_pem;
  12193. std::string client_cert_pem, client_key_pem;
  12194. read_file(SERVER_CERT_FILE, server_cert_pem);
  12195. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12196. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12197. read_file(client_cert_file, client_cert_pem);
  12198. read_file(client_private_key_file, client_key_pem);
  12199. // Create server with PEM memory
  12200. SSLServer::PemMemory server_pem = {
  12201. server_cert_pem.c_str(),
  12202. server_cert_pem.size(),
  12203. server_key_pem.c_str(),
  12204. server_key_pem.size(),
  12205. client_ca_pem.c_str(),
  12206. client_ca_pem.size(),
  12207. nullptr // no password for server key
  12208. };
  12209. SSLServer svr(server_pem);
  12210. ASSERT_TRUE(svr.is_valid());
  12211. svr.Get("/test", [&](const Request &, Response &res) {
  12212. res.set_content("test", "text/plain");
  12213. });
  12214. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12215. auto se = detail::scope_exit([&] {
  12216. svr.stop();
  12217. t.join();
  12218. ASSERT_FALSE(svr.is_running());
  12219. });
  12220. svr.wait_until_ready();
  12221. // Create client with PEM memory
  12222. const char *password = client_encrypted_private_key_pass.empty()
  12223. ? nullptr
  12224. : client_encrypted_private_key_pass.c_str();
  12225. SSLClient::PemMemory client_pem = {
  12226. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12227. client_key_pem.size(), password};
  12228. SSLClient cli(HOST, PORT, client_pem);
  12229. cli.enable_server_certificate_verification(false);
  12230. cli.set_connection_timeout(30);
  12231. auto res = cli.Get("/test");
  12232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12233. ASSERT_EQ(StatusCode::OK_200, res->status);
  12234. }
  12235. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12236. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12237. }
  12238. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12239. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12240. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12241. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12242. }
  12243. TEST(SSLClientServerTest, ClientCertMissing) {
  12244. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12245. CLIENT_CA_CERT_DIR);
  12246. ASSERT_TRUE(svr.is_valid());
  12247. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12248. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12249. auto se = detail::scope_exit([&] {
  12250. svr.stop();
  12251. t.join();
  12252. ASSERT_FALSE(svr.is_running());
  12253. });
  12254. svr.wait_until_ready();
  12255. SSLClient cli(HOST, PORT);
  12256. cli.set_connection_timeout(30);
  12257. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12258. // the chain check on Windows, so the result does not depend on the order.
  12259. cli.enable_server_hostname_verification(false);
  12260. auto res = cli.Get("/test");
  12261. ASSERT_TRUE(!res);
  12262. // When client cert is missing and server requires it, connection fails
  12263. // Error type depends on backend implementation
  12264. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12265. res.error() == Error::SSLConnection);
  12266. // Verify backend error is captured
  12267. // Note: This test may have different error codes depending on the exact
  12268. // verification failure
  12269. EXPECT_NE(0UL, res.ssl_backend_error());
  12270. }
  12271. TEST(SSLClientServerTest, TrustDirOptional) {
  12272. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12273. ASSERT_TRUE(svr.is_valid());
  12274. svr.Get("/test", [&](const Request &, Response &res) {
  12275. res.set_content("test", "text/plain");
  12276. });
  12277. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12278. auto se = detail::scope_exit([&] {
  12279. svr.stop();
  12280. t.join();
  12281. ASSERT_FALSE(svr.is_running());
  12282. });
  12283. svr.wait_until_ready();
  12284. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12285. cli.enable_server_certificate_verification(false);
  12286. cli.set_connection_timeout(30);
  12287. auto res = cli.Get("/test");
  12288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12289. ASSERT_EQ(StatusCode::OK_200, res->status);
  12290. }
  12291. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12292. class NoListenSSLServer : public SSLServer {
  12293. public:
  12294. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12295. const char *client_ca_cert_file_path,
  12296. const char *client_ca_cert_dir_path = nullptr)
  12297. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12298. client_ca_cert_dir_path),
  12299. stop_(false) {}
  12300. std::atomic_bool stop_;
  12301. private:
  12302. bool process_and_close_socket(socket_t /*sock*/) override {
  12303. // Don't create SSL context
  12304. while (!stop_.load()) {
  12305. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12306. }
  12307. return true;
  12308. }
  12309. };
  12310. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12311. CLIENT_CA_CERT_FILE);
  12312. ASSERT_TRUE(svr.is_valid());
  12313. svr.Get("/test", [&](const Request &, Response &res) {
  12314. res.set_content("test", "text/plain");
  12315. });
  12316. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12317. auto se = detail::scope_exit([&] {
  12318. svr.stop_ = true;
  12319. svr.stop();
  12320. t.join();
  12321. ASSERT_FALSE(svr.is_running());
  12322. });
  12323. svr.wait_until_ready();
  12324. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12325. cli.enable_server_certificate_verification(false);
  12326. cli.set_connection_timeout(1);
  12327. auto res = cli.Get("/test");
  12328. ASSERT_TRUE(!res);
  12329. EXPECT_EQ(Error::SSLConnection, res.error());
  12330. // Timeout results in WantRead error code (maps to backend-specific value)
  12331. EXPECT_NE(0, res.ssl_error());
  12332. }
  12333. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12334. // Test SSLServer with client certificate verification using the standard
  12335. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12336. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12337. CLIENT_CA_CERT_DIR);
  12338. ASSERT_TRUE(svr.is_valid());
  12339. svr.Get("/test", [&](const Request &req, Response &res) {
  12340. res.set_content("test", "text/plain");
  12341. auto cert = req.peer_cert();
  12342. ASSERT_TRUE(static_cast<bool>(cert));
  12343. auto common_name = cert.subject_cn();
  12344. EXPECT_EQ("Common Name", common_name);
  12345. });
  12346. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12347. auto se = detail::scope_exit([&] {
  12348. svr.stop();
  12349. t.join();
  12350. ASSERT_FALSE(svr.is_running());
  12351. });
  12352. svr.wait_until_ready();
  12353. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12354. cli.enable_server_certificate_verification(false);
  12355. cli.set_connection_timeout(30);
  12356. auto res = cli.Get("/test");
  12357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12358. ASSERT_EQ(StatusCode::OK_200, res->status);
  12359. }
  12360. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12361. // Verifies that wildcard matching and exact matching work consistently
  12362. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12363. using namespace httplib::tls;
  12364. // We need a running server to test against
  12365. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12366. ASSERT_TRUE(svr.is_valid());
  12367. svr.Get("/test", [](const Request &, Response &res) {
  12368. res.set_content("ok", "text/plain");
  12369. });
  12370. thread t([&]() { svr.listen(HOST, PORT); });
  12371. auto se = detail::scope_exit([&] {
  12372. svr.stop();
  12373. t.join();
  12374. });
  12375. svr.wait_until_ready();
  12376. bool verify_callback_called = false;
  12377. bool verify_result_wrong = false;
  12378. SSLClient cli(HOST, PORT);
  12379. cli.enable_server_certificate_verification(true);
  12380. cli.set_ca_cert_path(CA_CERT_FILE);
  12381. cli.set_connection_timeout(5);
  12382. // Note: Test certificate has CN="Common Name", not "localhost"
  12383. bool verify_result_cn = false;
  12384. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12385. verify_callback_called = true;
  12386. if (!ctx.cert) return false;
  12387. // Test 1: "Common Name" should match (our test server cert CN)
  12388. verify_result_cn = ctx.check_hostname("Common Name");
  12389. // Test 2: wrong hostname should not match
  12390. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12391. return true; // Accept for the purpose of this test
  12392. });
  12393. auto res = cli.Get("/test");
  12394. // The request may succeed or fail depending on cert configuration
  12395. // but the callback should have been called
  12396. ASSERT_TRUE(verify_callback_called)
  12397. << "Verify callback should have been called";
  12398. // CN="Common Name" should match our test certificate
  12399. //
  12400. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12401. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12402. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12403. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12404. // <openssl/base.h>, which is included transitively when
  12405. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12406. #if defined(OPENSSL_IS_BORINGSSL)
  12407. EXPECT_FALSE(verify_result_cn)
  12408. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12409. #else
  12410. EXPECT_TRUE(verify_result_cn)
  12411. << "verify_hostname should match 'Common Name' (certificate CN)";
  12412. #endif
  12413. // Wrong hostname should not match
  12414. EXPECT_FALSE(verify_result_wrong)
  12415. << "verify_hostname should not match 'wronghost.example.com'";
  12416. }
  12417. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12418. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12419. // X509_check_ip behavior and must hold for every backend.
  12420. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12421. using namespace httplib::tls;
  12422. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12423. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12424. ASSERT_TRUE(svr.is_valid());
  12425. svr.Get("/test", [](const Request &, Response &res) {
  12426. res.set_content("ok", "text/plain");
  12427. });
  12428. thread t([&]() { svr.listen(HOST, PORT); });
  12429. auto se = detail::scope_exit([&] {
  12430. svr.stop();
  12431. t.join();
  12432. });
  12433. svr.wait_until_ready();
  12434. bool verify_callback_called = false;
  12435. bool ip_matched_via_cn = true;
  12436. SSLClient cli(HOST, PORT);
  12437. cli.enable_server_certificate_verification(true);
  12438. cli.set_ca_cert_path(CA_CERT_FILE);
  12439. cli.set_connection_timeout(5);
  12440. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12441. verify_callback_called = true;
  12442. if (!ctx.cert) return false;
  12443. // The IP appears only in the CN, so it must NOT be accepted.
  12444. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12445. return true; // Accept for the purpose of this test
  12446. });
  12447. cli.Get("/test");
  12448. ASSERT_TRUE(verify_callback_called)
  12449. << "Verify callback should have been called";
  12450. EXPECT_FALSE(ip_matched_via_cn)
  12451. << "An IP host must not be authenticated via the certificate CN";
  12452. }
  12453. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12454. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12455. using namespace httplib::tls;
  12456. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12457. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12458. ASSERT_TRUE(svr.is_valid());
  12459. svr.Get("/test", [](const Request &, Response &res) {
  12460. res.set_content("ok", "text/plain");
  12461. });
  12462. thread t([&]() { svr.listen(HOST, PORT); });
  12463. auto se = detail::scope_exit([&] {
  12464. svr.stop();
  12465. t.join();
  12466. });
  12467. svr.wait_until_ready();
  12468. bool verify_callback_called = false;
  12469. bool san_matched = false;
  12470. bool wrong_ipv6_matched = true;
  12471. bool cn_ipv6_matched = true;
  12472. SSLClient cli(HOST, PORT);
  12473. cli.enable_server_certificate_verification(true);
  12474. cli.set_ca_cert_path(CA_CERT_FILE);
  12475. cli.set_connection_timeout(5);
  12476. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12477. verify_callback_called = true;
  12478. if (!ctx.cert) return false;
  12479. // Matches the IPv6 iPAddress SAN.
  12480. san_matched = ctx.check_hostname("2001:db8::1");
  12481. // A different IPv6 address must not match.
  12482. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12483. // "::1" lives only in the CN, so it must not be accepted.
  12484. cn_ipv6_matched = ctx.check_hostname("::1");
  12485. return true; // Accept for the purpose of this test
  12486. });
  12487. cli.Get("/test");
  12488. ASSERT_TRUE(verify_callback_called)
  12489. << "Verify callback should have been called";
  12490. EXPECT_TRUE(san_matched)
  12491. << "verify_hostname should match an IPv6 iPAddress SAN";
  12492. EXPECT_FALSE(wrong_ipv6_matched)
  12493. << "verify_hostname should not match a non-matching IPv6 address";
  12494. EXPECT_FALSE(cn_ipv6_matched)
  12495. << "An IPv6 host must not be authenticated via the certificate CN";
  12496. }
  12497. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  12498. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  12499. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  12500. using namespace httplib::tls;
  12501. // SANs: DNS:a.zz, IP:42.46.122.122
  12502. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12503. ASSERT_TRUE(svr.is_valid());
  12504. svr.Get("/test", [](const Request &, Response &res) {
  12505. res.set_content("ok", "text/plain");
  12506. });
  12507. auto port = svr.bind_to_any_port(HOST);
  12508. thread t([&]() { svr.listen_after_bind(); });
  12509. auto se = detail::scope_exit([&] {
  12510. svr.stop();
  12511. t.join();
  12512. });
  12513. svr.wait_until_ready();
  12514. bool verify_callback_called = false;
  12515. bool dns_san_matched = false;
  12516. bool ip_san_matched = false;
  12517. bool ip_matched_via_dns_san = true;
  12518. bool dns_matched_via_ip_san = true;
  12519. SSLClient cli(HOST, port);
  12520. cli.enable_server_certificate_verification(true);
  12521. cli.set_ca_cert_path(CA_CERT_FILE);
  12522. cli.set_connection_timeout(5);
  12523. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12524. verify_callback_called = true;
  12525. if (!ctx.cert) return false;
  12526. dns_san_matched = ctx.check_hostname("a.zz");
  12527. ip_san_matched = ctx.check_hostname("42.46.122.122");
  12528. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  12529. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  12530. return true; // Accept for the purpose of this test
  12531. });
  12532. cli.Get("/test");
  12533. ASSERT_TRUE(verify_callback_called)
  12534. << "Verify callback should have been called";
  12535. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  12536. EXPECT_TRUE(ip_san_matched)
  12537. << "verify_hostname should match an iPAddress SAN";
  12538. EXPECT_FALSE(ip_matched_via_dns_san)
  12539. << "An IP host must not be authenticated via a dNSName SAN";
  12540. EXPECT_FALSE(dns_matched_via_ip_san)
  12541. << "A DNS host must not be authenticated via an iPAddress SAN";
  12542. }
  12543. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  12544. // "www.*.example.test" names one host and not every host under example.test.
  12545. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  12546. using namespace httplib::tls;
  12547. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  12548. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  12549. ASSERT_TRUE(svr.is_valid());
  12550. svr.Get("/test", [](const Request &, Response &res) {
  12551. res.set_content("ok", "text/plain");
  12552. });
  12553. auto port = svr.bind_to_any_port(HOST);
  12554. thread t([&]() { svr.listen_after_bind(); });
  12555. auto se = detail::scope_exit([&] {
  12556. svr.stop();
  12557. t.join();
  12558. });
  12559. svr.wait_until_ready();
  12560. bool verify_callback_called = false;
  12561. bool leftmost_wildcard_matched = false;
  12562. bool wildcard_spanned_labels = true;
  12563. bool inner_wildcard_matched = true;
  12564. SSLClient cli(HOST, port);
  12565. cli.enable_server_certificate_verification(true);
  12566. cli.set_ca_cert_path(CA_CERT_FILE);
  12567. cli.set_connection_timeout(5);
  12568. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12569. verify_callback_called = true;
  12570. if (!ctx.cert) return false;
  12571. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  12572. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  12573. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  12574. return true; // Accept for the purpose of this test
  12575. });
  12576. cli.Get("/test");
  12577. ASSERT_TRUE(verify_callback_called)
  12578. << "Verify callback should have been called";
  12579. EXPECT_TRUE(leftmost_wildcard_matched)
  12580. << "A leftmost wildcard should match a single label";
  12581. EXPECT_FALSE(wildcard_spanned_labels)
  12582. << "A wildcard label must not match more than one label";
  12583. EXPECT_FALSE(inner_wildcard_matched)
  12584. << "A wildcard outside the leftmost label must not be honoured";
  12585. }
  12586. // sans() must report each SAN entry under its own type.
  12587. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  12588. using namespace httplib::tls;
  12589. // SANs: DNS:a.zz, IP:42.46.122.122
  12590. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12591. ASSERT_TRUE(svr.is_valid());
  12592. svr.Get("/test", [](const Request &, Response &res) {
  12593. res.set_content("ok", "text/plain");
  12594. });
  12595. auto port = svr.bind_to_any_port(HOST);
  12596. thread t([&]() { svr.listen_after_bind(); });
  12597. auto se = detail::scope_exit([&] {
  12598. svr.stop();
  12599. t.join();
  12600. });
  12601. svr.wait_until_ready();
  12602. bool verify_callback_called = false;
  12603. std::vector<SanEntry> sans;
  12604. SSLClient cli(HOST, port);
  12605. cli.enable_server_certificate_verification(true);
  12606. cli.set_ca_cert_path(CA_CERT_FILE);
  12607. cli.set_connection_timeout(5);
  12608. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12609. verify_callback_called = true;
  12610. if (!ctx.cert) return false;
  12611. sans = ctx.sans();
  12612. return true; // Accept for the purpose of this test
  12613. });
  12614. cli.Get("/test");
  12615. ASSERT_TRUE(verify_callback_called)
  12616. << "Verify callback should have been called";
  12617. auto has_san = [&](SanType type, const std::string &value) {
  12618. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  12619. return san.type == type && san.value == value;
  12620. });
  12621. };
  12622. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  12623. << "sans() should report the dNSName SAN";
  12624. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  12625. << "sans() should report the iPAddress SAN";
  12626. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  12627. << "sans() must not report the dNSName SAN as an address";
  12628. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  12629. << "sans() must not report the iPAddress SAN as a DNS name";
  12630. }
  12631. #endif
  12632. // mbedTLS-specific callback constructor test
  12633. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  12634. #ifdef CPPHTTPLIB_SSL_ENABLED
  12635. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  12636. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12637. ASSERT_TRUE(svr.is_valid());
  12638. // Set up a handler to verify client certificate is present
  12639. bool client_cert_verified = false;
  12640. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12641. // Verify that client certificate was provided
  12642. client_cert_verified = true;
  12643. res.set_content("success", "text/plain");
  12644. });
  12645. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12646. auto se = detail::scope_exit([&] {
  12647. svr.stop();
  12648. t.join();
  12649. ASSERT_FALSE(svr.is_running());
  12650. });
  12651. svr.wait_until_ready();
  12652. // Client with certificate
  12653. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12654. cli.enable_server_certificate_verification(false);
  12655. cli.set_connection_timeout(30);
  12656. auto res = cli.Get("/test");
  12657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12658. ASSERT_EQ(StatusCode::OK_200, res->status);
  12659. ASSERT_TRUE(client_cert_verified);
  12660. EXPECT_EQ("success", res->body);
  12661. }
  12662. #endif
  12663. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  12664. // backends
  12665. #ifdef CPPHTTPLIB_SSL_ENABLED
  12666. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  12667. using namespace httplib::tls;
  12668. // Test that when client CA cert file is provided,
  12669. // the server properly requests and validates client certificates
  12670. // Create a server with client authentication
  12671. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12672. ASSERT_TRUE(svr.is_valid());
  12673. bool handler_called = false;
  12674. svr.Get("/test", [&](const Request &req, Response &res) {
  12675. handler_called = true;
  12676. // Verify that a client certificate was provided
  12677. auto cert = req.peer_cert();
  12678. ASSERT_TRUE(static_cast<bool>(cert));
  12679. // Get the issuer name
  12680. std::string issuer_str = cert.issuer_name();
  12681. ASSERT_FALSE(issuer_str.empty());
  12682. // The client certificate should be issued by our test CA
  12683. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  12684. res.set_content("authenticated", "text/plain");
  12685. });
  12686. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12687. auto se = detail::scope_exit([&] {
  12688. svr.stop();
  12689. t.join();
  12690. ASSERT_FALSE(svr.is_running());
  12691. });
  12692. svr.wait_until_ready();
  12693. // Connect with a client certificate issued by the CA
  12694. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12695. cli.enable_server_certificate_verification(false);
  12696. cli.set_connection_timeout(30);
  12697. auto res = cli.Get("/test");
  12698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12699. ASSERT_EQ(StatusCode::OK_200, res->status);
  12700. ASSERT_TRUE(handler_called);
  12701. EXPECT_EQ("authenticated", res->body);
  12702. }
  12703. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12704. using namespace httplib::tls;
  12705. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12706. ASSERT_TRUE(svr.is_valid());
  12707. svr.Get("/test", [](const Request &, Response &res) {
  12708. res.set_content("ok", "text/plain");
  12709. });
  12710. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12711. auto se = detail::scope_exit([&] {
  12712. svr.stop();
  12713. t.join();
  12714. });
  12715. svr.wait_until_ready();
  12716. SSLClient cli(HOST, PORT);
  12717. cli.enable_server_certificate_verification(false);
  12718. cli.set_connection_timeout(30);
  12719. bool cert_checked = false;
  12720. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12721. if (ctx.cert) {
  12722. auto sans = ctx.sans();
  12723. // Test certificate may or may not have SANs - just verify the API
  12724. // works If SANs exist, verify the types are valid
  12725. for (const auto &san : sans) {
  12726. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  12727. san.type == SanType::EMAIL || san.type == SanType::URI ||
  12728. san.type == SanType::OTHER);
  12729. EXPECT_FALSE(san.value.empty());
  12730. }
  12731. cert_checked = true;
  12732. }
  12733. return true;
  12734. });
  12735. auto res = cli.Get("/test");
  12736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12737. EXPECT_TRUE(cert_checked);
  12738. }
  12739. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  12740. using namespace httplib::tls;
  12741. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12742. ASSERT_TRUE(svr.is_valid());
  12743. svr.Get("/test", [](const Request &, Response &res) {
  12744. res.set_content("ok", "text/plain");
  12745. });
  12746. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12747. auto se = detail::scope_exit([&] {
  12748. svr.stop();
  12749. t.join();
  12750. });
  12751. svr.wait_until_ready();
  12752. SSLClient cli(HOST, PORT);
  12753. cli.enable_server_certificate_verification(false);
  12754. cli.set_connection_timeout(30);
  12755. bool validity_checked = false;
  12756. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12757. if (ctx.cert) {
  12758. time_t not_before = 0, not_after = 0;
  12759. bool result = ctx.validity(not_before, not_after);
  12760. EXPECT_TRUE(result);
  12761. // Verify that not_before < now < not_after for a valid cert
  12762. time_t now = time(nullptr);
  12763. EXPECT_LT(not_before, now);
  12764. EXPECT_GT(not_after, now);
  12765. validity_checked = true;
  12766. }
  12767. return true;
  12768. });
  12769. auto res = cli.Get("/test");
  12770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12771. EXPECT_TRUE(validity_checked);
  12772. }
  12773. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  12774. using namespace httplib::tls;
  12775. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12776. ASSERT_TRUE(svr.is_valid());
  12777. svr.Get("/test", [](const Request &, Response &res) {
  12778. res.set_content("ok", "text/plain");
  12779. });
  12780. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12781. auto se = detail::scope_exit([&] {
  12782. svr.stop();
  12783. t.join();
  12784. });
  12785. svr.wait_until_ready();
  12786. SSLClient cli(HOST, PORT);
  12787. cli.enable_server_certificate_verification(false);
  12788. cli.set_connection_timeout(30);
  12789. bool serial_checked = false;
  12790. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12791. if (ctx.cert) {
  12792. std::string serial = ctx.serial();
  12793. EXPECT_FALSE(serial.empty());
  12794. // Serial should be a hex string
  12795. for (char c : serial) {
  12796. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  12797. (c >= 'a' && c <= 'f'));
  12798. }
  12799. serial_checked = true;
  12800. }
  12801. return true;
  12802. });
  12803. auto res = cli.Get("/test");
  12804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12805. EXPECT_TRUE(serial_checked);
  12806. }
  12807. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  12808. // Test 1: Valid CA file - no error should be recorded
  12809. {
  12810. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12811. CLIENT_CA_CERT_FILE);
  12812. ASSERT_TRUE(svr.is_valid());
  12813. // With valid setup, last_ssl_error should be 0
  12814. EXPECT_EQ(0, svr.ssl_last_error());
  12815. }
  12816. // Test 2: Invalid CA file content
  12817. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  12818. {
  12819. // Create a temporary file with completely invalid content
  12820. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  12821. {
  12822. std::ofstream ofs(temp_invalid_ca);
  12823. ofs << "This is not a certificate file at all\n";
  12824. ofs << "Just plain text content\n";
  12825. }
  12826. // Create server with invalid CA file
  12827. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  12828. // Clean up temporary file
  12829. std::remove(temp_invalid_ca);
  12830. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  12831. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  12832. // Note: SSL_CTX_load_verify_locations typically fails first,
  12833. // but our error handling code path is still exercised
  12834. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  12835. }
  12836. }
  12837. TEST(VerifyCallbackTest, VerifyContextFields) {
  12838. using namespace httplib::tls;
  12839. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12840. ASSERT_TRUE(svr.is_valid());
  12841. svr.Get("/test", [](const Request &, Response &res) {
  12842. res.set_content("ok", "text/plain");
  12843. });
  12844. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12845. auto se = detail::scope_exit([&] {
  12846. svr.stop();
  12847. t.join();
  12848. });
  12849. svr.wait_until_ready();
  12850. SSLClient cli(HOST, PORT);
  12851. cli.enable_server_certificate_verification(false);
  12852. cli.set_connection_timeout(30);
  12853. int callback_count = 0;
  12854. bool saw_leaf_cert = false;
  12855. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12856. if (ctx.cert) {
  12857. callback_count++;
  12858. // We should see at least one certificate (the leaf)
  12859. std::string cn = ctx.subject_cn();
  12860. if (!cn.empty()) { saw_leaf_cert = true; }
  12861. // Verify context fields are populated
  12862. EXPECT_NE(ctx.session, nullptr);
  12863. EXPECT_GE(ctx.depth, 0);
  12864. }
  12865. return true;
  12866. });
  12867. auto res = cli.Get("/test");
  12868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12869. EXPECT_GT(callback_count, 0);
  12870. EXPECT_TRUE(saw_leaf_cert);
  12871. }
  12872. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  12873. using httplib::tls::TlsError;
  12874. // Test that verify_error_to_string returns empty for success
  12875. std::string success_str = TlsError::verify_error_to_string(0);
  12876. EXPECT_TRUE(success_str.empty());
  12877. // Test that verify_error_to_string returns non-empty for error codes
  12878. // Using a common error code (certificate expired)
  12879. std::string error_str =
  12880. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  12881. EXPECT_FALSE(error_str.empty());
  12882. }
  12883. TEST(SessionVerifierTest, CertificateAccepted) {
  12884. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12885. ASSERT_TRUE(svr.is_valid());
  12886. svr.Get("/test", [](const Request &, Response &res) {
  12887. res.set_content("ok", "text/plain");
  12888. });
  12889. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12890. auto se = detail::scope_exit([&] {
  12891. svr.stop();
  12892. t.join();
  12893. });
  12894. svr.wait_until_ready();
  12895. SSLClient cli(HOST, PORT);
  12896. cli.enable_server_certificate_verification(false);
  12897. cli.set_connection_timeout(30);
  12898. bool callback_called = false;
  12899. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12900. EXPECT_NE(session, nullptr);
  12901. callback_called = true;
  12902. return SSLVerifierResponse::CertificateAccepted;
  12903. });
  12904. auto res = cli.Get("/test");
  12905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12906. EXPECT_EQ(200, res->status);
  12907. EXPECT_TRUE(callback_called);
  12908. }
  12909. TEST(SessionVerifierTest, CertificateRejected) {
  12910. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12911. ASSERT_TRUE(svr.is_valid());
  12912. svr.Get("/test", [](const Request &, Response &res) {
  12913. res.set_content("ok", "text/plain");
  12914. });
  12915. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12916. auto se = detail::scope_exit([&] {
  12917. svr.stop();
  12918. t.join();
  12919. });
  12920. svr.wait_until_ready();
  12921. SSLClient cli(HOST, PORT);
  12922. cli.enable_server_certificate_verification(false);
  12923. cli.set_connection_timeout(30);
  12924. bool callback_called = false;
  12925. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12926. EXPECT_NE(session, nullptr);
  12927. callback_called = true;
  12928. return SSLVerifierResponse::CertificateRejected;
  12929. });
  12930. auto res = cli.Get("/test");
  12931. EXPECT_FALSE(res);
  12932. EXPECT_TRUE(callback_called);
  12933. }
  12934. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  12935. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12936. ASSERT_TRUE(svr.is_valid());
  12937. svr.Get("/test", [](const Request &, Response &res) {
  12938. res.set_content("ok", "text/plain");
  12939. });
  12940. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12941. auto se = detail::scope_exit([&] {
  12942. svr.stop();
  12943. t.join();
  12944. });
  12945. svr.wait_until_ready();
  12946. // NoDecisionMade with verification disabled should succeed (no default check)
  12947. SSLClient cli(HOST, PORT);
  12948. cli.enable_server_certificate_verification(false);
  12949. cli.set_connection_timeout(30);
  12950. bool callback_called = false;
  12951. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12952. EXPECT_NE(session, nullptr);
  12953. callback_called = true;
  12954. return SSLVerifierResponse::NoDecisionMade;
  12955. });
  12956. auto res = cli.Get("/test");
  12957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12958. EXPECT_EQ(200, res->status);
  12959. EXPECT_TRUE(callback_called);
  12960. }
  12961. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  12962. SSLServer svr(SERVER_CERT_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. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12968. auto se = detail::scope_exit([&] {
  12969. svr.stop();
  12970. t.join();
  12971. });
  12972. svr.wait_until_ready();
  12973. // NoDecisionMade with verification enabled should fail (self-signed cert).
  12974. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  12975. // so we only check that the request fails, not whether the callback was
  12976. // called.
  12977. SSLClient cli(HOST, PORT);
  12978. cli.enable_server_certificate_verification(true);
  12979. cli.set_connection_timeout(30);
  12980. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12981. EXPECT_NE(session, nullptr);
  12982. return SSLVerifierResponse::NoDecisionMade;
  12983. });
  12984. auto res = cli.Get("/test");
  12985. EXPECT_FALSE(res);
  12986. }
  12987. TEST(SSLClientServerTest, ClientCAListFromPem) {
  12988. // Test SSL server using PemMemory constructor with client CA certificates
  12989. // Read PEM files
  12990. std::string server_cert_pem, server_key_pem, client_ca_pem;
  12991. read_file(SERVER_CERT_FILE, server_cert_pem);
  12992. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12993. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12994. // Create SSLServer with PemMemory constructor including client CA
  12995. SSLServer::PemMemory server_pem = {
  12996. server_cert_pem.c_str(),
  12997. server_cert_pem.size(),
  12998. server_key_pem.c_str(),
  12999. server_key_pem.size(),
  13000. client_ca_pem.c_str(),
  13001. client_ca_pem.size(),
  13002. nullptr // no password for server key
  13003. };
  13004. SSLServer svr(server_pem);
  13005. ASSERT_TRUE(svr.is_valid());
  13006. // No SSL error should be recorded for valid setup
  13007. EXPECT_EQ(0, svr.ssl_last_error());
  13008. // Set up server endpoints
  13009. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13010. res.set_content("ok", "text/plain");
  13011. });
  13012. // Start server in a thread
  13013. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13014. svr.wait_until_ready();
  13015. // Connect with client certificate (using constructor with paths)
  13016. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13017. cli.enable_server_certificate_verification(false);
  13018. auto res = cli.Get("/test-pem-ca");
  13019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13020. EXPECT_EQ(200, res->status);
  13021. EXPECT_EQ("ok", res->body);
  13022. svr.stop();
  13023. server_thread.join();
  13024. }
  13025. #endif
  13026. #ifdef _WIN32
  13027. TEST(CleanupTest, WSACleanup) {
  13028. int ret = WSACleanup();
  13029. ASSERT_EQ(0, ret);
  13030. }
  13031. #endif
  13032. #ifndef CPPHTTPLIB_SSL_ENABLED
  13033. TEST(NoSSLSupport, SimpleInterface) {
  13034. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13035. }
  13036. #endif
  13037. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13038. TEST(InvalidScheme, SimpleInterface) {
  13039. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13040. }
  13041. #endif
  13042. TEST(NoScheme, SimpleInterface) {
  13043. Client cli("yahoo.com:80");
  13044. ASSERT_TRUE(cli.is_valid());
  13045. }
  13046. TEST(SendAPI, SimpleInterface_Online) {
  13047. Client cli("http://yahoo.com");
  13048. Request req;
  13049. req.method = "GET";
  13050. req.path = "/";
  13051. auto res = cli.send(req);
  13052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13053. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13054. }
  13055. TEST(SendAPI, WithParamsInRequest) {
  13056. Server svr;
  13057. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13058. EXPECT_TRUE(req.has_param("test"));
  13059. EXPECT_EQ("test_value", req.get_param_value("test"));
  13060. });
  13061. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13062. auto se = detail::scope_exit([&] {
  13063. svr.stop();
  13064. t.join();
  13065. ASSERT_FALSE(svr.is_running());
  13066. });
  13067. svr.wait_until_ready();
  13068. Client cli(HOST, PORT);
  13069. {
  13070. Request req;
  13071. req.method = "GET";
  13072. req.path = "/";
  13073. req.params.emplace("test", "test_value");
  13074. auto res = cli.send(req);
  13075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13076. }
  13077. {
  13078. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13080. }
  13081. }
  13082. TEST(ClientImplMethods, GetSocketTest) {
  13083. httplib::Server svr;
  13084. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13085. res.status = StatusCode::OK_200;
  13086. });
  13087. auto port = svr.bind_to_any_port("127.0.0.1");
  13088. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13089. auto se = detail::scope_exit([&] {
  13090. svr.stop();
  13091. thread.join();
  13092. ASSERT_FALSE(svr.is_running());
  13093. });
  13094. svr.wait_until_ready();
  13095. {
  13096. httplib::Client cli("127.0.0.1", port);
  13097. cli.set_keep_alive(true);
  13098. // Use the behavior of cpp-httplib of opening the connection
  13099. // only when the first request happens. If that changes,
  13100. // this test would be obsolete.
  13101. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13102. // This also implicitly tests the server. But other tests would fail much
  13103. // earlier than this one to be considered.
  13104. auto res = cli.Get("/");
  13105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13106. EXPECT_EQ(StatusCode::OK_200, res->status);
  13107. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13108. }
  13109. }
  13110. #ifdef CPPHTTPLIB_SSL_ENABLED
  13111. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13112. Client cli("http://yahoo.com");
  13113. auto res = cli.Get("/");
  13114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13115. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13116. cli.set_follow_location(true);
  13117. res = cli.Get("/");
  13118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13119. EXPECT_EQ(StatusCode::OK_200, res->status);
  13120. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13121. }
  13122. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13123. Client cli("https://yahoo.com");
  13124. auto res = cli.Get("/");
  13125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13126. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13127. cli.set_follow_location(true);
  13128. res = cli.Get("/");
  13129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13130. EXPECT_EQ(StatusCode::OK_200, res->status);
  13131. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13132. }
  13133. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13134. Client cli("https://yahoo.com");
  13135. auto res = cli.Get("/");
  13136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13137. ASSERT_FALSE(!res);
  13138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13139. ASSERT_FALSE(res == nullptr);
  13140. ASSERT_TRUE(res != nullptr);
  13141. EXPECT_EQ(Error::Success, res.error());
  13142. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13143. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13144. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13145. cli.set_follow_location(true);
  13146. res = cli.Get("/");
  13147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13148. EXPECT_EQ(Error::Success, res.error());
  13149. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13150. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13151. EXPECT_EQ(StatusCode::OK_200, res->status);
  13152. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13153. }
  13154. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13155. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13156. Client cli("https://cdnjs.cloudflare.com");
  13157. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13158. Headers{{"Accept-Encoding", "br"}});
  13159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13160. EXPECT_EQ(StatusCode::OK_200, res->status);
  13161. EXPECT_EQ(287630U, res->body.size());
  13162. EXPECT_EQ("application/javascript; charset=utf-8",
  13163. res->get_header_value("Content-Type"));
  13164. }
  13165. #endif
  13166. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13167. #undef REDIR_HOST // Silence compiler warning
  13168. #define REDIR_HOST "https://httpbingo.org"
  13169. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13170. Client cli(REDIR_HOST);
  13171. cli.set_follow_location(true);
  13172. auto res =
  13173. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13175. EXPECT_EQ(StatusCode::OK_200, res->status);
  13176. }
  13177. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13178. Client cli(REDIR_HOST);
  13179. cli.set_follow_location(true);
  13180. Params params;
  13181. params.emplace("url", "http://example.com");
  13182. params.emplace("status_code", "302");
  13183. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13185. EXPECT_EQ(StatusCode::OK_200, res->status);
  13186. }
  13187. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13188. Client cli(REDIR_HOST);
  13189. cli.set_follow_location(true);
  13190. Params params;
  13191. params.emplace("url", "http://example.com");
  13192. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13194. EXPECT_EQ(StatusCode::OK_200, res->status);
  13195. }
  13196. TEST(HttpToHttpsRedirectTest, CertFile) {
  13197. auto ssl_port = PORT + 1;
  13198. Server svr;
  13199. ASSERT_TRUE(svr.is_valid());
  13200. svr.Get("/index", [&](const Request &, Response &res) {
  13201. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13202. "/index");
  13203. svr.stop();
  13204. });
  13205. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13206. ASSERT_TRUE(ssl_svr.is_valid());
  13207. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13208. res.set_content("test", "text/plain");
  13209. ssl_svr.stop();
  13210. });
  13211. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13212. thread t2 =
  13213. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13214. auto se = detail::scope_exit([&] {
  13215. t2.join();
  13216. t.join();
  13217. ASSERT_FALSE(svr.is_running());
  13218. });
  13219. svr.wait_until_ready();
  13220. ssl_svr.wait_until_ready();
  13221. Client cli("127.0.0.1", PORT);
  13222. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13223. cli.enable_server_certificate_verification(true);
  13224. cli.set_follow_location(true);
  13225. cli.set_connection_timeout(30);
  13226. auto res = cli.Get("/index");
  13227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13228. ASSERT_EQ(StatusCode::OK_200, res->status);
  13229. }
  13230. TEST(SSLClientRedirectTest, CertFile) {
  13231. auto ssl_port = PORT + 1;
  13232. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13233. ASSERT_TRUE(ssl_svr1.is_valid());
  13234. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13235. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13236. "/index");
  13237. ssl_svr1.stop();
  13238. });
  13239. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13240. ASSERT_TRUE(ssl_svr2.is_valid());
  13241. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13242. res.set_content("test", "text/plain");
  13243. ssl_svr2.stop();
  13244. });
  13245. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13246. thread t2 =
  13247. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13248. auto se = detail::scope_exit([&] {
  13249. t2.join();
  13250. t.join();
  13251. ASSERT_FALSE(ssl_svr1.is_running());
  13252. });
  13253. ssl_svr1.wait_until_ready();
  13254. ssl_svr2.wait_until_ready();
  13255. SSLClient cli("127.0.0.1", PORT);
  13256. std::string cert;
  13257. read_file(SERVER_CERT2_FILE, cert);
  13258. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13259. cli.enable_server_certificate_verification(true);
  13260. cli.set_follow_location(true);
  13261. cli.set_connection_timeout(30);
  13262. auto res = cli.Get("/index");
  13263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13264. ASSERT_EQ(StatusCode::OK_200, res->status);
  13265. }
  13266. #endif
  13267. #ifdef CPPHTTPLIB_SSL_ENABLED
  13268. // Test that set_ca_cert_store() skips system certs (consistent with
  13269. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13270. // should be trusted - system certs should NOT be loaded.
  13271. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  13272. // Load a specific cert that is NOT a system CA cert
  13273. std::string cert;
  13274. read_file(SERVER_CERT2_FILE, cert);
  13275. SSLClient cli("google.com");
  13276. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13277. cli.enable_server_certificate_verification(true);
  13278. // This should FAIL because:
  13279. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  13280. // 2. System certs should NOT be loaded when custom store is set
  13281. // If system certs WERE loaded, this would succeed
  13282. auto res = cli.Get("/");
  13283. ASSERT_FALSE(res);
  13284. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13285. }
  13286. // Same as above, but through the native store handle path. Regression test:
  13287. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  13288. // merged system certs into the user-provided store.
  13289. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  13290. std::string cert;
  13291. read_file(SERVER_CERT2_FILE, cert);
  13292. SSLClient cli("google.com");
  13293. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13294. cli.enable_server_certificate_verification(true);
  13295. auto res = cli.Get("/");
  13296. ASSERT_FALSE(res);
  13297. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13298. }
  13299. // A custom store set via the native handle must still verify a server whose
  13300. // cert it does contain.
  13301. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  13302. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13303. ASSERT_TRUE(svr.is_valid());
  13304. svr.Get("/test", [&](const Request &, Response &res) {
  13305. res.set_content("test", "text/plain");
  13306. });
  13307. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13308. auto se = detail::scope_exit([&] {
  13309. svr.stop();
  13310. t.join();
  13311. ASSERT_FALSE(svr.is_running());
  13312. });
  13313. svr.wait_until_ready();
  13314. SSLClient cli("127.0.0.1", PORT);
  13315. std::string cert;
  13316. read_file(SERVER_CERT2_FILE, cert);
  13317. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13318. cli.enable_server_certificate_verification(true);
  13319. cli.set_connection_timeout(30);
  13320. auto res = cli.Get("/test");
  13321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13322. ASSERT_EQ(StatusCode::OK_200, res->status);
  13323. }
  13324. // CA certs loaded through the universal Client must be transferred to the
  13325. // client created internally for following an HTTPS redirect. Regression test:
  13326. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  13327. // the CA data for redirect transfer.
  13328. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  13329. auto ssl_port = PORT + 1;
  13330. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13331. ASSERT_TRUE(ssl_svr1.is_valid());
  13332. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13333. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13334. "/index");
  13335. });
  13336. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13337. ASSERT_TRUE(ssl_svr2.is_valid());
  13338. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13339. res.set_content("test", "text/plain");
  13340. });
  13341. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13342. thread t2 =
  13343. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13344. auto se = detail::scope_exit([&] {
  13345. ssl_svr2.stop();
  13346. ssl_svr1.stop();
  13347. t2.join();
  13348. t.join();
  13349. ASSERT_FALSE(ssl_svr1.is_running());
  13350. });
  13351. ssl_svr1.wait_until_ready();
  13352. ssl_svr2.wait_until_ready();
  13353. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13354. std::string cert;
  13355. read_file(SERVER_CERT2_FILE, cert);
  13356. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13357. cli.enable_server_certificate_verification(true);
  13358. cli.set_follow_location(true);
  13359. cli.set_connection_timeout(30);
  13360. auto res = cli.Get("/index");
  13361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13362. ASSERT_EQ(StatusCode::OK_200, res->status);
  13363. }
  13364. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  13365. // so a host signed by a system CA verifies even though a custom CA is set
  13366. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  13367. std::string cert;
  13368. read_file(SERVER_CERT2_FILE, cert);
  13369. SSLClient cli("google.com");
  13370. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13371. cli.enable_system_ca(true);
  13372. cli.enable_server_certificate_verification(true);
  13373. auto res = cli.Get("/");
  13374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13375. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13376. }
  13377. // The custom CA remains effective when combined with the system CA
  13378. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  13379. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13380. ASSERT_TRUE(svr.is_valid());
  13381. svr.Get("/test", [&](const Request &, Response &res) {
  13382. res.set_content("test", "text/plain");
  13383. });
  13384. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13385. auto se = detail::scope_exit([&] {
  13386. svr.stop();
  13387. t.join();
  13388. ASSERT_FALSE(svr.is_running());
  13389. });
  13390. svr.wait_until_ready();
  13391. SSLClient cli("127.0.0.1", PORT);
  13392. std::string cert;
  13393. read_file(SERVER_CERT2_FILE, cert);
  13394. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13395. cli.enable_system_ca(true);
  13396. cli.enable_server_certificate_verification(true);
  13397. cli.set_connection_timeout(30);
  13398. auto res = cli.Get("/test");
  13399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13400. ASSERT_EQ(StatusCode::OK_200, res->status);
  13401. }
  13402. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  13403. // skip chain verification entirely (only the certificate identity was
  13404. // checked), so a server presenting an untrusted certificate with a matching
  13405. // IP SAN was accepted. The chain must be validated for IP hosts too.
  13406. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  13407. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13408. ASSERT_TRUE(svr.is_valid());
  13409. svr.Get("/test", [&](const Request &, Response &res) {
  13410. res.set_content("test", "text/plain");
  13411. });
  13412. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13413. auto se = detail::scope_exit([&] {
  13414. svr.stop();
  13415. t.join();
  13416. ASSERT_FALSE(svr.is_running());
  13417. });
  13418. svr.wait_until_ready();
  13419. SSLClient cli("127.0.0.1", PORT);
  13420. std::string cert;
  13421. // A trusted CA that did not sign the server certificate. The server cert
  13422. // (cert2) carries the matching IP SAN, so only chain validation can reject
  13423. // this connection.
  13424. read_file(CLIENT_CA_CERT_FILE, cert);
  13425. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13426. cli.enable_server_certificate_verification(true);
  13427. cli.set_connection_timeout(30);
  13428. auto res = cli.Get("/test");
  13429. ASSERT_FALSE(res);
  13430. }
  13431. // enable_system_ca(false) prevents system CA loading entirely
  13432. TEST(SSLClientTest, DisableSystemCa_Online) {
  13433. SSLClient cli("google.com");
  13434. cli.enable_system_ca(false);
  13435. cli.enable_server_certificate_verification(true);
  13436. auto res = cli.Get("/");
  13437. ASSERT_FALSE(res);
  13438. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  13439. // itself when the CA chain is empty
  13440. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13441. res.error() == Error::SSLConnection);
  13442. }
  13443. // The universal Client forwards enable_system_ca()
  13444. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  13445. std::string cert;
  13446. read_file(SERVER_CERT2_FILE, cert);
  13447. Client cli("https://google.com");
  13448. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13449. cli.enable_system_ca(true);
  13450. cli.enable_server_certificate_verification(true);
  13451. auto res = cli.Get("/");
  13452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13453. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13454. }
  13455. // The system CA policy must carry over to the client created internally for
  13456. // following a cross-host HTTPS redirect
  13457. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  13458. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13459. ASSERT_TRUE(svr.is_valid());
  13460. svr.Get("/index", [&](const Request &, Response &res) {
  13461. res.set_redirect("https://www.google.com/");
  13462. });
  13463. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13464. auto se = detail::scope_exit([&] {
  13465. svr.stop();
  13466. t.join();
  13467. ASSERT_FALSE(svr.is_running());
  13468. });
  13469. svr.wait_until_ready();
  13470. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13471. std::string cert;
  13472. read_file(SERVER_CERT2_FILE, cert);
  13473. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13474. cli.enable_system_ca(true);
  13475. cli.enable_server_certificate_verification(true);
  13476. cli.set_follow_location(true);
  13477. cli.set_connection_timeout(30);
  13478. // Receiving any response proves the redirect client completed the TLS
  13479. // handshake with a system-CA-signed host
  13480. auto res = cli.Get("/index");
  13481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13482. }
  13483. TEST(MultipartFormDataTest, LargeData) {
  13484. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13485. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  13486. const ContentReader &content_reader) {
  13487. if (req.is_multipart_form_data()) {
  13488. std::vector<FormData> items;
  13489. content_reader(
  13490. [&](const FormData &file) {
  13491. items.push_back(file);
  13492. return true;
  13493. },
  13494. [&](const char *data, size_t data_length) {
  13495. items.back().content.append(data, data_length);
  13496. return true;
  13497. });
  13498. EXPECT_TRUE(std::string(items[0].name) == "document");
  13499. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13500. EXPECT_TRUE(items[0].filename == "2MB_data");
  13501. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13502. EXPECT_TRUE(items[1].name == "hello");
  13503. EXPECT_TRUE(items[1].content == "world");
  13504. EXPECT_TRUE(items[1].filename == "");
  13505. EXPECT_TRUE(items[1].content_type == "");
  13506. } else {
  13507. std::string body;
  13508. content_reader([&](const char *data, size_t data_length) {
  13509. body.append(data, data_length);
  13510. return true;
  13511. });
  13512. }
  13513. });
  13514. auto port = svr.bind_to_any_port(HOST);
  13515. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13516. auto se = detail::scope_exit([&] {
  13517. svr.stop();
  13518. t.join();
  13519. ASSERT_FALSE(svr.is_running());
  13520. });
  13521. svr.wait_until_ready();
  13522. {
  13523. std::string data(1024 * 1024 * 2, '.');
  13524. std::stringstream buffer;
  13525. buffer << data;
  13526. SSLClient cli(HOST, port);
  13527. cli.enable_server_certificate_verification(false);
  13528. UploadFormDataItems items{
  13529. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13530. {"hello", "world", "", ""},
  13531. };
  13532. auto res = cli.Post("/post", items);
  13533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13534. ASSERT_EQ(StatusCode::OK_200, res->status);
  13535. }
  13536. }
  13537. TEST(MultipartFormDataTest, DataProviderItems) {
  13538. std::random_device seed_gen;
  13539. std::mt19937 random(seed_gen());
  13540. std::string rand1;
  13541. rand1.resize(1000);
  13542. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  13543. std::string rand2;
  13544. rand2.resize(3000);
  13545. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  13546. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13547. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  13548. const ContentReader &content_reader) {
  13549. ASSERT_FALSE(req.is_multipart_form_data());
  13550. std::string body;
  13551. content_reader([&](const char *data, size_t data_length) {
  13552. body.append(data, data_length);
  13553. return true;
  13554. });
  13555. EXPECT_EQ(body, "");
  13556. });
  13557. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  13558. const ContentReader &content_reader) {
  13559. ASSERT_TRUE(req.is_multipart_form_data());
  13560. std::vector<FormData> items;
  13561. content_reader(
  13562. [&](const FormData &file) {
  13563. items.push_back(file);
  13564. return true;
  13565. },
  13566. [&](const char *data, size_t data_length) {
  13567. items.back().content.append(data, data_length);
  13568. return true;
  13569. });
  13570. ASSERT_TRUE(items.size() == 2);
  13571. EXPECT_EQ(std::string(items[0].name), "name1");
  13572. EXPECT_EQ(items[0].content, "Testing123");
  13573. EXPECT_EQ(items[0].filename, "filename1");
  13574. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13575. EXPECT_EQ(items[1].name, "name2");
  13576. EXPECT_EQ(items[1].content, "Testing456");
  13577. EXPECT_EQ(items[1].filename, "");
  13578. EXPECT_EQ(items[1].content_type, "");
  13579. });
  13580. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  13581. const ContentReader &content_reader) {
  13582. ASSERT_TRUE(req.is_multipart_form_data());
  13583. std::vector<FormData> items;
  13584. content_reader(
  13585. [&](const FormData &file) {
  13586. items.push_back(file);
  13587. return true;
  13588. },
  13589. [&](const char *data, size_t data_length) {
  13590. items.back().content.append(data, data_length);
  13591. return true;
  13592. });
  13593. ASSERT_TRUE(items.size() == 2);
  13594. EXPECT_EQ(items[0].name, "name3");
  13595. EXPECT_EQ(items[0].content, rand1);
  13596. EXPECT_EQ(items[0].filename, "filename3");
  13597. EXPECT_EQ(items[0].content_type, "");
  13598. EXPECT_EQ(items[1].name, "name4");
  13599. EXPECT_EQ(items[1].content, rand2);
  13600. EXPECT_EQ(items[1].filename, "filename4");
  13601. EXPECT_EQ(items[1].content_type, "");
  13602. });
  13603. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  13604. const ContentReader &content_reader) {
  13605. ASSERT_TRUE(req.is_multipart_form_data());
  13606. std::vector<FormData> items;
  13607. content_reader(
  13608. [&](const FormData &file) {
  13609. items.push_back(file);
  13610. return true;
  13611. },
  13612. [&](const char *data, size_t data_length) {
  13613. items.back().content.append(data, data_length);
  13614. return true;
  13615. });
  13616. ASSERT_TRUE(items.size() == 4);
  13617. EXPECT_EQ(std::string(items[0].name), "name1");
  13618. EXPECT_EQ(items[0].content, "Testing123");
  13619. EXPECT_EQ(items[0].filename, "filename1");
  13620. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13621. EXPECT_EQ(items[1].name, "name2");
  13622. EXPECT_EQ(items[1].content, "Testing456");
  13623. EXPECT_EQ(items[1].filename, "");
  13624. EXPECT_EQ(items[1].content_type, "");
  13625. EXPECT_EQ(items[2].name, "name3");
  13626. EXPECT_EQ(items[2].content, rand1);
  13627. EXPECT_EQ(items[2].filename, "filename3");
  13628. EXPECT_EQ(items[2].content_type, "");
  13629. EXPECT_EQ(items[3].name, "name4");
  13630. EXPECT_EQ(items[3].content, rand2);
  13631. EXPECT_EQ(items[3].filename, "filename4");
  13632. EXPECT_EQ(items[3].content_type, "");
  13633. });
  13634. auto port = svr.bind_to_any_port("localhost");
  13635. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13636. auto se = detail::scope_exit([&] {
  13637. svr.stop();
  13638. t.join();
  13639. ASSERT_FALSE(svr.is_running());
  13640. });
  13641. svr.wait_until_ready();
  13642. {
  13643. SSLClient cli("localhost", port);
  13644. cli.enable_server_certificate_verification(false);
  13645. UploadFormDataItems items{
  13646. {"name1", "Testing123", "filename1", "application/octet-stream"},
  13647. {"name2", "Testing456", "", ""}, // not a file
  13648. };
  13649. {
  13650. auto res = cli.Post("/post-none", {}, {}, {});
  13651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13652. ASSERT_EQ(StatusCode::OK_200, res->status);
  13653. }
  13654. FormDataProviderItems providers;
  13655. {
  13656. auto res =
  13657. cli.Post("/post-items", {}, items, providers); // empty providers
  13658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13659. ASSERT_EQ(StatusCode::OK_200, res->status);
  13660. }
  13661. providers.push_back({"name3",
  13662. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13663. // test the offset is given correctly at each step
  13664. if (!offset)
  13665. sink.os.write(rand1.data(), 30);
  13666. else if (offset == 30)
  13667. sink.os.write(rand1.data() + 30, 300);
  13668. else if (offset == 330)
  13669. sink.os.write(rand1.data() + 330, 670);
  13670. else if (offset == rand1.size())
  13671. sink.done();
  13672. return true;
  13673. },
  13674. "filename3",
  13675. {}});
  13676. providers.push_back({"name4",
  13677. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13678. // test the offset is given correctly at each step
  13679. if (!offset)
  13680. sink.os.write(rand2.data(), 2000);
  13681. else if (offset == 2000)
  13682. sink.os.write(rand2.data() + 2000, 1);
  13683. else if (offset == 2001)
  13684. sink.os.write(rand2.data() + 2001, 999);
  13685. else if (offset == rand2.size())
  13686. sink.done();
  13687. return true;
  13688. },
  13689. "filename4",
  13690. {}});
  13691. {
  13692. auto res = cli.Post("/post-providers", {}, {}, providers);
  13693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13694. ASSERT_EQ(StatusCode::OK_200, res->status);
  13695. }
  13696. {
  13697. auto res = cli.Post("/post-both", {}, items, providers);
  13698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13699. ASSERT_EQ(StatusCode::OK_200, res->status);
  13700. }
  13701. }
  13702. }
  13703. TEST(MultipartFormDataTest, BadHeader) {
  13704. Server svr;
  13705. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13706. res.set_content("ok", "text/plain");
  13707. });
  13708. thread t = thread([&] { svr.listen(HOST, PORT); });
  13709. auto se = detail::scope_exit([&] {
  13710. svr.stop();
  13711. t.join();
  13712. ASSERT_FALSE(svr.is_running());
  13713. });
  13714. svr.wait_until_ready();
  13715. const std::string body =
  13716. "This is the preamble. It is to be ignored, though it\r\n"
  13717. "is a handy place for composition agents to include an\r\n"
  13718. "explanatory note to non-MIME conformant readers.\r\n"
  13719. "\r\n"
  13720. "\r\n"
  13721. "--simple boundary\r\n"
  13722. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13723. ": BAD...\r\n"
  13724. "\r\n"
  13725. "value1\r\n"
  13726. "--simple boundary\r\n"
  13727. "Content-Disposition: form-data; name=\"field2\"; "
  13728. "filename=\"example.txt\"\r\n"
  13729. "\r\n"
  13730. "value2\r\n"
  13731. "--simple boundary--\r\n"
  13732. "This is the epilogue. It is also to be ignored.\r\n";
  13733. std::string content_type =
  13734. R"(multipart/form-data; boundary="simple boundary")";
  13735. Client cli(HOST, PORT);
  13736. auto res = cli.Post("/post", body, content_type.c_str());
  13737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13738. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13739. }
  13740. TEST(MultipartFormDataTest, WithPreamble) {
  13741. Server svr;
  13742. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13743. res.set_content("ok", "text/plain");
  13744. });
  13745. thread t = thread([&] { svr.listen(HOST, PORT); });
  13746. auto se = detail::scope_exit([&] {
  13747. svr.stop();
  13748. t.join();
  13749. ASSERT_FALSE(svr.is_running());
  13750. });
  13751. svr.wait_until_ready();
  13752. const std::string body =
  13753. "This is the preamble. It is to be ignored, though it\r\n"
  13754. "is a handy place for composition agents to include an\r\n"
  13755. "explanatory note to non-MIME conformant readers.\r\n"
  13756. "\r\n"
  13757. "\r\n"
  13758. "--simple boundary\r\n"
  13759. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13760. "\r\n"
  13761. "value1\r\n"
  13762. "--simple boundary\r\n"
  13763. "Content-Disposition: form-data; name=\"field2\"; "
  13764. "filename=\"example.txt\"\r\n"
  13765. "\r\n"
  13766. "value2\r\n"
  13767. "--simple boundary--\r\n"
  13768. "This is the epilogue. It is also to be ignored.\r\n";
  13769. std::string content_type =
  13770. R"(multipart/form-data; boundary="simple boundary")";
  13771. Client cli(HOST, PORT);
  13772. auto res = cli.Post("/post", body, content_type.c_str());
  13773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13774. EXPECT_EQ(StatusCode::OK_200, res->status);
  13775. }
  13776. TEST(MultipartFormDataTest, PostCustomBoundary) {
  13777. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13778. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  13779. const ContentReader &content_reader) {
  13780. if (req.is_multipart_form_data()) {
  13781. std::vector<FormData> items;
  13782. content_reader(
  13783. [&](const FormData &file) {
  13784. items.push_back(file);
  13785. return true;
  13786. },
  13787. [&](const char *data, size_t data_length) {
  13788. items.back().content.append(data, data_length);
  13789. return true;
  13790. });
  13791. EXPECT_TRUE(std::string(items[0].name) == "document");
  13792. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13793. EXPECT_TRUE(items[0].filename == "2MB_data");
  13794. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13795. EXPECT_TRUE(items[1].name == "hello");
  13796. EXPECT_TRUE(items[1].content == "world");
  13797. EXPECT_TRUE(items[1].filename == "");
  13798. EXPECT_TRUE(items[1].content_type == "");
  13799. } else {
  13800. std::string body;
  13801. content_reader([&](const char *data, size_t data_length) {
  13802. body.append(data, data_length);
  13803. return true;
  13804. });
  13805. }
  13806. });
  13807. auto port = svr.bind_to_any_port("localhost");
  13808. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13809. auto se = detail::scope_exit([&] {
  13810. svr.stop();
  13811. t.join();
  13812. ASSERT_FALSE(svr.is_running());
  13813. });
  13814. svr.wait_until_ready();
  13815. {
  13816. std::string data(1024 * 1024 * 2, '.');
  13817. std::stringstream buffer;
  13818. buffer << data;
  13819. SSLClient cli("localhost", port);
  13820. cli.enable_server_certificate_verification(false);
  13821. UploadFormDataItems items{
  13822. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13823. {"hello", "world", "", ""},
  13824. };
  13825. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  13826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13827. ASSERT_EQ(StatusCode::OK_200, res->status);
  13828. }
  13829. }
  13830. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  13831. std::string data(1024 * 1024 * 2, '&');
  13832. std::stringstream buffer;
  13833. buffer << data;
  13834. Client cli("https://localhost:8080");
  13835. UploadFormDataItems items{
  13836. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13837. {"hello", "world", "", ""},
  13838. };
  13839. for (const char &c : " \t\r\n") {
  13840. auto res =
  13841. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  13842. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13843. ASSERT_FALSE(res);
  13844. }
  13845. }
  13846. TEST(MultipartFormDataTest, PutFormData) {
  13847. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13848. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  13849. const ContentReader &content_reader) {
  13850. if (req.is_multipart_form_data()) {
  13851. std::vector<FormData> items;
  13852. content_reader(
  13853. [&](const FormData &file) {
  13854. items.push_back(file);
  13855. return true;
  13856. },
  13857. [&](const char *data, size_t data_length) {
  13858. items.back().content.append(data, data_length);
  13859. return true;
  13860. });
  13861. EXPECT_TRUE(std::string(items[0].name) == "document");
  13862. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13863. EXPECT_TRUE(items[0].filename == "2MB_data");
  13864. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13865. EXPECT_TRUE(items[1].name == "hello");
  13866. EXPECT_TRUE(items[1].content == "world");
  13867. EXPECT_TRUE(items[1].filename == "");
  13868. EXPECT_TRUE(items[1].content_type == "");
  13869. } else {
  13870. std::string body;
  13871. content_reader([&](const char *data, size_t data_length) {
  13872. body.append(data, data_length);
  13873. return true;
  13874. });
  13875. }
  13876. });
  13877. auto port = svr.bind_to_any_port("localhost");
  13878. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13879. auto se = detail::scope_exit([&] {
  13880. svr.stop();
  13881. t.join();
  13882. ASSERT_FALSE(svr.is_running());
  13883. });
  13884. svr.wait_until_ready();
  13885. {
  13886. std::string data(1024 * 1024 * 2, '&');
  13887. std::stringstream buffer;
  13888. buffer << data;
  13889. SSLClient cli("localhost", port);
  13890. cli.enable_server_certificate_verification(false);
  13891. UploadFormDataItems items{
  13892. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13893. {"hello", "world", "", ""},
  13894. };
  13895. auto res = cli.Put("/put", items);
  13896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13897. ASSERT_EQ(StatusCode::OK_200, res->status);
  13898. }
  13899. }
  13900. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  13901. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13902. svr.Put("/put_customboundary",
  13903. [&](const Request &req, const Response & /*res*/,
  13904. const ContentReader &content_reader) {
  13905. if (req.is_multipart_form_data()) {
  13906. std::vector<FormData> items;
  13907. content_reader(
  13908. [&](const FormData &file) {
  13909. items.push_back(file);
  13910. return true;
  13911. },
  13912. [&](const char *data, size_t data_length) {
  13913. items.back().content.append(data, data_length);
  13914. return true;
  13915. });
  13916. EXPECT_TRUE(std::string(items[0].name) == "document");
  13917. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13918. EXPECT_TRUE(items[0].filename == "2MB_data");
  13919. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13920. EXPECT_TRUE(items[1].name == "hello");
  13921. EXPECT_TRUE(items[1].content == "world");
  13922. EXPECT_TRUE(items[1].filename == "");
  13923. EXPECT_TRUE(items[1].content_type == "");
  13924. } else {
  13925. std::string body;
  13926. content_reader([&](const char *data, size_t data_length) {
  13927. body.append(data, data_length);
  13928. return true;
  13929. });
  13930. }
  13931. });
  13932. auto port = svr.bind_to_any_port("localhost");
  13933. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13934. auto se = detail::scope_exit([&] {
  13935. svr.stop();
  13936. t.join();
  13937. ASSERT_FALSE(svr.is_running());
  13938. });
  13939. svr.wait_until_ready();
  13940. {
  13941. std::string data(1024 * 1024 * 2, '&');
  13942. std::stringstream buffer;
  13943. buffer << data;
  13944. SSLClient cli("localhost", port);
  13945. cli.enable_server_certificate_verification(false);
  13946. UploadFormDataItems items{
  13947. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13948. {"hello", "world", "", ""},
  13949. };
  13950. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  13951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13952. ASSERT_EQ(StatusCode::OK_200, res->status);
  13953. }
  13954. }
  13955. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  13956. std::string data(1024 * 1024 * 2, '&');
  13957. std::stringstream buffer;
  13958. buffer << data;
  13959. Client cli("https://localhost:8080");
  13960. cli.enable_server_certificate_verification(false);
  13961. UploadFormDataItems items{
  13962. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13963. {"hello", "world", "", ""},
  13964. };
  13965. for (const char &c : " \t\r\n") {
  13966. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  13967. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13968. ASSERT_FALSE(res);
  13969. }
  13970. }
  13971. TEST(MultipartFormDataTest, AlternateFilename) {
  13972. auto handled = false;
  13973. Server svr;
  13974. svr.Post("/test", [&](const Request &req, Response &res) {
  13975. ASSERT_EQ(2u, req.form.files.size());
  13976. ASSERT_EQ(1u, req.form.fields.size());
  13977. // Test files
  13978. const auto &file1 = req.form.get_file("file1");
  13979. ASSERT_EQ("file1", file1.name);
  13980. ASSERT_EQ("A.txt", file1.filename);
  13981. ASSERT_EQ("text/plain", file1.content_type);
  13982. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  13983. const auto &file2 = req.form.get_file("file2");
  13984. ASSERT_EQ("file2", file2.name);
  13985. ASSERT_EQ("a.html", file2.filename);
  13986. ASSERT_EQ("text/html", file2.content_type);
  13987. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  13988. file2.content);
  13989. // Test text field
  13990. const auto &text = req.form.get_field("text");
  13991. ASSERT_EQ("text default", text);
  13992. res.set_content("ok", "text/plain");
  13993. handled = true;
  13994. });
  13995. thread t = thread([&] { svr.listen(HOST, PORT); });
  13996. auto se = detail::scope_exit([&] {
  13997. svr.stop();
  13998. t.join();
  13999. ASSERT_FALSE(svr.is_running());
  14000. ASSERT_TRUE(handled);
  14001. });
  14002. svr.wait_until_ready();
  14003. auto req = "POST /test HTTP/1.1\r\n"
  14004. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14005. "Content-Length: 399\r\n"
  14006. "\r\n"
  14007. "----------\r\n"
  14008. "Content-Disposition: form-data; name=\"text\"\r\n"
  14009. "\r\n"
  14010. "text default\r\n"
  14011. "----------\r\n"
  14012. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14013. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14014. "Content-Type: text/plain\r\n"
  14015. "\r\n"
  14016. "Content of a.txt.\r\n"
  14017. "\r\n"
  14018. "----------\r\n"
  14019. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14020. "\"a.html\"\r\n"
  14021. "Content-Type: text/html\r\n"
  14022. "\r\n"
  14023. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14024. "\r\n"
  14025. "------------\r\n";
  14026. ASSERT_TRUE(send_request(1, req));
  14027. }
  14028. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14029. auto handled = false;
  14030. Server svr;
  14031. svr.Post("/test", [&](const Request &req, Response &res) {
  14032. // Case-insensitive "utf-8''" prefix with a long value
  14033. const auto &file = req.form.get_file("file1");
  14034. ASSERT_EQ("file1", file.name);
  14035. // 8000 chars exercises both the Content-Disposition parser and the
  14036. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  14037. // Prior to the fix, std::regex_match on this header would cause O(N)
  14038. // stack recursion in libstdc++, leading to SIGSEGV.
  14039. std::string expected_filename(8000, 'A');
  14040. ASSERT_EQ(expected_filename, file.filename);
  14041. res.set_content("ok", "text/plain");
  14042. handled = true;
  14043. });
  14044. thread t = thread([&] { svr.listen(HOST, PORT); });
  14045. auto se = detail::scope_exit([&] {
  14046. svr.stop();
  14047. t.join();
  14048. ASSERT_FALSE(svr.is_running());
  14049. ASSERT_TRUE(handled);
  14050. });
  14051. svr.wait_until_ready();
  14052. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14053. // Regression test for GHSA-qq6v-r583-3h69
  14054. std::string long_filename(8000, 'A');
  14055. std::string body = "----------\r\n"
  14056. "Content-Disposition: form-data; name=\"file1\"; "
  14057. "filename*=\"Utf-8''" +
  14058. long_filename +
  14059. "\"\r\n"
  14060. "\r\n"
  14061. "hello\r\n"
  14062. "------------\r\n";
  14063. auto req = "POST /test HTTP/1.1\r\n"
  14064. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14065. "Content-Length: " +
  14066. std::to_string(body.size()) + "\r\n\r\n" + body;
  14067. ASSERT_TRUE(send_request(1, req));
  14068. }
  14069. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14070. auto handled = false;
  14071. Server svr;
  14072. svr.Post("/test", [&](const Request &req, Response &) {
  14073. ASSERT_EQ(2u, req.form.fields.size());
  14074. const auto &text1 = req.form.get_field("text1");
  14075. ASSERT_EQ("text1", text1);
  14076. const auto &text2 = req.form.get_field("text2");
  14077. ASSERT_EQ("text2", text2);
  14078. handled = true;
  14079. });
  14080. thread t = thread([&] { svr.listen(HOST, PORT); });
  14081. auto se = detail::scope_exit([&] {
  14082. svr.stop();
  14083. t.join();
  14084. ASSERT_FALSE(svr.is_running());
  14085. ASSERT_TRUE(handled);
  14086. });
  14087. svr.wait_until_ready();
  14088. auto req = "POST /test HTTP/1.1\r\n"
  14089. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14090. "Content-Length: 146\r\n"
  14091. "\r\n----------\r\n"
  14092. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14093. "\r\n"
  14094. "text1"
  14095. "\r\n----------\r\n"
  14096. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14097. "\r\n"
  14098. "text2"
  14099. "\r\n------------";
  14100. std::string response;
  14101. ASSERT_TRUE(send_request(1, req, &response));
  14102. ASSERT_EQ("200", response.substr(9, 3));
  14103. }
  14104. TEST(MultipartFormDataTest, ContentLength) {
  14105. auto handled = false;
  14106. Server svr;
  14107. svr.Post("/test", [&](const Request &req, Response &) {
  14108. ASSERT_EQ(2u, req.form.fields.size());
  14109. const auto &text1 = req.form.get_field("text1");
  14110. ASSERT_EQ("text1", text1);
  14111. const auto &text2 = req.form.get_field("text2");
  14112. ASSERT_EQ("text2", text2);
  14113. handled = true;
  14114. });
  14115. thread t = thread([&] { svr.listen(HOST, PORT); });
  14116. auto se = detail::scope_exit([&] {
  14117. svr.stop();
  14118. t.join();
  14119. ASSERT_FALSE(svr.is_running());
  14120. ASSERT_TRUE(handled);
  14121. });
  14122. svr.wait_until_ready();
  14123. auto req = "POST /test HTTP/1.1\r\n"
  14124. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14125. "Content-Length: 167\r\n"
  14126. "\r\n----------\r\n"
  14127. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14128. "Content-Length: 5\r\n"
  14129. "\r\n"
  14130. "text1"
  14131. "\r\n----------\r\n"
  14132. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14133. "\r\n"
  14134. "text2"
  14135. "\r\n------------\r\n";
  14136. std::string response;
  14137. ASSERT_TRUE(send_request(1, req, &response));
  14138. ASSERT_EQ("200", response.substr(9, 3));
  14139. }
  14140. TEST(MultipartFormDataTest, AccessPartHeaders) {
  14141. auto handled = false;
  14142. Server svr;
  14143. svr.Post("/test", [&](const Request &req, Response &) {
  14144. ASSERT_EQ(2u, req.form.fields.size());
  14145. const auto &text1 = req.form.get_field("text1");
  14146. ASSERT_EQ("text1", text1);
  14147. // TODO: Add header access for text fields if needed
  14148. const auto &text2 = req.form.get_field("text2");
  14149. ASSERT_EQ("text2", text2);
  14150. // TODO: Header access for text fields needs to be implemented
  14151. // auto &headers = it->second.headers;
  14152. // ASSERT_EQ(3U, headers.size());
  14153. // auto custom_header = headers.find("x-whatever");
  14154. // ASSERT_TRUE(custom_header != headers.end());
  14155. // ASSERT_NE("customvalue", custom_header->second);
  14156. // ASSERT_EQ("CustomValue", custom_header->second);
  14157. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14158. handled = true;
  14159. });
  14160. thread t = thread([&] { svr.listen(HOST, PORT); });
  14161. auto se = detail::scope_exit([&] {
  14162. svr.stop();
  14163. t.join();
  14164. ASSERT_FALSE(svr.is_running());
  14165. ASSERT_TRUE(handled);
  14166. });
  14167. svr.wait_until_ready();
  14168. auto req = "POST /test HTTP/1.1\r\n"
  14169. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14170. "Content-Length: 232\r\n"
  14171. "\r\n----------\r\n"
  14172. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14173. "Content-Length: 5\r\n"
  14174. "X-Test: 1\r\n"
  14175. "\r\n"
  14176. "text1"
  14177. "\r\n----------\r\n"
  14178. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14179. "Content-Type: text/plain\r\n"
  14180. "X-Whatever: CustomValue\r\n"
  14181. "\r\n"
  14182. "text2"
  14183. "\r\n------------\r\n"
  14184. "That should be disregarded. Not even read";
  14185. std::string response;
  14186. ASSERT_TRUE(send_request(1, req, &response));
  14187. ASSERT_EQ("200", response.substr(9, 3));
  14188. }
  14189. TEST(MultipartFormDataTest, LargeHeader) {
  14190. auto handled = false;
  14191. Server svr;
  14192. svr.Post("/test", [&](const Request &req, Response &) {
  14193. ASSERT_EQ(1u, req.form.fields.size());
  14194. const auto &text = req.form.get_field("name1");
  14195. ASSERT_EQ("text1", text);
  14196. handled = true;
  14197. });
  14198. thread t = thread([&] { svr.listen(HOST, PORT); });
  14199. auto se = detail::scope_exit([&] {
  14200. svr.stop();
  14201. t.join();
  14202. ASSERT_FALSE(svr.is_running());
  14203. ASSERT_TRUE(handled);
  14204. });
  14205. svr.wait_until_ready();
  14206. auto boundary = std::string("cpp-httplib-multipart-data");
  14207. std::string content = "--" + boundary +
  14208. "\r\n"
  14209. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14210. "\r\n"
  14211. "text1\r\n"
  14212. "--" +
  14213. boundary + "--\r\n";
  14214. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14215. "Content-Type: multipart/form-data;boundary=" +
  14216. boundary +
  14217. "\r\n"
  14218. "Content-Length: " +
  14219. std::to_string(content.size()) +
  14220. "\r\n"
  14221. "Dummy-Header: ";
  14222. std::string header_suffix = "\r\n"
  14223. "\r\n";
  14224. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14225. size_t header_dummy_size =
  14226. read_buff_size -
  14227. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14228. auto header_dummy = std::string(header_dummy_size, '@');
  14229. auto req = header_prefix + header_dummy + header_suffix + content;
  14230. std::string response;
  14231. ASSERT_TRUE(send_request(1, req, &response));
  14232. ASSERT_EQ("200", response.substr(9, 3));
  14233. }
  14234. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14235. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14236. // (not chunked Transfer-Encoding) after the streaming refactor.
  14237. auto handled = false;
  14238. Server svr;
  14239. svr.Post("/upload", [&](const Request &req, Response &res) {
  14240. auto cl_it = req.headers.find("Content-Length");
  14241. EXPECT_TRUE(cl_it != req.headers.end());
  14242. auto te_it = req.headers.find("Transfer-Encoding");
  14243. EXPECT_TRUE(te_it == req.headers.end());
  14244. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  14245. res.set_content("ok", "text/plain");
  14246. handled = true;
  14247. });
  14248. auto port = svr.bind_to_any_port(HOST);
  14249. auto t = thread([&] { svr.listen_after_bind(); });
  14250. auto se = detail::scope_exit([&] {
  14251. svr.stop();
  14252. t.join();
  14253. ASSERT_FALSE(svr.is_running());
  14254. ASSERT_TRUE(handled);
  14255. });
  14256. svr.wait_until_ready();
  14257. UploadFormDataItems items = {
  14258. {"field1", "hello", "", "text/plain"},
  14259. {"file1", "world", "test.txt", "application/octet-stream"},
  14260. };
  14261. Client cli(HOST, port);
  14262. auto res = cli.Post("/upload", {}, items);
  14263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14264. EXPECT_EQ(StatusCode::OK_200, res->status);
  14265. }
  14266. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14267. // Verify that make_multipart_content_provider coalesces many small segments
  14268. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14269. constexpr size_t kItemCount = 1000;
  14270. UploadFormDataItems items;
  14271. items.reserve(kItemCount);
  14272. for (size_t i = 0; i < kItemCount; i++) {
  14273. items.push_back(
  14274. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14275. }
  14276. const std::string boundary = "----test-boundary";
  14277. auto content_length = detail::get_multipart_content_length(items, boundary);
  14278. auto provider = detail::make_multipart_content_provider(items, boundary);
  14279. // Drive the provider the same way write_content_with_progress does
  14280. size_t write_count = 0;
  14281. size_t total_bytes = 0;
  14282. DataSink sink;
  14283. size_t offset = 0;
  14284. sink.write = [&](const char *d, size_t l) -> bool {
  14285. (void)d;
  14286. write_count++;
  14287. total_bytes += l;
  14288. offset += l;
  14289. return true;
  14290. };
  14291. sink.is_writable = []() -> bool { return true; };
  14292. while (offset < content_length) {
  14293. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  14294. }
  14295. EXPECT_EQ(content_length, total_bytes);
  14296. // The total number of segments is 3 * kItemCount + 1 = 3001.
  14297. // With buffering into 64KB blocks, write_count should be much smaller.
  14298. auto segment_count = 3 * kItemCount + 1;
  14299. EXPECT_LT(write_count, segment_count / 10);
  14300. }
  14301. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  14302. // Integration test: send many UploadFormDataItems and verify the server
  14303. // receives all of them correctly (#2410).
  14304. constexpr size_t kItemCount = 500;
  14305. auto handled = false;
  14306. Server svr;
  14307. svr.Post("/upload", [&](const Request &req, Response &res) {
  14308. EXPECT_EQ(kItemCount, req.form.fields.size());
  14309. for (size_t i = 0; i < kItemCount; i++) {
  14310. auto key = "field" + std::to_string(i);
  14311. auto val = "value" + std::to_string(i);
  14312. auto it = req.form.fields.find(key);
  14313. if (it != req.form.fields.end()) {
  14314. EXPECT_EQ(val, it->second.content);
  14315. } else {
  14316. ADD_FAILURE() << "Missing field: " << key;
  14317. }
  14318. }
  14319. res.set_content("ok", "text/plain");
  14320. handled = true;
  14321. });
  14322. auto port = svr.bind_to_any_port(HOST);
  14323. auto t = thread([&] { svr.listen_after_bind(); });
  14324. auto se = detail::scope_exit([&] {
  14325. svr.stop();
  14326. t.join();
  14327. ASSERT_FALSE(svr.is_running());
  14328. ASSERT_TRUE(handled);
  14329. });
  14330. svr.wait_until_ready();
  14331. UploadFormDataItems items;
  14332. items.reserve(kItemCount);
  14333. for (size_t i = 0; i < kItemCount; i++) {
  14334. items.push_back(
  14335. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14336. }
  14337. Client cli(HOST, port);
  14338. auto res = cli.Post("/upload", items);
  14339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14340. EXPECT_EQ(StatusCode::OK_200, res->status);
  14341. }
  14342. TEST(MultipartFormDataTest, MakeFileProvider) {
  14343. // Verify make_file_provider sends a file's contents correctly.
  14344. const std::string file_content(4096, 'Z');
  14345. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  14346. {
  14347. std::ofstream ofs(tmp_path, std::ios::binary);
  14348. ofs.write(file_content.data(),
  14349. static_cast<std::streamsize>(file_content.size()));
  14350. }
  14351. auto handled = false;
  14352. Server svr;
  14353. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  14354. const ContentReader &content_reader) {
  14355. ASSERT_TRUE(req.is_multipart_form_data());
  14356. std::vector<FormData> items;
  14357. content_reader(
  14358. [&](const FormData &file) {
  14359. items.push_back(file);
  14360. return true;
  14361. },
  14362. [&](const char *data, size_t data_length) {
  14363. items.back().content.append(data, data_length);
  14364. return true;
  14365. });
  14366. ASSERT_EQ(1u, items.size());
  14367. EXPECT_EQ("myfile", items[0].name);
  14368. EXPECT_EQ("data.bin", items[0].filename);
  14369. EXPECT_EQ("application/octet-stream", items[0].content_type);
  14370. EXPECT_EQ(file_content, items[0].content);
  14371. handled = true;
  14372. });
  14373. auto port = svr.bind_to_any_port(HOST);
  14374. auto t = thread([&] { svr.listen_after_bind(); });
  14375. auto se = detail::scope_exit([&] {
  14376. svr.stop();
  14377. t.join();
  14378. ASSERT_FALSE(svr.is_running());
  14379. ASSERT_TRUE(handled);
  14380. std::remove(tmp_path.c_str());
  14381. });
  14382. svr.wait_until_ready();
  14383. FormDataProviderItems providers;
  14384. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  14385. "application/octet-stream"));
  14386. Client cli(HOST, port);
  14387. auto res = cli.Post("/upload", {}, {}, providers);
  14388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14389. EXPECT_EQ(StatusCode::OK_200, res->status);
  14390. }
  14391. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  14392. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  14393. // (100) headers is rejected with a 400 Bad Request response.
  14394. Server svr;
  14395. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14396. res.set_content("ok", "text/plain");
  14397. });
  14398. thread t = thread([&] { svr.listen(HOST, PORT); });
  14399. auto se = detail::scope_exit([&] {
  14400. svr.stop();
  14401. t.join();
  14402. ASSERT_FALSE(svr.is_running());
  14403. });
  14404. svr.wait_until_ready();
  14405. // Build a multipart part with 101 custom headers (exceeding
  14406. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  14407. std::stringstream body;
  14408. body << "--simpleboundary\r\n"
  14409. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  14410. for (int i = 0; i < 101; i++) {
  14411. body << "X-Custom-Header-" << i << ": value\r\n";
  14412. }
  14413. body << "\r\n"
  14414. << "value1\r\n"
  14415. << "--simpleboundary--\r\n";
  14416. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  14417. Client cli(HOST, PORT);
  14418. auto res = cli.Post("/post", body.str(), content_type.c_str());
  14419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14420. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14421. }
  14422. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  14423. // A body that never contains the declared boundary must not be accumulated
  14424. // while the parser waits for it. Buffering it would also make every read
  14425. // rescan everything seen so far, which is quadratic in the body size.
  14426. Server svr;
  14427. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14428. res.set_content("ok", "text/plain");
  14429. });
  14430. auto port = svr.bind_to_any_port(HOST);
  14431. thread t = thread([&] { svr.listen_after_bind(); });
  14432. auto se = detail::scope_exit([&] {
  14433. svr.stop();
  14434. t.join();
  14435. ASSERT_FALSE(svr.is_running());
  14436. });
  14437. svr.wait_until_ready();
  14438. Client cli(HOST, port);
  14439. cli.set_read_timeout(60, 0);
  14440. cli.set_write_timeout(60, 0);
  14441. // '-' is the worst case: it matches the first character of the boundary, so
  14442. // every position has to be checked against it.
  14443. auto post_dashes = [&](size_t size) {
  14444. const std::string body(size, '-');
  14445. auto start = std::chrono::steady_clock::now();
  14446. auto res =
  14447. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  14448. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  14449. std::chrono::steady_clock::now() - start)
  14450. .count();
  14451. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14452. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  14453. return ms;
  14454. };
  14455. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  14456. // Windows.
  14457. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  14458. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  14459. // Comparing the two sizes rather than checking an absolute duration keeps
  14460. // this meaningful across build types and CI load, both of which move the
  14461. // absolute numbers by more than an order of magnitude. Four times the bytes
  14462. // costs about four times the time when parsing is linear, and about sixteen
  14463. // times when the body is buffered and rescanned.
  14464. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  14465. EXPECT_LT(ms_16mb, ms_4mb * 10)
  14466. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  14467. << "ms, which suggests the body is being buffered and rescanned";
  14468. }
  14469. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  14470. // A boundary can only be followed by CRLF or by "--", so anything else is
  14471. // malformed no matter what comes next. The parser must say so right away
  14472. // instead of buffering the rest of the declared body.
  14473. Server svr;
  14474. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14475. res.set_content("ok", "text/plain");
  14476. });
  14477. auto port = svr.bind_to_any_port(HOST);
  14478. thread t = 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. // Announce a 1 MB body but send only the malformed prefix. A parser that
  14486. // buffers instead of failing would still be waiting for the remaining bytes.
  14487. const std::string body = "--zzzz\r\n"
  14488. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14489. "\r\n"
  14490. "text1"
  14491. "\r\n--zzzzXX";
  14492. const std::string req = "POST /post HTTP/1.1\r\n"
  14493. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14494. "Content-Length: 1048576\r\n"
  14495. "\r\n" +
  14496. body;
  14497. std::string response;
  14498. ASSERT_TRUE(send_request(3, req, &response, port));
  14499. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  14500. EXPECT_EQ("400", response.substr(9, 3));
  14501. }
  14502. // Posts a multipart body split into two writes, so that the server sees the
  14503. // split at whatever offset the caller chose, and expects the single "text1"
  14504. // field to come through.
  14505. static void expect_split_multipart_ok(const std::string &body1,
  14506. const std::string &body2) {
  14507. auto handled = false;
  14508. Server svr;
  14509. svr.Post("/post", [&](const Request &req, Response &) {
  14510. EXPECT_EQ(1u, req.form.fields.size());
  14511. EXPECT_EQ("text1", req.form.get_field("text1"));
  14512. handled = true;
  14513. });
  14514. auto port = svr.bind_to_any_port(HOST);
  14515. thread t = thread([&] { svr.listen_after_bind(); });
  14516. auto se = detail::scope_exit([&] {
  14517. svr.stop();
  14518. t.join();
  14519. ASSERT_FALSE(svr.is_running());
  14520. ASSERT_TRUE(handled);
  14521. });
  14522. svr.wait_until_ready();
  14523. // "Connection: close" makes the server close once it has answered, so the
  14524. // response drain ends immediately instead of idling until the read timeout.
  14525. const std::string head =
  14526. "POST /post HTTP/1.1\r\n"
  14527. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14528. "Connection: close\r\n"
  14529. "Content-Length: " +
  14530. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  14531. std::string response;
  14532. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  14533. ASSERT_GE(response.size(), 12u) << "no response";
  14534. EXPECT_EQ("200", response.substr(9, 3));
  14535. }
  14536. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  14537. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  14538. // ignored, including when it does not arrive in the same read as the
  14539. // close-delimiter itself.
  14540. expect_split_multipart_ok("--zzzz\r\n"
  14541. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14542. "\r\n"
  14543. "text1"
  14544. "\r\n--zzzz--",
  14545. "\r\nthis epilogue must be ignored\r\n");
  14546. }
  14547. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  14548. // The initial boundary may be preceded by a preamble of any length and may
  14549. // straddle a read boundary. Discarding data while waiting for it must not
  14550. // throw away a partial boundary sitting at the end of the buffer.
  14551. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  14552. "zz\r\n"
  14553. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14554. "\r\n"
  14555. "text1"
  14556. "\r\n--zzzz--\r\n");
  14557. }
  14558. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  14559. // The received boundary was only checked for being non-empty, so it could be
  14560. // as long as a header is allowed to be. The parser scans the body for
  14561. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  14562. // costs a nearly full comparison at nearly every position, making the
  14563. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  14564. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  14565. Server svr;
  14566. svr.Post("/post", [](const Request &req, Response &res) {
  14567. EXPECT_EQ(1u, req.form.fields.size());
  14568. EXPECT_EQ("text1", req.form.get_field("text1"));
  14569. res.set_content("ok", "text/plain");
  14570. });
  14571. auto port = svr.bind_to_any_port(HOST);
  14572. thread t = thread([&] { svr.listen_after_bind(); });
  14573. auto se = detail::scope_exit([&] {
  14574. svr.stop();
  14575. t.join();
  14576. ASSERT_FALSE(svr.is_running());
  14577. });
  14578. svr.wait_until_ready();
  14579. Client cli(HOST, port);
  14580. auto post_with_boundary_of_length = [&](size_t len) {
  14581. const std::string boundary(len, 'a');
  14582. const std::string body =
  14583. "--" + boundary +
  14584. "\r\n"
  14585. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14586. "\r\n"
  14587. "text1"
  14588. "\r\n--" +
  14589. boundary + "--\r\n";
  14590. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  14591. };
  14592. auto res = post_with_boundary_of_length(70);
  14593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14594. EXPECT_EQ(StatusCode::OK_200, res->status);
  14595. res = post_with_boundary_of_length(71);
  14596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14597. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14598. }
  14599. TEST(MakeFileBodyTest, Basic) {
  14600. const std::string file_content(4096, 'Z');
  14601. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  14602. {
  14603. std::ofstream ofs(tmp_path, std::ios::binary);
  14604. ofs.write(file_content.data(),
  14605. static_cast<std::streamsize>(file_content.size()));
  14606. }
  14607. auto handled = false;
  14608. Server svr;
  14609. svr.Post("/upload", [&](const Request &req, Response &res) {
  14610. EXPECT_EQ(file_content, req.body);
  14611. handled = true;
  14612. res.status = StatusCode::OK_200;
  14613. });
  14614. auto port = svr.bind_to_any_port(HOST);
  14615. auto t = thread([&] { svr.listen_after_bind(); });
  14616. auto se = detail::scope_exit([&] {
  14617. svr.stop();
  14618. t.join();
  14619. ASSERT_FALSE(svr.is_running());
  14620. ASSERT_TRUE(handled);
  14621. std::remove(tmp_path.c_str());
  14622. });
  14623. svr.wait_until_ready();
  14624. auto fb = make_file_body(tmp_path);
  14625. ASSERT_GT(fb.first, 0u);
  14626. Client cli(HOST, port);
  14627. auto res =
  14628. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  14629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14630. EXPECT_EQ(StatusCode::OK_200, res->status);
  14631. }
  14632. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  14633. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  14634. {
  14635. std::ofstream ofs(path, std::ios::binary);
  14636. const std::string content(100, 'A');
  14637. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14638. }
  14639. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14640. auto body = make_file_body(path);
  14641. ASSERT_EQ(100u, body.first);
  14642. ASSERT_TRUE(static_cast<bool>(body.second));
  14643. // Rewritten shorter after its length was measured - and, on a server, after
  14644. // that length has already gone out as Content-Length.
  14645. {
  14646. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  14647. const std::string content(10, 'A');
  14648. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14649. }
  14650. std::string written;
  14651. DataSink sink;
  14652. sink.write = [&](const char *d, size_t l) {
  14653. written.append(d, l);
  14654. return true;
  14655. };
  14656. // The provider has to report failure. write_content_with_progress() advances
  14657. // its offset only by what was written, so a provider that returns true
  14658. // without completing the length it promised is called again straight away,
  14659. // and again.
  14660. EXPECT_FALSE(body.second(0, body.first, sink));
  14661. EXPECT_EQ(std::string(10, 'A'), written);
  14662. }
  14663. TEST(MakeFileBodyTest, WholeFileIsSent) {
  14664. const std::string path = "./httplib_test_make_file_body_whole.bin";
  14665. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  14666. {
  14667. std::ofstream ofs(path, std::ios::binary);
  14668. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14669. }
  14670. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14671. auto body = make_file_body(path);
  14672. ASSERT_EQ(content.size(), body.first);
  14673. ASSERT_TRUE(static_cast<bool>(body.second));
  14674. std::string written;
  14675. DataSink sink;
  14676. sink.write = [&](const char *d, size_t l) {
  14677. written.append(d, l);
  14678. return true;
  14679. };
  14680. EXPECT_TRUE(body.second(0, body.first, sink));
  14681. EXPECT_EQ(content, written);
  14682. }
  14683. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  14684. static constexpr unsigned int number_of_tasks{1000000};
  14685. std::atomic_uint count{0};
  14686. std::unique_ptr<TaskQueue> task_queue{
  14687. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  14688. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14689. auto queued = task_queue->enqueue(
  14690. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  14691. EXPECT_TRUE(queued);
  14692. }
  14693. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14694. task_queue->shutdown();
  14695. #else
  14696. EXPECT_NO_THROW(task_queue->shutdown());
  14697. #endif
  14698. EXPECT_EQ(number_of_tasks, count.load());
  14699. }
  14700. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  14701. static constexpr unsigned int number_of_tasks{1000000};
  14702. static constexpr unsigned int qlimit{2};
  14703. unsigned int queued_count{0};
  14704. std::atomic_uint count{0};
  14705. std::unique_ptr<TaskQueue> task_queue{
  14706. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  14707. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14708. if (task_queue->enqueue(
  14709. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  14710. queued_count++;
  14711. }
  14712. }
  14713. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14714. task_queue->shutdown();
  14715. #else
  14716. EXPECT_NO_THROW(task_queue->shutdown());
  14717. #endif
  14718. EXPECT_EQ(queued_count, count.load());
  14719. EXPECT_TRUE(queued_count <= number_of_tasks);
  14720. EXPECT_TRUE(queued_count >= qlimit);
  14721. }
  14722. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  14723. // Use a short idle timeout so a dynamic thread spawns, times out and
  14724. // exits during the test, and the pool keeps working afterwards.
  14725. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  14726. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  14727. /*idle_timeout_sec=*/1}};
  14728. std::atomic_uint count{0};
  14729. std::condition_variable cv;
  14730. std::mutex mtx;
  14731. bool release = false;
  14732. // Block the base thread so the second task spawns a dynamic thread.
  14733. EXPECT_TRUE(task_queue->enqueue([&] {
  14734. std::unique_lock<std::mutex> lock(mtx);
  14735. while (!release) {
  14736. cv.wait(lock);
  14737. }
  14738. count++;
  14739. }));
  14740. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14741. // Let the dynamic thread finish its task and exceed the idle timeout.
  14742. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  14743. {
  14744. std::unique_lock<std::mutex> lock(mtx);
  14745. release = true;
  14746. }
  14747. cv.notify_all();
  14748. // The pool must still accept and run tasks after the dynamic thread exited.
  14749. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14750. task_queue->shutdown();
  14751. EXPECT_EQ(3u, count.load());
  14752. }
  14753. TEST(TaskQueueTest, MaxQueuedRequests) {
  14754. static constexpr unsigned int qlimit{3};
  14755. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  14756. std::condition_variable sem_cv;
  14757. std::mutex sem_mtx;
  14758. int credits = 0;
  14759. bool queued;
  14760. /* Fill up the queue with tasks that will block until we give them credits to
  14761. * complete. */
  14762. for (unsigned int n = 0; n <= qlimit;) {
  14763. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  14764. std::unique_lock<std::mutex> lock(sem_mtx);
  14765. while (credits <= 0) {
  14766. sem_cv.wait(lock);
  14767. }
  14768. /* Consume the credit and signal the test code if they are all gone. */
  14769. if (--credits == 0) { sem_cv.notify_one(); }
  14770. });
  14771. if (n < qlimit) {
  14772. /* The first qlimit enqueues must succeed. */
  14773. EXPECT_TRUE(queued);
  14774. } else {
  14775. /* The last one will succeed only when the worker thread
  14776. * starts and dequeues the first blocking task. Although
  14777. * not necessary for the correctness of this test, we sleep for
  14778. * a short while to avoid busy waiting. */
  14779. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14780. }
  14781. if (queued) { n++; }
  14782. }
  14783. /* Further enqueues must fail since the queue is full. */
  14784. for (auto i = 0; i < 4; i++) {
  14785. queued = task_queue->enqueue([] {});
  14786. EXPECT_FALSE(queued);
  14787. }
  14788. /* Give the credits to allow the previous tasks to complete. */
  14789. {
  14790. std::unique_lock<std::mutex> lock(sem_mtx);
  14791. credits += qlimit + 1;
  14792. }
  14793. sem_cv.notify_all();
  14794. /* Wait for all the credits to be consumed. */
  14795. {
  14796. std::unique_lock<std::mutex> lock(sem_mtx);
  14797. while (credits > 0) {
  14798. sem_cv.wait(lock);
  14799. }
  14800. }
  14801. /* Check that we are able again to enqueue at least qlimit tasks. */
  14802. for (unsigned int i = 0; i < qlimit; i++) {
  14803. queued = task_queue->enqueue([] {});
  14804. EXPECT_TRUE(queued);
  14805. }
  14806. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14807. task_queue->shutdown();
  14808. #else
  14809. EXPECT_NO_THROW(task_queue->shutdown());
  14810. #endif
  14811. }
  14812. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  14813. Server svr;
  14814. std::string method;
  14815. std::string body;
  14816. auto has_content_length = false;
  14817. auto has_transfer_encoding = false;
  14818. std::atomic<int> bad_requests{0};
  14819. // Leftover body bytes get parsed as a malformed request and answered with
  14820. // 400
  14821. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  14822. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  14823. });
  14824. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  14825. res.set_redirect("/down", StatusCode::SeeOther_303);
  14826. });
  14827. svr.Get("/down", [&](const Request &req, Response &res) {
  14828. method = req.method;
  14829. body = req.body;
  14830. has_content_length = req.has_header("Content-Length");
  14831. has_transfer_encoding = req.has_header("Transfer-Encoding");
  14832. res.set_content("ok", "text/plain");
  14833. });
  14834. auto port = svr.bind_to_any_port(HOST);
  14835. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14836. auto se = detail::scope_exit([&] {
  14837. svr.stop();
  14838. thread.join();
  14839. ASSERT_FALSE(svr.is_running());
  14840. });
  14841. svr.wait_until_ready();
  14842. const std::string payload = "SECRET-BODY";
  14843. auto check = [&](Client &cli, const Result &res) {
  14844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14845. EXPECT_EQ(StatusCode::OK_200, res->status);
  14846. EXPECT_EQ("ok", res->body);
  14847. EXPECT_EQ("GET", method);
  14848. EXPECT_TRUE(body.empty());
  14849. EXPECT_FALSE(has_content_length);
  14850. EXPECT_FALSE(has_transfer_encoding);
  14851. // Nothing of the original body may be left on the connection
  14852. auto res2 = cli.Get("/down");
  14853. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  14854. EXPECT_EQ(StatusCode::OK_200, res2->status);
  14855. EXPECT_EQ("ok", res2->body);
  14856. EXPECT_EQ(0, bad_requests);
  14857. };
  14858. // With content length
  14859. {
  14860. Client cli(HOST, port);
  14861. cli.set_keep_alive(true);
  14862. cli.set_follow_location(true);
  14863. auto res = cli.Post(
  14864. "/up", payload.size(),
  14865. [&](size_t offset, size_t length, DataSink &sink) {
  14866. return sink.write(payload.data() + offset, length);
  14867. },
  14868. "text/plain");
  14869. check(cli, res);
  14870. }
  14871. // Without content length (chunked)
  14872. {
  14873. Client cli(HOST, port);
  14874. cli.set_keep_alive(true);
  14875. cli.set_follow_location(true);
  14876. auto res = cli.Post(
  14877. "/up",
  14878. [&](size_t /*offset*/, DataSink &sink) {
  14879. sink.write(payload.data(), payload.size());
  14880. sink.done();
  14881. return true;
  14882. },
  14883. "text/plain");
  14884. check(cli, res);
  14885. }
  14886. }
  14887. TEST(RedirectTest, LocationPathIsNotDecoded) {
  14888. Server svr;
  14889. std::string target;
  14890. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  14891. // Echo the still-encoded name back in the Location
  14892. const std::string prefix = "/start/";
  14893. res.status = StatusCode::Found_302;
  14894. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  14895. });
  14896. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  14897. target = req.target;
  14898. res.set_content("ok", "text/plain");
  14899. });
  14900. auto port = svr.bind_to_any_port(HOST);
  14901. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14902. auto se = detail::scope_exit([&] {
  14903. svr.stop();
  14904. thread.join();
  14905. ASSERT_FALSE(svr.is_running());
  14906. });
  14907. svr.wait_until_ready();
  14908. // Decoding the Location path would turn the first four into a path
  14909. // separator, a query delimiter, a fragment delimiter and a different
  14910. // percent-encoded octet. The rest must keep reaching the server as they are.
  14911. const std::vector<std::string> names = {
  14912. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  14913. };
  14914. for (auto path_encode : {true, false}) {
  14915. Client cli(HOST, port);
  14916. cli.set_follow_location(true);
  14917. cli.set_path_encode(path_encode);
  14918. for (const auto &name : names) {
  14919. target.clear();
  14920. auto res = cli.Get("/start/" + name);
  14921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14922. EXPECT_EQ(StatusCode::OK_200, res->status);
  14923. EXPECT_EQ("/dest/" + name, target);
  14924. }
  14925. }
  14926. }
  14927. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  14928. Server svr;
  14929. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14930. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  14931. });
  14932. svr.Get("/hello", [](const Request &req, Response &res) {
  14933. res.set_content(req.get_param_value("key"), "text/plain");
  14934. });
  14935. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14936. auto se = detail::scope_exit([&] {
  14937. svr.stop();
  14938. thread.join();
  14939. ASSERT_FALSE(svr.is_running());
  14940. });
  14941. svr.wait_until_ready();
  14942. {
  14943. Client cli(HOST, PORT);
  14944. cli.set_follow_location(true);
  14945. auto res = cli.Get("/");
  14946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14947. EXPECT_EQ(StatusCode::OK_200, res->status);
  14948. EXPECT_EQ("val&key2=val2", res->body);
  14949. }
  14950. }
  14951. #endif
  14952. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  14953. Server svr;
  14954. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14955. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  14956. });
  14957. svr.Get("/hello", [](const Request &req, Response &res) {
  14958. res.set_content(req.get_param_value("key"), "text/plain");
  14959. });
  14960. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14961. auto se = detail::scope_exit([&] {
  14962. svr.stop();
  14963. thread.join();
  14964. ASSERT_FALSE(svr.is_running());
  14965. });
  14966. svr.wait_until_ready();
  14967. {
  14968. Client cli(HOST, PORT);
  14969. cli.set_follow_location(true);
  14970. auto res = cli.Get("/");
  14971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14972. EXPECT_EQ(StatusCode::OK_200, res->status);
  14973. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  14974. }
  14975. }
  14976. TEST(RedirectTest, RedirectWithPlusInPath) {
  14977. Server svr;
  14978. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14979. res.set_redirect("/a+b");
  14980. });
  14981. // Route pattern uses regex; escape + as \\+
  14982. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  14983. res.set_content(req.path, "text/plain");
  14984. });
  14985. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14986. auto se = detail::scope_exit([&] {
  14987. svr.stop();
  14988. thread.join();
  14989. ASSERT_FALSE(svr.is_running());
  14990. });
  14991. svr.wait_until_ready();
  14992. {
  14993. Client cli(HOST, PORT);
  14994. cli.set_follow_location(true);
  14995. auto res = cli.Get("/");
  14996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14997. EXPECT_EQ(StatusCode::OK_200, res->status);
  14998. EXPECT_EQ("/a+b", res->body);
  14999. }
  15000. }
  15001. TEST(RedirectTest, ResolveRelativeLocation) {
  15002. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15003. const std::vector<std::pair<std::string, std::string>> cases = {
  15004. {"g", "/b/c/g"},
  15005. {"./g", "/b/c/g"},
  15006. {"g/", "/b/c/g/"},
  15007. {"?y", "/b/c/d;p?y"},
  15008. {"g?y", "/b/c/g?y"},
  15009. {"#s", "/b/c/d;p?q#s"},
  15010. {"g#s", "/b/c/g#s"},
  15011. {"g?y#s", "/b/c/g?y#s"},
  15012. {";x", "/b/c/;x"},
  15013. {"g;x", "/b/c/g;x"},
  15014. {".", "/b/c/"},
  15015. {"./", "/b/c/"},
  15016. {"..", "/b/"},
  15017. {"../", "/b/"},
  15018. {"../g", "/b/g"},
  15019. {"../..", "/"},
  15020. {"../../", "/"},
  15021. {"../../g", "/g"},
  15022. {"../../../g", "/g"},
  15023. {"g.", "/b/c/g."},
  15024. {".g", "/b/c/.g"},
  15025. {"g..", "/b/c/g.."},
  15026. {"..g", "/b/c/..g"},
  15027. {"./../g", "/b/g"},
  15028. {"./g/.", "/b/c/g/"},
  15029. {"g/./h", "/b/c/g/h"},
  15030. {"g/../h", "/b/c/h"},
  15031. {"g;x=1/./y", "/b/c/g;x=1/y"},
  15032. {"g;x=1/../y", "/b/c/y"},
  15033. {"g?y/./x", "/b/c/g?y/./x"},
  15034. {"g#s/../x", "/b/c/g#s/../x"},
  15035. // Not relative-path references, so left for parse_url.
  15036. {"/g", "/g"},
  15037. {"//g", "//g"},
  15038. {"http://g/x", "http://g/x"},
  15039. {"g:h", "g:h"},
  15040. };
  15041. for (const auto &c : cases) {
  15042. EXPECT_EQ(c.second,
  15043. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15044. << c.first;
  15045. }
  15046. }
  15047. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15048. Server svr;
  15049. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15050. res.set_redirect(req.get_param_value("to"));
  15051. });
  15052. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15053. res.set_content(req.target, "text/plain");
  15054. });
  15055. svr.Get("/other", [](const Request &req, Response &res) {
  15056. res.set_content(req.target, "text/plain");
  15057. });
  15058. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15059. auto se = detail::scope_exit([&] {
  15060. svr.stop();
  15061. thread.join();
  15062. ASSERT_FALSE(svr.is_running());
  15063. });
  15064. svr.wait_until_ready();
  15065. const std::vector<std::pair<std::string, std::string>> cases = {
  15066. {"next", "/dir/next"},
  15067. {"./next?x=1", "/dir/next?x=1"},
  15068. {"../other", "/other"},
  15069. };
  15070. for (const auto &c : cases) {
  15071. Client cli(HOST, PORT);
  15072. cli.set_follow_location(true);
  15073. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15074. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15075. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  15076. EXPECT_EQ(c.second, res->body) << c.first;
  15077. }
  15078. }
  15079. #ifdef CPPHTTPLIB_SSL_ENABLED
  15080. TEST(RedirectTest, Issue2185_Online) {
  15081. SSLClient client("github.com");
  15082. client.set_follow_location(true);
  15083. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  15084. "Coollab-Windows.zip");
  15085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15086. EXPECT_EQ(StatusCode::OK_200, res->status);
  15087. EXPECT_EQ(9920427U, res->body.size());
  15088. }
  15089. #endif
  15090. TEST(VulnerabilityTest, CRLFInjection) {
  15091. Server svr;
  15092. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  15093. res.set_content("Hello 1", "text/plain");
  15094. });
  15095. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  15096. res.set_content("Hello 2", "text/plain");
  15097. });
  15098. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  15099. res.set_content("Hello 3", "text/plain");
  15100. });
  15101. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  15102. res.set_content("Hello 4", "text/plain");
  15103. });
  15104. svr.set_logger([](const Request &req, const Response & /*res*/) {
  15105. for (const auto &x : req.headers) {
  15106. auto key = x.first;
  15107. EXPECT_STRNE("evil", key.c_str());
  15108. }
  15109. });
  15110. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15111. auto se = detail::scope_exit([&] {
  15112. svr.stop();
  15113. thread.join();
  15114. ASSERT_FALSE(svr.is_running());
  15115. });
  15116. svr.wait_until_ready();
  15117. {
  15118. Client cli(HOST, PORT);
  15119. cli.Post("/test1", "A=B",
  15120. "application/x-www-form-urlencoded\r\nevil: hello1");
  15121. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  15122. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  15123. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  15124. }
  15125. }
  15126. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  15127. auto server_thread = std::thread([] {
  15128. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15129. default_socket_options(srv);
  15130. sockaddr_in addr{};
  15131. addr.sin_family = AF_INET;
  15132. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15133. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15134. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  15135. ::listen(srv, 1);
  15136. sockaddr_in cli_addr{};
  15137. socklen_t cli_len = sizeof(cli_addr);
  15138. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15139. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  15140. std::string buf_all;
  15141. char buf[2048];
  15142. ssize_t n;
  15143. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  15144. buf_all.append(buf, static_cast<size_t>(n));
  15145. size_t pos;
  15146. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  15147. auto request_block = buf_all.substr(0, pos + 4); // include separator
  15148. auto e = request_block.find("\r\n");
  15149. if (e != std::string::npos) {
  15150. auto request_line = request_block.substr(0, e);
  15151. std::string msg =
  15152. "CRLF injection detected in request line: '" + request_line + "'";
  15153. EXPECT_FALSE(true) << msg;
  15154. }
  15155. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  15156. ::send(cli,
  15157. #ifdef _WIN32
  15158. static_cast<const char *>(resp.c_str()),
  15159. static_cast<int>(resp.size()),
  15160. #else
  15161. resp.c_str(), resp.size(),
  15162. #endif
  15163. 0);
  15164. buf_all.erase(0, pos + 4);
  15165. }
  15166. }
  15167. detail::close_socket(cli);
  15168. detail::close_socket(srv);
  15169. });
  15170. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15171. auto cli = Client("127.0.0.1", PORT + 1);
  15172. auto headers = Headers{
  15173. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  15174. {"Connection", "keep-alive"}};
  15175. auto res = cli.Get("/hi", headers);
  15176. EXPECT_FALSE(res);
  15177. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15178. server_thread.join();
  15179. }
  15180. // A request rejected before any byte reaches the socket must fail right away
  15181. // instead of waiting for a response the server will never send.
  15182. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  15183. // The kernel completes the TCP handshake from the listen backlog, so the
  15184. // client connects, but nothing ever reads, responds or closes.
  15185. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15186. default_socket_options(srv);
  15187. sockaddr_in addr{};
  15188. addr.sin_family = AF_INET;
  15189. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15190. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15191. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15192. ASSERT_EQ(0, ::listen(srv, 8));
  15193. auto cli = Client("127.0.0.1", PORT + 1);
  15194. cli.set_read_timeout(10, 0);
  15195. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  15196. return std::chrono::duration_cast<std::chrono::milliseconds>(
  15197. std::chrono::steady_clock::now() - start)
  15198. .count();
  15199. };
  15200. {
  15201. Request req;
  15202. req.method = "GE T";
  15203. req.path = "/";
  15204. auto start = std::chrono::steady_clock::now();
  15205. auto res = cli.send(req);
  15206. EXPECT_FALSE(res);
  15207. EXPECT_EQ(Error::Write, res.error());
  15208. EXPECT_LT(elapsed_ms(start), 1000);
  15209. }
  15210. {
  15211. auto start = std::chrono::steady_clock::now();
  15212. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  15213. EXPECT_FALSE(res);
  15214. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15215. EXPECT_LT(elapsed_ms(start), 1000);
  15216. }
  15217. EXPECT_FALSE(cli.is_socket_open());
  15218. detail::close_socket(srv);
  15219. }
  15220. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  15221. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15222. default_socket_options(srv);
  15223. sockaddr_in addr{};
  15224. addr.sin_family = AF_INET;
  15225. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15226. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15227. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15228. ASSERT_EQ(0, ::listen(srv, 1));
  15229. std::string received;
  15230. auto server_thread = std::thread([&] {
  15231. auto sock = ::accept(srv, nullptr, nullptr);
  15232. if (sock == INVALID_SOCKET) { return; }
  15233. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  15234. char buf[2048];
  15235. ssize_t n;
  15236. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  15237. received.append(buf, static_cast<size_t>(n));
  15238. }
  15239. detail::close_socket(sock);
  15240. });
  15241. {
  15242. auto cli = Client("127.0.0.1", PORT + 1);
  15243. // "Z" sorts after the default headers, so writing straight to the socket
  15244. // would have sent the request line and those headers before the rejection.
  15245. auto handle =
  15246. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  15247. EXPECT_FALSE(handle.is_valid());
  15248. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  15249. }
  15250. server_thread.join();
  15251. detail::close_socket(srv);
  15252. EXPECT_TRUE(received.empty()) << received;
  15253. }
  15254. TEST(PathParamsTest, StaticMatch) {
  15255. const auto pattern = "/users/all";
  15256. detail::PathParamsMatcher matcher(pattern);
  15257. Request request;
  15258. request.path = "/users/all";
  15259. ASSERT_TRUE(matcher.match(request));
  15260. std::unordered_map<std::string, std::string> expected_params = {};
  15261. EXPECT_EQ(request.path_params, expected_params);
  15262. }
  15263. TEST(PathParamsTest, StaticMismatch) {
  15264. const auto pattern = "/users/all";
  15265. detail::PathParamsMatcher matcher(pattern);
  15266. Request request;
  15267. request.path = "/users/1";
  15268. ASSERT_FALSE(matcher.match(request));
  15269. }
  15270. TEST(PathParamsTest, SingleParamInTheMiddle) {
  15271. const auto pattern = "/users/:id/subscriptions";
  15272. detail::PathParamsMatcher matcher(pattern);
  15273. Request request;
  15274. request.path = "/users/42/subscriptions";
  15275. ASSERT_TRUE(matcher.match(request));
  15276. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15277. EXPECT_EQ(request.path_params, expected_params);
  15278. }
  15279. TEST(PathParamsTest, SingleParamInTheEnd) {
  15280. const auto pattern = "/users/:id";
  15281. detail::PathParamsMatcher matcher(pattern);
  15282. Request request;
  15283. request.path = "/users/24";
  15284. ASSERT_TRUE(matcher.match(request));
  15285. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  15286. EXPECT_EQ(request.path_params, expected_params);
  15287. }
  15288. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  15289. const auto pattern = "/users/:id/";
  15290. detail::PathParamsMatcher matcher(pattern);
  15291. Request request;
  15292. request.path = "/users/42/";
  15293. ASSERT_TRUE(matcher.match(request));
  15294. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15295. EXPECT_EQ(request.path_params, expected_params);
  15296. }
  15297. TEST(PathParamsTest, EmptyParam) {
  15298. const auto pattern = "/users/:id/";
  15299. detail::PathParamsMatcher matcher(pattern);
  15300. Request request;
  15301. request.path = "/users//";
  15302. ASSERT_TRUE(matcher.match(request));
  15303. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  15304. EXPECT_EQ(request.path_params, expected_params);
  15305. }
  15306. TEST(PathParamsTest, FragmentMismatch) {
  15307. const auto pattern = "/users/:id/";
  15308. detail::PathParamsMatcher matcher(pattern);
  15309. Request request;
  15310. request.path = "/admins/24/";
  15311. ASSERT_FALSE(matcher.match(request));
  15312. }
  15313. TEST(PathParamsTest, ExtraFragments) {
  15314. const auto pattern = "/users/:id";
  15315. detail::PathParamsMatcher matcher(pattern);
  15316. Request request;
  15317. request.path = "/users/42/subscriptions";
  15318. ASSERT_FALSE(matcher.match(request));
  15319. }
  15320. TEST(PathParamsTest, MissingTrailingParam) {
  15321. const auto pattern = "/users/:id";
  15322. detail::PathParamsMatcher matcher(pattern);
  15323. Request request;
  15324. request.path = "/users";
  15325. ASSERT_FALSE(matcher.match(request));
  15326. }
  15327. TEST(PathParamsTest, MissingParamInTheMiddle) {
  15328. const auto pattern = "/users/:id/subscriptions";
  15329. detail::PathParamsMatcher matcher(pattern);
  15330. Request request;
  15331. request.path = "/users/subscriptions";
  15332. ASSERT_FALSE(matcher.match(request));
  15333. }
  15334. TEST(PathParamsTest, MultipleParams) {
  15335. const auto pattern = "/users/:userid/subscriptions/:subid";
  15336. detail::PathParamsMatcher matcher(pattern);
  15337. Request request;
  15338. request.path = "/users/42/subscriptions/2";
  15339. ASSERT_TRUE(matcher.match(request));
  15340. std::unordered_map<std::string, std::string> expected_params = {
  15341. {"userid", "42"}, {"subid", "2"}};
  15342. EXPECT_EQ(request.path_params, expected_params);
  15343. }
  15344. TEST(PathParamsTest, SequenceOfParams) {
  15345. const auto pattern = "/values/:x/:y/:z";
  15346. detail::PathParamsMatcher matcher(pattern);
  15347. Request request;
  15348. request.path = "/values/1/2/3";
  15349. ASSERT_TRUE(matcher.match(request));
  15350. std::unordered_map<std::string, std::string> expected_params = {
  15351. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  15352. EXPECT_EQ(request.path_params, expected_params);
  15353. }
  15354. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  15355. const auto pattern = "/prefix:suffix";
  15356. detail::PathParamsMatcher matcher(pattern);
  15357. Request request;
  15358. request.path = "/prefix:suffix";
  15359. ASSERT_TRUE(matcher.match(request));
  15360. const std::unordered_map<std::string, std::string> expected_params = {};
  15361. EXPECT_EQ(request.path_params, expected_params);
  15362. }
  15363. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  15364. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  15365. // calling thread's stack on a long enough path for a quantified pattern;
  15366. // RegexMatcher must refuse to run regex matching on paths beyond
  15367. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  15368. detail::RegexMatcher matcher("/files/(.*)");
  15369. Request within_limit;
  15370. within_limit.path = "/files/" + std::string(10, 'A');
  15371. EXPECT_TRUE(matcher.match(within_limit));
  15372. Request over_limit;
  15373. over_limit.path =
  15374. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  15375. EXPECT_FALSE(matcher.match(over_limit));
  15376. }
  15377. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  15378. Server svr;
  15379. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  15380. res.set_content("ok", "text/plain");
  15381. });
  15382. auto port = svr.bind_to_any_port(HOST);
  15383. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15384. auto se = detail::scope_exit([&] {
  15385. svr.stop();
  15386. thread.join();
  15387. ASSERT_FALSE(svr.is_running());
  15388. });
  15389. svr.wait_until_ready();
  15390. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  15391. // request URI limit; this used to be able to crash the process.
  15392. std::string path =
  15393. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  15394. std::string req = "GET " + path +
  15395. " HTTP/1.1\r\n"
  15396. "Host: " +
  15397. std::string(HOST) + ":" + std::to_string(port) +
  15398. "\r\n"
  15399. "Connection: close\r\n"
  15400. "\r\n";
  15401. std::string response;
  15402. ASSERT_TRUE(send_request(5, req, &response, port));
  15403. EXPECT_NE(std::string::npos, response.find("404"));
  15404. }
  15405. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  15406. Server svr;
  15407. auto handler = [](const Request & /*req*/, Response &res) {
  15408. res.set_content("hit", "text/plain");
  15409. };
  15410. // No regex metacharacter, so this one is compared literally
  15411. svr.Get("/literal/route", handler);
  15412. // '.' is a regex metacharacter, so this one must keep regex semantics
  15413. svr.Get("/a.c", handler);
  15414. auto port = svr.bind_to_any_port(HOST);
  15415. std::thread t([&]() { svr.listen_after_bind(); });
  15416. auto se = detail::scope_exit([&] {
  15417. svr.stop();
  15418. t.join();
  15419. ASSERT_FALSE(svr.is_running());
  15420. });
  15421. svr.wait_until_ready();
  15422. Client cli(HOST, port);
  15423. struct {
  15424. const char *path;
  15425. int status;
  15426. } cases[] = {
  15427. {"/literal/route", StatusCode::OK_200},
  15428. {"/literal/routes", StatusCode::NotFound_404},
  15429. {"/literal/rout", StatusCode::NotFound_404},
  15430. {"/abc", StatusCode::OK_200},
  15431. {"/a.c", StatusCode::OK_200},
  15432. };
  15433. for (const auto &x : cases) {
  15434. auto res = cli.Get(x.path);
  15435. ASSERT_TRUE(res) << x.path;
  15436. EXPECT_EQ(x.status, res->status) << x.path;
  15437. }
  15438. }
  15439. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  15440. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  15441. // from exhausting the stack, so it must only constrain routes that actually
  15442. // run a regular expression. A literal route is matched by comparison and
  15443. // stays usable at any length.
  15444. Server svr;
  15445. const std::string pattern =
  15446. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  15447. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  15448. res.set_content("hit", "text/plain");
  15449. });
  15450. auto port = svr.bind_to_any_port(HOST);
  15451. std::thread t([&]() { svr.listen_after_bind(); });
  15452. auto se = detail::scope_exit([&] {
  15453. svr.stop();
  15454. t.join();
  15455. ASSERT_FALSE(svr.is_running());
  15456. });
  15457. svr.wait_until_ready();
  15458. Client cli(HOST, port);
  15459. auto res = cli.Get(pattern);
  15460. ASSERT_TRUE(res);
  15461. EXPECT_EQ(StatusCode::OK_200, res->status);
  15462. }
  15463. TEST(ParseUrlTest, VariousPatterns) {
  15464. {
  15465. detail::UrlComponents uc;
  15466. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  15467. EXPECT_EQ("http", uc.scheme);
  15468. EXPECT_EQ("example.com", uc.host);
  15469. EXPECT_EQ("8080", uc.port);
  15470. EXPECT_EQ("/path", uc.path);
  15471. EXPECT_EQ("?q=1", uc.query);
  15472. }
  15473. {
  15474. detail::UrlComponents uc;
  15475. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  15476. EXPECT_EQ("https", uc.scheme);
  15477. EXPECT_EQ("example.com", uc.host);
  15478. EXPECT_TRUE(uc.port.empty());
  15479. EXPECT_EQ("/path", uc.path);
  15480. }
  15481. {
  15482. detail::UrlComponents uc;
  15483. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  15484. EXPECT_EQ("::1", uc.host);
  15485. EXPECT_EQ("8080", uc.port);
  15486. EXPECT_EQ("/path", uc.path);
  15487. }
  15488. {
  15489. detail::UrlComponents uc;
  15490. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  15491. }
  15492. {
  15493. // Bytes after the IPv6 literal must be a delimiter, not folded into
  15494. // the path while the connection still targets the bracketed host.
  15495. detail::UrlComponents uc;
  15496. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  15497. }
  15498. {
  15499. detail::UrlComponents uc;
  15500. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  15501. }
  15502. {
  15503. detail::UrlComponents uc;
  15504. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  15505. EXPECT_EQ("::1", uc.host);
  15506. EXPECT_TRUE(uc.port.empty());
  15507. EXPECT_EQ("/path", uc.path);
  15508. }
  15509. {
  15510. detail::UrlComponents uc;
  15511. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  15512. EXPECT_TRUE(uc.scheme.empty());
  15513. EXPECT_EQ("example.com", uc.host);
  15514. EXPECT_EQ("/path", uc.path);
  15515. EXPECT_EQ("?q=1", uc.query);
  15516. }
  15517. {
  15518. detail::UrlComponents uc;
  15519. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  15520. EXPECT_TRUE(uc.host.empty());
  15521. EXPECT_EQ("/path", uc.path);
  15522. EXPECT_EQ("?q=1", uc.query);
  15523. }
  15524. {
  15525. detail::UrlComponents uc;
  15526. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  15527. EXPECT_EQ("example.com", uc.host);
  15528. EXPECT_EQ("8080", uc.port);
  15529. }
  15530. {
  15531. // Unix socket path — must not be parsed as host
  15532. detail::UrlComponents uc;
  15533. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  15534. EXPECT_TRUE(uc.host.empty());
  15535. }
  15536. {
  15537. detail::UrlComponents uc;
  15538. ASSERT_TRUE(detail::parse_url("", uc));
  15539. EXPECT_TRUE(uc.host.empty());
  15540. EXPECT_TRUE(uc.path.empty());
  15541. }
  15542. {
  15543. detail::UrlComponents uc;
  15544. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  15545. }
  15546. {
  15547. detail::UrlComponents uc;
  15548. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  15549. }
  15550. {
  15551. // Accepted by parse_url; callers restrict to http/https
  15552. detail::UrlComponents uc;
  15553. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  15554. EXPECT_EQ("ftp", uc.scheme);
  15555. }
  15556. {
  15557. detail::UrlComponents uc;
  15558. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  15559. }
  15560. {
  15561. detail::UrlComponents uc;
  15562. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  15563. }
  15564. }
  15565. TEST(ParseUrlTest, FragmentHandling) {
  15566. {
  15567. detail::UrlComponents uc;
  15568. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  15569. EXPECT_EQ("/path", uc.path);
  15570. EXPECT_TRUE(uc.query.empty());
  15571. }
  15572. {
  15573. detail::UrlComponents uc;
  15574. ASSERT_TRUE(detail::parse_url("#frag", uc));
  15575. EXPECT_TRUE(uc.path.empty());
  15576. EXPECT_TRUE(uc.query.empty());
  15577. }
  15578. }
  15579. TEST(ParseUrlTest, UserinfoHandling) {
  15580. // Userinfo with @ but no colon — host includes @
  15581. detail::UrlComponents uc;
  15582. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  15583. EXPECT_EQ("user@host.com", uc.host);
  15584. EXPECT_EQ("/path", uc.path);
  15585. }
  15586. TEST(ParseUrlTest, IPv6EdgeCases) {
  15587. {
  15588. detail::UrlComponents uc;
  15589. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  15590. EXPECT_TRUE(uc.scheme.empty());
  15591. EXPECT_EQ("::1", uc.host);
  15592. EXPECT_EQ("8080", uc.port);
  15593. }
  15594. {
  15595. // Zone ID '%25' is not in [a-fA-F0-9:]
  15596. detail::UrlComponents uc;
  15597. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  15598. }
  15599. }
  15600. TEST(ParseUrlTest, SchemeEdgeCases) {
  15601. {
  15602. detail::UrlComponents uc;
  15603. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  15604. }
  15605. {
  15606. detail::UrlComponents uc;
  15607. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  15608. }
  15609. {
  15610. detail::UrlComponents uc;
  15611. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  15612. }
  15613. }
  15614. TEST(ParseUrlTest, PortEdgeCases) {
  15615. {
  15616. detail::UrlComponents uc;
  15617. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  15618. EXPECT_TRUE(uc.port.empty());
  15619. EXPECT_EQ("/path", uc.path);
  15620. }
  15621. {
  15622. // parse_url accepts any port string; validation is done by parse_port
  15623. detail::UrlComponents uc;
  15624. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  15625. EXPECT_EQ("abc", uc.port);
  15626. }
  15627. }
  15628. TEST(ParseUrlTest, WebSocketPatterns) {
  15629. {
  15630. detail::UrlComponents uc;
  15631. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  15632. EXPECT_EQ("ws", uc.scheme);
  15633. EXPECT_EQ("echo.example.com", uc.host);
  15634. EXPECT_EQ("8080", uc.port);
  15635. EXPECT_EQ("/ws", uc.path);
  15636. }
  15637. {
  15638. detail::UrlComponents uc;
  15639. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  15640. EXPECT_EQ("wss", uc.scheme);
  15641. EXPECT_EQ("echo.example.com", uc.host);
  15642. EXPECT_TRUE(uc.port.empty());
  15643. EXPECT_EQ("/ws", uc.path);
  15644. }
  15645. }
  15646. TEST(ParseUrlTest, QueryOnly) {
  15647. detail::UrlComponents uc;
  15648. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  15649. EXPECT_TRUE(uc.host.empty());
  15650. EXPECT_TRUE(uc.path.empty());
  15651. EXPECT_EQ("?q=1&r=2", uc.query);
  15652. }
  15653. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  15654. detail::UrlComponents uc;
  15655. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  15656. EXPECT_TRUE(uc.scheme.empty());
  15657. EXPECT_EQ("example.com", uc.host);
  15658. EXPECT_EQ("443", uc.port);
  15659. EXPECT_EQ("/path", uc.path);
  15660. }
  15661. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  15662. // If ipv6 regex working, regex match codepath is taken.
  15663. // else port will default to 80 in Client impl
  15664. int clientImplMagicPort = 80;
  15665. int port = 4321;
  15666. // above ports must be different to avoid false negative
  15667. EXPECT_NE(clientImplMagicPort, port);
  15668. std::string ipV6TestURL = "http://[ff06::c3]";
  15669. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  15670. CLIENT_PRIVATE_KEY_FILE);
  15671. EXPECT_EQ(cli.port(), port);
  15672. }
  15673. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  15674. auto file_path = "./www/dir/index.html";
  15675. auto dir_path = "./www/dir";
  15676. detail::FileStat stat_file(file_path);
  15677. EXPECT_TRUE(stat_file.is_file());
  15678. EXPECT_FALSE(stat_file.is_dir());
  15679. detail::FileStat stat_dir(dir_path);
  15680. EXPECT_FALSE(stat_dir.is_file());
  15681. EXPECT_TRUE(stat_dir.is_dir());
  15682. }
  15683. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  15684. // IPv4 with default HTTP port (80)
  15685. EXPECT_EQ("example.com",
  15686. detail::make_host_and_port_string("example.com", 80, false));
  15687. // IPv4 with default HTTPS port (443)
  15688. EXPECT_EQ("example.com",
  15689. detail::make_host_and_port_string("example.com", 443, true));
  15690. // IPv4 with non-default HTTP port
  15691. EXPECT_EQ("example.com:8080",
  15692. detail::make_host_and_port_string("example.com", 8080, false));
  15693. // IPv4 with non-default HTTPS port
  15694. EXPECT_EQ("example.com:8443",
  15695. detail::make_host_and_port_string("example.com", 8443, true));
  15696. // IPv6 with default HTTP port (80)
  15697. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  15698. // IPv6 with default HTTPS port (443)
  15699. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  15700. // IPv6 with non-default HTTP port
  15701. EXPECT_EQ("[::1]:8080",
  15702. detail::make_host_and_port_string("::1", 8080, false));
  15703. // IPv6 with non-default HTTPS port
  15704. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  15705. // IPv6 full address with default port
  15706. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  15707. detail::make_host_and_port_string(
  15708. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  15709. // IPv6 full address with non-default port
  15710. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  15711. detail::make_host_and_port_string(
  15712. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  15713. // IPv6 localhost with non-default port
  15714. EXPECT_EQ("[::1]:3000",
  15715. detail::make_host_and_port_string("::1", 3000, false));
  15716. // IPv6 with zone ID (link-local address) with default port
  15717. EXPECT_EQ("[fe80::1%eth0]",
  15718. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  15719. // IPv6 with zone ID (link-local address) with non-default port
  15720. EXPECT_EQ("[fe80::1%eth0]:8080",
  15721. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  15722. // Edge case: Port 443 with is_ssl=false (should add port)
  15723. EXPECT_EQ("example.com:443",
  15724. detail::make_host_and_port_string("example.com", 443, false));
  15725. // Edge case: Port 80 with is_ssl=true (should add port)
  15726. EXPECT_EQ("example.com:80",
  15727. detail::make_host_and_port_string("example.com", 80, true));
  15728. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  15729. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  15730. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  15731. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  15732. // Security fix: Already bracketed IPv6 should not get double brackets
  15733. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  15734. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  15735. EXPECT_EQ("[::1]:8080",
  15736. detail::make_host_and_port_string("[::1]", 8080, false));
  15737. EXPECT_EQ("[2001:db8::1]:8080",
  15738. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  15739. EXPECT_EQ("[fe80::1%eth0]",
  15740. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  15741. EXPECT_EQ("[fe80::1%eth0]:8080",
  15742. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  15743. // Edge case: Empty host (should return as-is)
  15744. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  15745. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  15746. // This is a known limitation but shouldn't crash
  15747. EXPECT_EQ("[host:name]",
  15748. detail::make_host_and_port_string("host:name", 80, false));
  15749. // Port number edge cases (no validation, but should not crash)
  15750. EXPECT_EQ("example.com:0",
  15751. detail::make_host_and_port_string("example.com", 0, false));
  15752. EXPECT_EQ("example.com:-1",
  15753. detail::make_host_and_port_string("example.com", -1, false));
  15754. EXPECT_EQ("example.com:65535",
  15755. detail::make_host_and_port_string("example.com", 65535, false));
  15756. EXPECT_EQ("example.com:65536",
  15757. detail::make_host_and_port_string("example.com", 65536, false));
  15758. }
  15759. #ifdef CPPHTTPLIB_SSL_ENABLED
  15760. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  15761. httplib::SSLClient cli("roblox.com", 443);
  15762. cli.set_follow_location(true);
  15763. auto res = cli.Get("/");
  15764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15765. EXPECT_EQ(StatusCode::OK_200, res->status);
  15766. }
  15767. #endif
  15768. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  15769. Server svr;
  15770. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15771. EXPECT_EQ(res.status, 400);
  15772. });
  15773. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15774. auto se = detail::scope_exit([&] {
  15775. svr.stop();
  15776. thread.join();
  15777. ASSERT_FALSE(svr.is_running());
  15778. });
  15779. svr.wait_until_ready();
  15780. Client cli(HOST, PORT);
  15781. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  15782. }
  15783. TEST(InvalidHeaderCharsTest, is_field_name) {
  15784. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  15785. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  15786. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  15787. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  15788. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  15789. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  15790. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  15791. EXPECT_FALSE(detail::fields::is_field_name(""));
  15792. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  15793. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  15794. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  15795. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  15796. }
  15797. TEST(InvalidHeaderCharsTest, is_field_value) {
  15798. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  15799. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  15800. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  15801. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  15802. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  15803. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  15804. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  15805. EXPECT_TRUE(detail::fields::is_field_value(""));
  15806. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  15807. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  15808. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  15809. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  15810. EXPECT_TRUE(detail::fields::is_field_value("0"));
  15811. }
  15812. TEST(InvalidHeaderCharsTest, OnServer) {
  15813. Server svr;
  15814. svr.Get("/test_name", [&](const Request &req, Response &res) {
  15815. std::string header = "Not Set";
  15816. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15817. res.set_header(header, "value");
  15818. res.set_content("Page Content Page Content", "text/plain");
  15819. });
  15820. svr.Get("/test_value", [&](const Request &req, Response &res) {
  15821. std::string header = "Not Set";
  15822. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15823. res.set_header("X-Test", header);
  15824. res.set_content("Page Content Page Content", "text/plain");
  15825. });
  15826. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15827. auto se = detail::scope_exit([&] {
  15828. svr.stop();
  15829. thread.join();
  15830. ASSERT_FALSE(svr.is_running());
  15831. });
  15832. svr.wait_until_ready();
  15833. Client cli(HOST, PORT);
  15834. {
  15835. auto res = cli.Get(
  15836. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15838. EXPECT_EQ("Page Content Page Content", res->body);
  15839. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15840. }
  15841. {
  15842. auto res = cli.Get(
  15843. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15845. EXPECT_EQ("Page Content Page Content", res->body);
  15846. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15847. }
  15848. }
  15849. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  15850. auto handled = false;
  15851. Server svr;
  15852. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15853. thread t = thread([&] { svr.listen(HOST, PORT); });
  15854. auto se = detail::scope_exit([&] {
  15855. svr.stop();
  15856. t.join();
  15857. ASSERT_FALSE(svr.is_running());
  15858. ASSERT_FALSE(handled);
  15859. });
  15860. svr.wait_until_ready();
  15861. auto req = "POST /test HTTP/1.1\r\n"
  15862. "Content-Length: x\r\n"
  15863. "\r\n";
  15864. std::string response;
  15865. ASSERT_TRUE(send_request(1, req, &response));
  15866. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15867. response.substr(0, response.find("\r\n")));
  15868. }
  15869. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  15870. // case-insensitive, and a server that receives a 100-continue expectation in
  15871. // an HTTP/1.0 request MUST ignore it.
  15872. static void probe_expect(int port, const std::string &req, bool *got_100) {
  15873. std::string response;
  15874. ASSERT_TRUE(send_request(1, req, &response, port));
  15875. *got_100 = response.find("100 Continue") != std::string::npos;
  15876. }
  15877. class ExpectTokenTest : public ::testing::Test {
  15878. protected:
  15879. void SetUp() override {
  15880. svr_.Post("/p", [](const Request &, Response &res) {
  15881. res.set_content("ok", "text/plain");
  15882. });
  15883. port_ = svr_.bind_to_any_port(HOST);
  15884. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15885. svr_.wait_until_ready();
  15886. }
  15887. void TearDown() override {
  15888. svr_.stop();
  15889. if (thread_.joinable()) { thread_.join(); }
  15890. }
  15891. std::string request(const char *version, const char *expect_value) const {
  15892. return std::string("POST /p ") + version +
  15893. "\r\n"
  15894. "Host: localhost\r\n"
  15895. "Content-Length: 2\r\n"
  15896. "Connection: close\r\n"
  15897. "Expect: " +
  15898. expect_value +
  15899. "\r\n"
  15900. "\r\n"
  15901. "hi";
  15902. }
  15903. Server svr_;
  15904. int port_ = 0;
  15905. thread thread_;
  15906. };
  15907. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  15908. bool got_100 = false;
  15909. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  15910. EXPECT_TRUE(got_100);
  15911. }
  15912. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  15913. bool got_100 = true;
  15914. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  15915. EXPECT_FALSE(got_100);
  15916. }
  15917. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  15918. bool got_100 = false;
  15919. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  15920. EXPECT_TRUE(got_100);
  15921. }
  15922. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  15923. bool got_100 = false;
  15924. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  15925. EXPECT_TRUE(got_100);
  15926. }
  15927. // `100 Continue` is sent only when the server starts reading the body, so a
  15928. // request rejected before that never invites the client to send it. The
  15929. // requests below carry the expectation but withhold the body, as a client
  15930. // waiting for `100 Continue` would.
  15931. // A POST that expects `100 Continue` and withholds its two-byte body.
  15932. static std::string expect_headers_only(const std::string &path) {
  15933. return "POST " + path +
  15934. " HTTP/1.1\r\n"
  15935. "Host: localhost\r\n"
  15936. "Content-Length: 2\r\n"
  15937. "Expect: 100-continue\r\n"
  15938. "\r\n";
  15939. }
  15940. class ExpectLazyContinueTest : public ::testing::Test {
  15941. protected:
  15942. void SetUp() override {
  15943. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  15944. if (req.path == "/pre-routing") {
  15945. res.status = StatusCode::Unauthorized_401;
  15946. return Server::HandlerResponse::Handled;
  15947. }
  15948. return Server::HandlerResponse::Unhandled;
  15949. });
  15950. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  15951. if (req.matched_route == "/pre-request") {
  15952. res.status = StatusCode::Forbidden_403;
  15953. return Server::HandlerResponse::Handled;
  15954. }
  15955. return Server::HandlerResponse::Unhandled;
  15956. });
  15957. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  15958. res.set_content("ok", "text/plain");
  15959. });
  15960. svr_.Post("/pre-request", [](const Request &, Response &res) {
  15961. res.set_content("ok", "text/plain");
  15962. });
  15963. svr_.Post("/reader-used", [](const Request &, Response &res,
  15964. const ContentReader &content_reader) {
  15965. std::string body;
  15966. content_reader([&](const char *data, size_t len) {
  15967. body.append(data, len);
  15968. return true;
  15969. });
  15970. res.set_content(body, "text/plain");
  15971. });
  15972. svr_.Post("/reader-unused",
  15973. [](const Request &, Response &res, const ContentReader &) {
  15974. res.set_content("ignored", "text/plain");
  15975. });
  15976. port_ = svr_.bind_to_any_port(HOST);
  15977. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15978. svr_.wait_until_ready();
  15979. }
  15980. void TearDown() override {
  15981. svr_.stop();
  15982. if (thread_.joinable()) { thread_.join(); }
  15983. }
  15984. // Sends `req` and reads until the server closes the connection. Returns
  15985. // false if the read had to wait for the client-side timeout instead.
  15986. bool send_until_closed(const std::string &req, std::string *resp) const {
  15987. auto start = std::chrono::steady_clock::now();
  15988. if (!send_request(3, req, resp, port_)) { return false; }
  15989. auto elapsed = std::chrono::steady_clock::now() - start;
  15990. return elapsed < std::chrono::seconds(2);
  15991. }
  15992. // The final response comes without `100 Continue`, and the server closes
  15993. // the connection since the body may or may not follow.
  15994. void expect_final_without_interim(const std::string &path,
  15995. const char *status_line) const {
  15996. std::string resp;
  15997. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  15998. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  15999. EXPECT_EQ(0u, resp.find(status_line));
  16000. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16001. }
  16002. Server svr_;
  16003. int port_ = 0;
  16004. thread thread_;
  16005. };
  16006. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16007. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16008. }
  16009. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16010. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16011. }
  16012. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16013. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16014. }
  16015. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16016. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16017. }
  16018. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16019. // The body follows once `100 Continue` has had time to arrive.
  16020. auto req = expect_headers_only("/reader-used");
  16021. req.insert(req.size() - 2, "Connection: close\r\n");
  16022. std::string resp;
  16023. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16024. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  16025. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  16026. EXPECT_NE(std::string::npos, resp.find("hi"));
  16027. }
  16028. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  16029. // Large enough for the client to add `Expect: 100-continue` itself.
  16030. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  16031. std::atomic<bool> body_sent{false};
  16032. Client cli(HOST, port_);
  16033. auto res = cli.Post(
  16034. "/pre-request", length,
  16035. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  16036. body_sent = true;
  16037. std::string chunk(len, 'x');
  16038. sink.write(chunk.data(), chunk.size());
  16039. return true;
  16040. },
  16041. "application/octet-stream");
  16042. ASSERT_TRUE(res);
  16043. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16044. EXPECT_FALSE(body_sent);
  16045. }
  16046. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16047. Server svr;
  16048. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16049. return StatusCode::ExpectationFailed_417;
  16050. });
  16051. svr.Post("/p", [](const Request &, Response &res) {
  16052. res.set_content("ok", "text/plain");
  16053. });
  16054. auto port = svr.bind_to_any_port(HOST);
  16055. thread t = thread([&] { svr.listen_after_bind(); });
  16056. auto se = detail::scope_exit([&] {
  16057. svr.stop();
  16058. t.join();
  16059. });
  16060. svr.wait_until_ready();
  16061. std::string resp;
  16062. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16063. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16064. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16065. // Exactly one response: the route handler must not run after the 417.
  16066. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16067. }
  16068. #ifndef _WIN32
  16069. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16070. static constexpr char reject[] = "Unauthorized";
  16071. static constexpr char accept[] = "Upload accepted";
  16072. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  16073. Server svr;
  16074. svr.set_expect_100_continue_handler(
  16075. [](const Request & /*req*/, Response &res) {
  16076. res.status = StatusCode::Unauthorized_401;
  16077. res.set_content(reject, "text/plain");
  16078. return res.status;
  16079. });
  16080. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  16081. res.set_content(accept, "text/plain");
  16082. });
  16083. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16084. auto se = detail::scope_exit([&] {
  16085. svr.stop();
  16086. thread.join();
  16087. ASSERT_FALSE(svr.is_running());
  16088. });
  16089. svr.wait_until_ready();
  16090. {
  16091. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  16092. curl_easy_init(), &curl_easy_cleanup};
  16093. ASSERT_NE(curl, nullptr);
  16094. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  16095. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  16096. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  16097. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  16098. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  16099. &curl_slist_free_all};
  16100. ASSERT_NE(list, nullptr);
  16101. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  16102. struct read_data {
  16103. size_t read_size;
  16104. size_t total_size;
  16105. } data = {0, total_size};
  16106. using read_callback_t =
  16107. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16108. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  16109. void *userdata) -> size_t {
  16110. read_data *d = (read_data *)userdata;
  16111. if (!userdata || d->read_size >= d->total_size) { return 0; }
  16112. std::fill_n(ptr, size * nmemb, 'A');
  16113. d->read_size += size * nmemb;
  16114. return size * nmemb;
  16115. };
  16116. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  16117. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  16118. std::vector<char> buffer;
  16119. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  16120. using write_callback_t =
  16121. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16122. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  16123. void *userdata) -> size_t {
  16124. std::vector<char> *buf = (std::vector<char> *)userdata;
  16125. buf->reserve(buf->size() + size * nmemb + 1);
  16126. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  16127. return size * nmemb;
  16128. };
  16129. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  16130. {
  16131. const auto res = curl_easy_perform(curl.get());
  16132. ASSERT_EQ(res, CURLE_OK);
  16133. }
  16134. {
  16135. auto response_code = long{};
  16136. const auto res =
  16137. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  16138. ASSERT_EQ(res, CURLE_OK);
  16139. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  16140. }
  16141. {
  16142. auto dl = curl_off_t{};
  16143. const auto res =
  16144. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  16145. ASSERT_EQ(res, CURLE_OK);
  16146. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  16147. }
  16148. {
  16149. buffer.push_back('\0');
  16150. ASSERT_STRCASEEQ(buffer.data(), reject);
  16151. }
  16152. }
  16153. }
  16154. #endif
  16155. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  16156. // Regression test for #2458.
  16157. //
  16158. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  16159. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  16160. // ticket can make the client socket spuriously readable during the
  16161. // 100-continue wait. If the readiness is mistaken for an incoming response,
  16162. // the client withholds the body and then blocks reading a response that never
  16163. // comes, failing with `Failed to read connection`.
  16164. //
  16165. // A correct client (like curl) sends the body once no `100 Continue` arrives
  16166. // within the timeout. This raw OpenSSL server deliberately never sends
  16167. // `100 Continue`; the client must still deliver the body and receive 200.
  16168. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  16169. signal(SIGPIPE, SIG_IGN);
  16170. const auto port = PORT + 4;
  16171. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16172. ASSERT_NE(srv, INVALID_SOCKET);
  16173. int opt = 1;
  16174. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  16175. sockaddr_in addr{};
  16176. addr.sin_family = AF_INET;
  16177. addr.sin_port = htons(static_cast<uint16_t>(port));
  16178. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16179. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16180. ASSERT_EQ(0, ::listen(srv, 1));
  16181. std::atomic<size_t> server_body_bytes{0};
  16182. auto server_thread = std::thread([&] {
  16183. sockaddr_in cli_addr{};
  16184. socklen_t cli_len = sizeof(cli_addr);
  16185. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16186. if (cli == INVALID_SOCKET) { return; }
  16187. // Bound the lifetime of the server side so a buggy client (which never
  16188. // sends the body) cannot make this thread block forever on join.
  16189. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  16190. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16191. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  16192. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  16193. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  16194. SSL *ssl = SSL_new(ctx);
  16195. SSL_set_fd(ssl, static_cast<int>(cli));
  16196. if (SSL_accept(ssl) > 0) {
  16197. // Read the request headers. Reading here also flushes the TLS 1.3
  16198. // session tickets to the client. Deliberately do NOT send
  16199. // `100 Continue`.
  16200. std::string buf;
  16201. char tmp[1024];
  16202. while (buf.find("\r\n\r\n") == std::string::npos) {
  16203. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16204. if (n <= 0) { break; }
  16205. buf.append(tmp, static_cast<size_t>(n));
  16206. }
  16207. // A correct client sends the body now; count what arrives.
  16208. auto pos = buf.find("\r\n\r\n");
  16209. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  16210. while (body < 4096) {
  16211. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16212. if (n <= 0) { break; }
  16213. body += static_cast<size_t>(n);
  16214. }
  16215. server_body_bytes = body;
  16216. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  16217. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  16218. SSL_shutdown(ssl);
  16219. }
  16220. SSL_free(ssl);
  16221. detail::close_socket(cli);
  16222. SSL_CTX_free(ctx);
  16223. });
  16224. auto se = detail::scope_exit([&] {
  16225. server_thread.join();
  16226. detail::close_socket(srv);
  16227. });
  16228. SSLClient cli("127.0.0.1", port);
  16229. cli.enable_server_certificate_verification(false);
  16230. cli.set_connection_timeout(5, 0);
  16231. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  16232. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  16233. std::string body(4096, 'A');
  16234. auto res = cli.Put("/api/test", body, "application/json");
  16235. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  16236. EXPECT_EQ(StatusCode::OK_200, res->status);
  16237. EXPECT_EQ(body.size(), server_body_bytes.load());
  16238. }
  16239. #endif
  16240. template <typename S, typename C>
  16241. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  16242. svr.Get("/stream", [&](const Request &, Response &res) {
  16243. auto data = new std::string("01234567890123456789");
  16244. res.set_content_provider(
  16245. data->size(), "text/plain",
  16246. [&, data](size_t offset, size_t length, DataSink &sink) {
  16247. const size_t DATA_CHUNK_SIZE = 4;
  16248. const auto &d = *data;
  16249. std::this_thread::sleep_for(std::chrono::seconds(1));
  16250. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  16251. return true;
  16252. },
  16253. [data](bool success) {
  16254. EXPECT_FALSE(success);
  16255. delete data;
  16256. });
  16257. });
  16258. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  16259. auto i = new size_t(0);
  16260. res.set_content_provider(
  16261. "text/plain",
  16262. [i](size_t, DataSink &sink) {
  16263. if (*i < 5) {
  16264. std::this_thread::sleep_for(std::chrono::seconds(1));
  16265. sink.write("abcd", 4);
  16266. (*i)++;
  16267. } else {
  16268. sink.done();
  16269. }
  16270. return true;
  16271. },
  16272. [i](bool success) {
  16273. EXPECT_FALSE(success);
  16274. delete i;
  16275. });
  16276. });
  16277. svr.Get("/chunked", [&](const Request &, Response &res) {
  16278. auto i = new size_t(0);
  16279. res.set_chunked_content_provider(
  16280. "text/plain",
  16281. [i](size_t, DataSink &sink) {
  16282. if (*i < 5) {
  16283. std::this_thread::sleep_for(std::chrono::seconds(1));
  16284. sink.os << "abcd";
  16285. (*i)++;
  16286. } else {
  16287. sink.done();
  16288. }
  16289. return true;
  16290. },
  16291. [i](bool success) {
  16292. EXPECT_FALSE(success);
  16293. delete i;
  16294. });
  16295. });
  16296. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16297. auto se = detail::scope_exit([&] {
  16298. svr.stop();
  16299. listen_thread.join();
  16300. ASSERT_FALSE(svr.is_running());
  16301. });
  16302. svr.wait_until_ready();
  16303. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  16304. {
  16305. auto start = std::chrono::steady_clock::now();
  16306. auto res = cli.Get("/stream");
  16307. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16308. std::chrono::steady_clock::now() - start)
  16309. .count();
  16310. ASSERT_FALSE(res);
  16311. EXPECT_EQ(Error::Read, res.error());
  16312. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16313. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16314. }
  16315. {
  16316. auto start = std::chrono::steady_clock::now();
  16317. auto res = cli.Get("/stream_without_length");
  16318. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16319. std::chrono::steady_clock::now() - start)
  16320. .count();
  16321. ASSERT_FALSE(res);
  16322. EXPECT_EQ(Error::Read, res.error());
  16323. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16324. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16325. }
  16326. {
  16327. auto start = std::chrono::steady_clock::now();
  16328. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  16329. EXPECT_EQ("abcd", string(data, data_length));
  16330. return true;
  16331. });
  16332. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16333. std::chrono::steady_clock::now() - start)
  16334. .count();
  16335. ASSERT_FALSE(res);
  16336. EXPECT_EQ(Error::Read, res.error());
  16337. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16338. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16339. }
  16340. }
  16341. TEST(MaxTimeoutTest, ContentStream) {
  16342. time_t timeout = 2000;
  16343. time_t threshold = 200;
  16344. Server svr;
  16345. Client cli("localhost", PORT);
  16346. max_timeout_test(svr, cli, timeout, threshold);
  16347. }
  16348. #ifdef CPPHTTPLIB_SSL_ENABLED
  16349. TEST(MaxTimeoutTest, ContentStreamSSL) {
  16350. time_t timeout = 2000;
  16351. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  16352. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16353. SSLClient cli("localhost", PORT);
  16354. cli.enable_server_certificate_verification(false);
  16355. max_timeout_test(svr, cli, timeout, threshold);
  16356. }
  16357. #endif
  16358. class EventDispatcher {
  16359. public:
  16360. EventDispatcher() {}
  16361. bool wait_event(DataSink *sink) {
  16362. unique_lock<mutex> lk(m_);
  16363. int id = id_;
  16364. // Wait with timeout to prevent hanging if client disconnects
  16365. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  16366. [&] { return cid_ == id; })) {
  16367. return false; // Timeout occurred
  16368. }
  16369. sink->write(message_.data(), message_.size());
  16370. return true;
  16371. }
  16372. void send_event(const string &message) {
  16373. lock_guard<mutex> lk(m_);
  16374. cid_ = id_++;
  16375. message_ = message;
  16376. cv_.notify_all();
  16377. }
  16378. private:
  16379. mutex m_;
  16380. condition_variable cv_;
  16381. atomic_int id_{0};
  16382. atomic_int cid_{-1};
  16383. string message_;
  16384. };
  16385. TEST(ClientInThreadTest, Issue2068) {
  16386. EventDispatcher ed;
  16387. Server svr;
  16388. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  16389. res.set_chunked_content_provider("text/event-stream",
  16390. [&](size_t /*offset*/, DataSink &sink) {
  16391. return ed.wait_event(&sink);
  16392. });
  16393. });
  16394. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  16395. svr.wait_until_ready();
  16396. thread event_thread([&] {
  16397. int id = 0;
  16398. while (svr.is_running()) {
  16399. this_thread::sleep_for(chrono::milliseconds(500));
  16400. std::stringstream ss;
  16401. ss << "data: " << id << "\n\n";
  16402. ed.send_event(ss.str());
  16403. id++;
  16404. }
  16405. });
  16406. auto se = detail::scope_exit([&] {
  16407. svr.stop();
  16408. listen_thread.join();
  16409. event_thread.join();
  16410. ASSERT_FALSE(svr.is_running());
  16411. });
  16412. {
  16413. auto client = detail::make_unique<Client>(HOST, PORT);
  16414. client->set_read_timeout(std::chrono::minutes(10));
  16415. std::atomic<bool> stop{false};
  16416. std::thread t([&] {
  16417. client->Get("/event1",
  16418. [&](const char *, size_t) -> bool { return !stop; });
  16419. });
  16420. std::this_thread::sleep_for(std::chrono::seconds(2));
  16421. stop = true;
  16422. client->stop();
  16423. t.join();
  16424. // Reset client after thread has finished
  16425. client.reset();
  16426. }
  16427. }
  16428. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  16429. auto handled = false;
  16430. Server svr;
  16431. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16432. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16433. auto se = detail::scope_exit([&] {
  16434. svr.stop();
  16435. t.join();
  16436. ASSERT_FALSE(svr.is_running());
  16437. ASSERT_FALSE(handled);
  16438. });
  16439. svr.wait_until_ready();
  16440. // Two Content-Length headers with different values — must be rejected
  16441. auto req = "POST /test HTTP/1.1\r\n"
  16442. "Content-Length: 5\r\n"
  16443. "Content-Length: 10\r\n"
  16444. "\r\n"
  16445. "hello";
  16446. std::string response;
  16447. ASSERT_TRUE(send_request(1, req, &response));
  16448. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16449. response.substr(0, response.find("\r\n")));
  16450. }
  16451. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  16452. auto handled = false;
  16453. Server svr;
  16454. svr.Post("/test", [&](const Request &, Response &res) {
  16455. handled = true;
  16456. res.set_content("ok", "text/plain");
  16457. });
  16458. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16459. auto se = detail::scope_exit([&] {
  16460. svr.stop();
  16461. t.join();
  16462. ASSERT_FALSE(svr.is_running());
  16463. ASSERT_TRUE(handled);
  16464. });
  16465. svr.wait_until_ready();
  16466. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  16467. auto req = "POST /test HTTP/1.1\r\n"
  16468. "Content-Length: 5\r\n"
  16469. "Content-Length: 5\r\n"
  16470. "\r\n"
  16471. "hello";
  16472. std::string response;
  16473. ASSERT_TRUE(send_request(1, req, &response));
  16474. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  16475. }
  16476. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  16477. Server svr;
  16478. svr.Get("/", [](const Request &req, Response &res) {
  16479. EXPECT_EQ(2U, req.trailers.size());
  16480. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  16481. // Denied
  16482. EXPECT_FALSE(req.has_trailer("Content-Length"));
  16483. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  16484. // Accepted
  16485. EXPECT_TRUE(req.has_trailer("X-Hello"));
  16486. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  16487. EXPECT_TRUE(req.has_trailer("X-World"));
  16488. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  16489. res.set_content("ok", "text/plain");
  16490. });
  16491. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16492. auto se = detail::scope_exit([&] {
  16493. svr.stop();
  16494. t.join();
  16495. ASSERT_FALSE(svr.is_running());
  16496. });
  16497. svr.wait_until_ready();
  16498. const std::string req = "GET / HTTP/1.1\r\n"
  16499. "Transfer-Encoding: chunked\r\n"
  16500. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  16501. "\r\n"
  16502. "0\r\n"
  16503. "Content-Length: 10\r\n"
  16504. "Host: internal.local\r\n"
  16505. "Content-Type: malicious/content\r\n"
  16506. "Cookie: any\r\n"
  16507. "Set-Cookie: any\r\n"
  16508. "X-Forwarded-For: attacker.com\r\n"
  16509. "X-Real-Ip: 1.1.1.1\r\n"
  16510. "X-Hello: hello\r\n"
  16511. "X-World: world\r\n"
  16512. "\r\n";
  16513. std::string res;
  16514. ASSERT_TRUE(send_request(1, req, &res));
  16515. }
  16516. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  16517. // several field lines, and the combined value is what has to be parsed. A
  16518. // Trailer field split across lines therefore declares every name it lists;
  16519. // reading only the first line silently drops the trailers the later lines
  16520. // declare. The prohibited-trailer filter still applies to every line.
  16521. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  16522. Server svr;
  16523. size_t observed_trailer_count = 0;
  16524. std::string observed_hello;
  16525. std::string observed_world;
  16526. bool observed_content_length = true;
  16527. svr.Get("/", [&](const Request &req, Response &res) {
  16528. observed_trailer_count = req.trailers.size();
  16529. observed_hello = req.get_trailer_value("X-Hello");
  16530. observed_world = req.get_trailer_value("X-World");
  16531. observed_content_length = req.has_trailer("Content-Length");
  16532. res.set_content("ok", "text/plain");
  16533. });
  16534. auto port = svr.bind_to_any_port(HOST);
  16535. thread t = thread([&]() { svr.listen_after_bind(); });
  16536. auto se = detail::scope_exit([&] {
  16537. svr.stop();
  16538. t.join();
  16539. ASSERT_FALSE(svr.is_running());
  16540. });
  16541. svr.wait_until_ready();
  16542. const std::string req = "GET / HTTP/1.1\r\n"
  16543. "Transfer-Encoding: chunked\r\n"
  16544. "Trailer: X-Hello\r\n"
  16545. "Trailer: X-World, Content-Length\r\n"
  16546. "\r\n"
  16547. "0\r\n"
  16548. "X-Hello: hello\r\n"
  16549. "X-World: world\r\n"
  16550. "Content-Length: 10\r\n"
  16551. "\r\n";
  16552. std::string res;
  16553. ASSERT_TRUE(send_request(1, req, &res, port));
  16554. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  16555. // Accepted: both field lines contribute to the declared set
  16556. EXPECT_EQ(2U, observed_trailer_count);
  16557. EXPECT_EQ(observed_hello, "hello");
  16558. EXPECT_EQ(observed_world, "world");
  16559. // Denied: a prohibited name stays prohibited on a later field line
  16560. EXPECT_FALSE(observed_content_length);
  16561. }
  16562. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  16563. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  16564. // unbounded run of fields that are never declared, because the counter would
  16565. // only advance for declared fields.
  16566. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  16567. Server svr;
  16568. bool handler_called = false;
  16569. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  16570. handler_called = true;
  16571. res.set_content("ok", "text/plain");
  16572. });
  16573. auto port = svr.bind_to_any_port(HOST);
  16574. thread t = thread([&]() { svr.listen_after_bind(); });
  16575. auto se = detail::scope_exit([&] {
  16576. svr.stop();
  16577. t.join();
  16578. ASSERT_FALSE(svr.is_running());
  16579. });
  16580. svr.wait_until_ready();
  16581. // Declare nothing, then send far more undeclared trailer fields than the
  16582. // header-count limit. Parsing must stop and reject the request rather than
  16583. // read every line.
  16584. std::string req = "GET / HTTP/1.1\r\n"
  16585. "Transfer-Encoding: chunked\r\n"
  16586. "\r\n"
  16587. "0\r\n";
  16588. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  16589. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  16590. }
  16591. req += "\r\n";
  16592. std::string res;
  16593. ASSERT_TRUE(send_request(1, req, &res, port));
  16594. // The request is rejected before the handler runs.
  16595. EXPECT_FALSE(handler_called);
  16596. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  16597. }
  16598. // The set of declared trailer names is capped so a peer cannot grow it without
  16599. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  16600. // declared past the cap is not honored, even if the field is actually sent.
  16601. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  16602. Server svr;
  16603. // One name inside the cap and one past it, so the test tracks the cap rather
  16604. // than a fixed count.
  16605. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  16606. const std::string within_cap_name = "X-T-0";
  16607. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  16608. bool observed_within_cap = false;
  16609. bool observed_past_cap = false;
  16610. svr.Get("/", [&](const Request &req, Response &res) {
  16611. observed_within_cap = req.has_trailer(within_cap_name);
  16612. observed_past_cap = req.has_trailer(past_cap_name);
  16613. res.set_content("ok", "text/plain");
  16614. });
  16615. auto port = svr.bind_to_any_port(HOST);
  16616. thread t = thread([&]() { svr.listen_after_bind(); });
  16617. auto se = detail::scope_exit([&] {
  16618. svr.stop();
  16619. t.join();
  16620. ASSERT_FALSE(svr.is_running());
  16621. });
  16622. svr.wait_until_ready();
  16623. // Declare more trailer names than the cap in a single Trailer field, then
  16624. // actually send the first (within the cap) and the last (past it).
  16625. std::string trailer_decl = "Trailer: ";
  16626. for (int i = 0; i < declared_count; i++) {
  16627. if (i != 0) { trailer_decl += ", "; }
  16628. trailer_decl += "X-T-" + std::to_string(i);
  16629. }
  16630. trailer_decl += "\r\n";
  16631. const std::string req = "GET / HTTP/1.1\r\n"
  16632. "Transfer-Encoding: chunked\r\n" +
  16633. trailer_decl +
  16634. "\r\n"
  16635. "0\r\n" +
  16636. within_cap_name + ": a\r\n" + past_cap_name +
  16637. ": b\r\n"
  16638. "\r\n";
  16639. std::string res;
  16640. ASSERT_TRUE(send_request(1, req, &res, port));
  16641. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  16642. // A name within the cap is honored; one declared past the cap is dropped.
  16643. EXPECT_TRUE(observed_within_cap);
  16644. EXPECT_FALSE(observed_past_cap);
  16645. }
  16646. // A direct client that is not listed in trusted_proxies must not be able to
  16647. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  16648. // the peer address on the actual TCP connection determines whether the
  16649. // header is honored.
  16650. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  16651. Server svr;
  16652. // Deliberately does NOT include the loopback address the test client
  16653. // actually connects from, so the direct connection is not a trusted proxy.
  16654. svr.set_trusted_proxies({"203.0.113.66"});
  16655. std::string observed_remote_addr;
  16656. svr.Get("/ip", [&](const Request &req, Response &res) {
  16657. observed_remote_addr = req.remote_addr;
  16658. res.set_content("ok", "text/plain");
  16659. });
  16660. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16661. auto se = detail::scope_exit([&] {
  16662. svr.stop();
  16663. t.join();
  16664. ASSERT_FALSE(svr.is_running());
  16665. });
  16666. svr.wait_until_ready();
  16667. Client cli(HOST, PORT);
  16668. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  16669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16670. EXPECT_EQ(StatusCode::OK_200, res->status);
  16671. // The connecting peer is not a trusted proxy, so the spoofed header must be
  16672. // ignored entirely and the real connection-level address retained.
  16673. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16674. observed_remote_addr == "127.0.0.1");
  16675. }
  16676. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  16677. Server svr;
  16678. std::string observed_remote_addr;
  16679. std::string observed_xff;
  16680. svr.Get("/ip", [&](const Request &req, Response &res) {
  16681. observed_remote_addr = req.remote_addr;
  16682. observed_xff = req.get_header_value("X-Forwarded-For");
  16683. res.set_content("ok", "text/plain");
  16684. });
  16685. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16686. auto se = detail::scope_exit([&] {
  16687. svr.stop();
  16688. t.join();
  16689. ASSERT_FALSE(svr.is_running());
  16690. });
  16691. svr.wait_until_ready();
  16692. Client cli(HOST, PORT);
  16693. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  16694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16695. EXPECT_EQ(StatusCode::OK_200, res->status);
  16696. EXPECT_EQ(observed_xff, "203.0.113.66");
  16697. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16698. observed_remote_addr == "127.0.0.1");
  16699. }
  16700. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  16701. Server svr;
  16702. svr.set_trusted_proxies({"203.0.113.66"});
  16703. std::string observed_remote_addr;
  16704. std::string observed_xff;
  16705. svr.Get("/ip", [&](const Request &req, Response &res) {
  16706. observed_remote_addr = req.remote_addr;
  16707. observed_xff = req.get_header_value("X-Forwarded-For");
  16708. res.set_content("ok", "text/plain");
  16709. });
  16710. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16711. auto se = detail::scope_exit([&] {
  16712. svr.stop();
  16713. t.join();
  16714. ASSERT_FALSE(svr.is_running());
  16715. });
  16716. svr.wait_until_ready();
  16717. Client cli(HOST, PORT);
  16718. auto res = cli.Get("/ip");
  16719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16720. EXPECT_EQ(StatusCode::OK_200, res->status);
  16721. EXPECT_EQ(observed_xff, "");
  16722. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16723. observed_remote_addr == "127.0.0.1");
  16724. }
  16725. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  16726. Server svr;
  16727. // Include the loopback address the test client actually connects from, so
  16728. // the direct connection itself is recognized as the trusted proxy hop.
  16729. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  16730. std::string observed_remote_addr;
  16731. std::string observed_xff;
  16732. svr.Get("/ip", [&](const Request &req, Response &res) {
  16733. observed_remote_addr = req.remote_addr;
  16734. observed_xff = req.get_header_value("X-Forwarded-For");
  16735. res.set_content("ok", "text/plain");
  16736. });
  16737. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16738. auto se = detail::scope_exit([&] {
  16739. svr.stop();
  16740. t.join();
  16741. ASSERT_FALSE(svr.is_running());
  16742. });
  16743. svr.wait_until_ready();
  16744. Client cli(HOST, PORT);
  16745. auto res = cli.Get(
  16746. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  16747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16748. EXPECT_EQ(StatusCode::OK_200, res->status);
  16749. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  16750. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16751. }
  16752. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  16753. Server svr;
  16754. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  16755. std::string observed_remote_addr;
  16756. std::string observed_xff;
  16757. svr.Get("/ip", [&](const Request &req, Response &res) {
  16758. observed_remote_addr = req.remote_addr;
  16759. observed_xff = req.get_header_value("X-Forwarded-For");
  16760. res.set_content("ok", "text/plain");
  16761. });
  16762. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16763. auto se = detail::scope_exit([&] {
  16764. svr.stop();
  16765. t.join();
  16766. ASSERT_FALSE(svr.is_running());
  16767. });
  16768. svr.wait_until_ready();
  16769. Client cli(HOST, PORT);
  16770. auto res = cli.Get(
  16771. "/ip",
  16772. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16774. EXPECT_EQ(StatusCode::OK_200, res->status);
  16775. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16776. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16777. }
  16778. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  16779. Server svr;
  16780. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16781. std::string observed_remote_addr;
  16782. std::string observed_xff;
  16783. svr.Get("/ip", [&](const Request &req, Response &res) {
  16784. observed_remote_addr = req.remote_addr;
  16785. observed_xff = req.get_header_value("X-Forwarded-For");
  16786. res.set_content("ok", "text/plain");
  16787. });
  16788. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16789. auto se = detail::scope_exit([&] {
  16790. svr.stop();
  16791. t.join();
  16792. ASSERT_FALSE(svr.is_running());
  16793. });
  16794. svr.wait_until_ready();
  16795. Client cli(HOST, PORT);
  16796. auto res = cli.Get(
  16797. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  16798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16799. EXPECT_EQ(StatusCode::OK_200, res->status);
  16800. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  16801. // by the closest hop) is used. The leftmost entry is fully client-controlled
  16802. // and must not be selected.
  16803. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  16804. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  16805. }
  16806. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  16807. Server svr;
  16808. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  16809. std::string observed_remote_addr;
  16810. svr.Get("/ip", [&](const Request &req, Response &res) {
  16811. observed_remote_addr = req.remote_addr;
  16812. res.set_content("ok", "text/plain");
  16813. });
  16814. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16815. auto se = detail::scope_exit([&] {
  16816. svr.stop();
  16817. t.join();
  16818. ASSERT_FALSE(svr.is_running());
  16819. });
  16820. svr.wait_until_ready();
  16821. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  16822. // a forged address and the trusted proxy's own address; the forged value must
  16823. // not win over the address the trusted proxy actually recorded.
  16824. Client cli(HOST, PORT);
  16825. auto res = cli.Get(
  16826. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  16827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16828. EXPECT_EQ(StatusCode::OK_200, res->status);
  16829. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  16830. }
  16831. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  16832. Server svr;
  16833. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16834. std::string observed_remote_addr;
  16835. std::string observed_xff;
  16836. svr.Get("/ip", [&](const Request &req, Response &res) {
  16837. observed_remote_addr = req.remote_addr;
  16838. observed_xff = req.get_header_value("X-Forwarded-For");
  16839. res.set_content("ok", "text/plain");
  16840. });
  16841. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16842. auto se = detail::scope_exit([&] {
  16843. svr.stop();
  16844. t.join();
  16845. ASSERT_FALSE(svr.is_running());
  16846. });
  16847. svr.wait_until_ready();
  16848. Client cli(HOST, PORT);
  16849. auto res = cli.Get(
  16850. "/ip",
  16851. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16853. EXPECT_EQ(StatusCode::OK_200, res->status);
  16854. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16855. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16856. }
  16857. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  16858. Server svr;
  16859. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16860. std::string observed_remote_addr;
  16861. std::string observed_xff;
  16862. svr.Get("/ip", [&](const Request &req, Response &res) {
  16863. observed_remote_addr = req.remote_addr;
  16864. observed_xff = req.get_header_value("X-Forwarded-For");
  16865. res.set_content("ok", "text/plain");
  16866. });
  16867. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16868. auto se = detail::scope_exit([&] {
  16869. svr.stop();
  16870. t.join();
  16871. ASSERT_FALSE(svr.is_running());
  16872. });
  16873. svr.wait_until_ready();
  16874. std::string raw_req =
  16875. "GET /ip HTTP/1.1\r\n"
  16876. "Host: localhost\r\n"
  16877. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  16878. "Connection: close\r\n"
  16879. "\r\n";
  16880. std::string out;
  16881. ASSERT_TRUE(send_request(5, raw_req, &out));
  16882. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16883. // Header parser trims surrounding whitespace of the header value
  16884. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  16885. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16886. }
  16887. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  16888. // one comma-joined value, in the order received. Proxies such as HAProxy append
  16889. // their own X-Forwarded-For as a separate field line rather than extending the
  16890. // one the client sent, so every occurrence has to be taken into account.
  16891. // Reading only the first one hands back the address the client chose.
  16892. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  16893. Server svr;
  16894. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16895. std::string observed_remote_addr;
  16896. size_t observed_xff_count = 0;
  16897. svr.Get("/ip", [&](const Request &req, Response &res) {
  16898. observed_remote_addr = req.remote_addr;
  16899. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  16900. res.set_content("ok", "text/plain");
  16901. });
  16902. auto port = svr.bind_to_any_port(HOST);
  16903. thread t = thread([&]() { svr.listen_after_bind(); });
  16904. auto se = detail::scope_exit([&] {
  16905. svr.stop();
  16906. t.join();
  16907. ASSERT_FALSE(svr.is_running());
  16908. });
  16909. svr.wait_until_ready();
  16910. // The client supplies the first field line; the trusted proxy appends the
  16911. // address it observed as a second one.
  16912. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  16913. "Host: localhost\r\n"
  16914. "X-Forwarded-For: 1.2.3.4\r\n"
  16915. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  16916. "Connection: close\r\n"
  16917. "\r\n";
  16918. std::string out;
  16919. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16920. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16921. EXPECT_EQ(observed_xff_count, 2U);
  16922. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16923. // The same chain spread over one field line per hop derives the same client
  16924. // address, i.e. the split and the comma-joined representations agree.
  16925. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  16926. "Host: localhost\r\n"
  16927. "X-Forwarded-For: 1.2.3.4\r\n"
  16928. "X-Forwarded-For: 198.51.100.23\r\n"
  16929. "X-Forwarded-For: 192.0.2.45\r\n"
  16930. "Connection: close\r\n"
  16931. "\r\n";
  16932. out.clear();
  16933. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  16934. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16935. EXPECT_EQ(observed_xff_count, 3U);
  16936. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16937. }
  16938. // An X-Forwarded-For header whose value parses to zero IP segments must not
  16939. // crash the server (it used to call front() on an empty vector inside
  16940. // get_client_ip). The connection-level remote address must be retained instead.
  16941. static void run_malformed_xff_test(const std::string &xff_value) {
  16942. Server svr;
  16943. svr.set_trusted_proxies({"192.0.2.45"});
  16944. std::string observed_remote_addr;
  16945. svr.Get("/ip", [&](const Request &req, Response &res) {
  16946. observed_remote_addr = req.remote_addr;
  16947. res.set_content("ok", "text/plain");
  16948. });
  16949. int port = 0;
  16950. thread t = thread([&]() {
  16951. port = svr.bind_to_any_port(HOST);
  16952. svr.listen_after_bind();
  16953. });
  16954. auto se = detail::scope_exit([&] {
  16955. svr.stop();
  16956. t.join();
  16957. ASSERT_FALSE(svr.is_running());
  16958. });
  16959. svr.wait_until_ready();
  16960. Client cli(HOST, port);
  16961. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  16962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16963. EXPECT_EQ(StatusCode::OK_200, res->status);
  16964. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16965. observed_remote_addr == "127.0.0.1");
  16966. }
  16967. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  16968. run_malformed_xff_test("");
  16969. }
  16970. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  16971. run_malformed_xff_test(",");
  16972. }
  16973. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  16974. run_malformed_xff_test(", , ,");
  16975. }
  16976. // The same rule applies to Accept: a request whose acceptable types are spread
  16977. // over several field lines must be negotiated against all of them.
  16978. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  16979. // case-insensitive connection options. Comparing the whole field value against
  16980. // one option misses a client that sends several of them, and misses every
  16981. // casing but the one written in the comparison.
  16982. //
  16983. // Sends req, reads the response, then reuses the same socket for a second
  16984. // request to find out whether the server kept the connection.
  16985. static void probe_connection_reuse(int port, const std::string &req,
  16986. bool *announced_close, bool *reusable) {
  16987. auto error = Error::Success;
  16988. auto sock = detail::create_client_socket(
  16989. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16990. /*connection_timeout_sec=*/5, 0,
  16991. /*read_timeout_sec=*/1, 0,
  16992. /*write_timeout_sec=*/5, 0, std::string(), error);
  16993. ASSERT_NE(sock, INVALID_SOCKET);
  16994. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  16995. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  16996. "Host: localhost\r\n"
  16997. "Connection: close\r\n"
  16998. "\r\n";
  16999. std::string first_response;
  17000. std::string second_response;
  17001. detail::process_client_socket(
  17002. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  17003. [&](Stream &strm) {
  17004. if (strm.write(req.data(), req.size()) !=
  17005. static_cast<ssize_t>(req.size())) {
  17006. return false;
  17007. }
  17008. char buf[512];
  17009. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  17010. // Headers plus the two-byte body of the handler below
  17011. while (reader.getline()) {
  17012. first_response += reader.ptr();
  17013. if (first_response.find("ok") != std::string::npos) { break; }
  17014. }
  17015. if (strm.write(second.data(), second.size()) !=
  17016. static_cast<ssize_t>(second.size())) {
  17017. return true;
  17018. }
  17019. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  17020. while (reader2.getline()) {
  17021. second_response += reader2.ptr();
  17022. if (second_response.find("ok") != std::string::npos) { break; }
  17023. }
  17024. return true;
  17025. });
  17026. *announced_close =
  17027. first_response.find("Connection: close") != std::string::npos;
  17028. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  17029. }
  17030. class ConnectionTokenTest : public ::testing::Test {
  17031. protected:
  17032. void SetUp() override {
  17033. svr_.Get("/keepalive", [](const Request &, Response &res) {
  17034. res.set_content("ok", "text/plain");
  17035. });
  17036. port_ = svr_.bind_to_any_port(HOST);
  17037. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17038. svr_.wait_until_ready();
  17039. }
  17040. void TearDown() override {
  17041. svr_.stop();
  17042. if (thread_.joinable()) { thread_.join(); }
  17043. }
  17044. Server svr_;
  17045. int port_ = 0;
  17046. thread thread_;
  17047. };
  17048. // "close" alongside another option still closes the connection, and the
  17049. // response says so rather than leaving the peer to discover it.
  17050. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  17051. bool announced_close = false;
  17052. bool reusable = true;
  17053. probe_connection_reuse(port_,
  17054. "GET /keepalive HTTP/1.1\r\n"
  17055. "Host: localhost\r\n"
  17056. "Connection: keep-alive, close\r\n"
  17057. "\r\n",
  17058. &announced_close, &reusable);
  17059. EXPECT_TRUE(announced_close);
  17060. EXPECT_FALSE(reusable);
  17061. }
  17062. // "close" split over two field lines is the same list, so it is honored too.
  17063. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  17064. bool announced_close = false;
  17065. bool reusable = true;
  17066. probe_connection_reuse(port_,
  17067. "GET /keepalive HTTP/1.1\r\n"
  17068. "Host: localhost\r\n"
  17069. "Connection: keep-alive\r\n"
  17070. "Connection: close\r\n"
  17071. "\r\n",
  17072. &announced_close, &reusable);
  17073. EXPECT_TRUE(announced_close);
  17074. EXPECT_FALSE(reusable);
  17075. }
  17076. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  17077. // keep-alive in the spelling everyone actually sends keeps its connection.
  17078. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  17079. bool announced_close = false;
  17080. bool reusable = false;
  17081. probe_connection_reuse(port_,
  17082. "GET /keepalive HTTP/1.0\r\n"
  17083. "Host: localhost\r\n"
  17084. "Connection: keep-alive\r\n"
  17085. "\r\n",
  17086. &announced_close, &reusable);
  17087. EXPECT_FALSE(announced_close);
  17088. EXPECT_TRUE(reusable);
  17089. }
  17090. // A token the value merely contains is not the token itself.
  17091. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  17092. bool announced_close = false;
  17093. bool reusable = false;
  17094. probe_connection_reuse(port_,
  17095. "GET /keepalive HTTP/1.1\r\n"
  17096. "Host: localhost\r\n"
  17097. "Connection: notclose\r\n"
  17098. "\r\n",
  17099. &announced_close, &reusable);
  17100. EXPECT_FALSE(announced_close);
  17101. EXPECT_TRUE(reusable);
  17102. }
  17103. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  17104. Server svr;
  17105. std::vector<std::string> observed_types;
  17106. svr.Get("/", [&](const Request &req, Response &res) {
  17107. observed_types = req.accept_content_types;
  17108. res.set_content("ok", "text/plain");
  17109. });
  17110. auto port = svr.bind_to_any_port(HOST);
  17111. thread t = thread([&]() { svr.listen_after_bind(); });
  17112. auto se = detail::scope_exit([&] {
  17113. svr.stop();
  17114. t.join();
  17115. ASSERT_FALSE(svr.is_running());
  17116. });
  17117. svr.wait_until_ready();
  17118. Client cli(HOST, port);
  17119. Headers headers;
  17120. headers.emplace("Accept", "text/plain;q=0.5");
  17121. headers.emplace("Accept", "application/json");
  17122. auto res = cli.Get("/", headers);
  17123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17124. EXPECT_EQ(StatusCode::OK_200, res->status);
  17125. // Sorted by q-value, so the second field line's type comes first
  17126. ASSERT_EQ(2U, observed_types.size());
  17127. EXPECT_EQ("application/json", observed_types[0]);
  17128. EXPECT_EQ("text/plain", observed_types[1]);
  17129. }
  17130. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  17131. // empty field line must not contribute a bare comma to the combined value.
  17132. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  17133. Server svr;
  17134. std::vector<std::string> observed_types;
  17135. svr.Get("/", [&](const Request &req, Response &res) {
  17136. observed_types = req.accept_content_types;
  17137. res.set_content("ok", "text/plain");
  17138. });
  17139. auto port = svr.bind_to_any_port(HOST);
  17140. thread t = thread([&]() { svr.listen_after_bind(); });
  17141. auto se = detail::scope_exit([&] {
  17142. svr.stop();
  17143. t.join();
  17144. ASSERT_FALSE(svr.is_running());
  17145. });
  17146. svr.wait_until_ready();
  17147. // Empty first field line, then a real one
  17148. std::string raw_req = "GET / HTTP/1.1\r\n"
  17149. "Host: localhost\r\n"
  17150. "Accept:\r\n"
  17151. "Accept: application/json\r\n"
  17152. "Connection: close\r\n"
  17153. "\r\n";
  17154. std::string out;
  17155. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17156. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17157. ASSERT_EQ(1U, observed_types.size());
  17158. EXPECT_EQ("application/json", observed_types[0]);
  17159. }
  17160. // The skip in get_combined_header_value() is what keeps an empty field line
  17161. // from contributing a bare comma. Only a trailing empty field line exercises
  17162. // it: a leading one is already covered by the "combined is still empty" check,
  17163. // and parse_accept_header() now ignores the empty element either way, so the
  17164. // request-level test above can no longer tell the two apart.
  17165. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  17166. Headers headers;
  17167. headers.emplace("Accept", "text/html");
  17168. headers.emplace("Accept", "");
  17169. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  17170. headers.clear();
  17171. headers.emplace("Accept", "");
  17172. headers.emplace("Accept", "application/json");
  17173. EXPECT_EQ("application/json",
  17174. detail::get_combined_header_value(headers, "Accept"));
  17175. }
  17176. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17177. // An encoding offered on a later Accept-Encoding field line is still offered.
  17178. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  17179. Server svr;
  17180. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17181. res.set_content(std::string(1024, 'x'), "text/plain");
  17182. });
  17183. auto port = svr.bind_to_any_port(HOST);
  17184. thread t = thread([&]() { svr.listen_after_bind(); });
  17185. auto se = detail::scope_exit([&] {
  17186. svr.stop();
  17187. t.join();
  17188. ASSERT_FALSE(svr.is_running());
  17189. });
  17190. svr.wait_until_ready();
  17191. Client cli(HOST, port);
  17192. cli.set_decompress(false);
  17193. Headers headers;
  17194. headers.emplace("Accept-Encoding", "identity");
  17195. headers.emplace("Accept-Encoding", "gzip");
  17196. auto res = cli.Get("/", headers);
  17197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17198. EXPECT_EQ(StatusCode::OK_200, res->status);
  17199. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  17200. }
  17201. #endif
  17202. #ifndef _WIN32
  17203. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  17204. Server svr;
  17205. svr.Post("/post", [&](const Request &req, Response &res) {
  17206. res.set_content(req.body, "text/plain");
  17207. });
  17208. svr.Put("/put", [&](const Request &req, Response &res) {
  17209. res.set_content(req.body, "text/plain");
  17210. });
  17211. svr.Patch("/patch", [&](const Request &req, Response &res) {
  17212. res.set_content(req.body, "text/plain");
  17213. });
  17214. svr.Delete("/delete", [&](const Request &req, Response &res) {
  17215. res.set_content(req.body, "text/plain");
  17216. });
  17217. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17218. auto se = detail::scope_exit([&] {
  17219. svr.stop();
  17220. t.join();
  17221. ASSERT_FALSE(svr.is_running());
  17222. });
  17223. svr.wait_until_ready();
  17224. std::string resp;
  17225. // POST without Content-Length
  17226. ASSERT_TRUE(send_request(5,
  17227. "POST /post HTTP/1.1\r\n"
  17228. "Host: localhost\r\n"
  17229. "Connection: close\r\n"
  17230. "\r\n",
  17231. &resp));
  17232. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17233. // PUT without Content-Length
  17234. resp.clear();
  17235. ASSERT_TRUE(send_request(5,
  17236. "PUT /put HTTP/1.1\r\n"
  17237. "Host: localhost\r\n"
  17238. "Connection: close\r\n"
  17239. "\r\n",
  17240. &resp));
  17241. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17242. // PATCH without Content-Length
  17243. resp.clear();
  17244. ASSERT_TRUE(send_request(5,
  17245. "PATCH /patch HTTP/1.1\r\n"
  17246. "Host: localhost\r\n"
  17247. "Connection: close\r\n"
  17248. "\r\n",
  17249. &resp));
  17250. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17251. // DELETE without Content-Length
  17252. resp.clear();
  17253. ASSERT_TRUE(send_request(5,
  17254. "DELETE /delete HTTP/1.1\r\n"
  17255. "Host: localhost\r\n"
  17256. "Connection: close\r\n"
  17257. "\r\n",
  17258. &resp));
  17259. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17260. }
  17261. #endif
  17262. //==============================================================================
  17263. // open_stream() Tests
  17264. //==============================================================================
  17265. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  17266. std::string result;
  17267. char buf[8192];
  17268. ssize_t n;
  17269. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17270. result.append(buf, static_cast<size_t>(n));
  17271. }
  17272. return result;
  17273. }
  17274. // Mock stream for unit tests
  17275. class MockStream : public Stream {
  17276. public:
  17277. std::string data;
  17278. size_t pos = 0;
  17279. ssize_t error_after = -1; // -1 = no error
  17280. explicit MockStream(const std::string &d, ssize_t err = -1)
  17281. : data(d), error_after(err) {}
  17282. bool is_readable() const override { return true; }
  17283. bool wait_readable() const override { return true; }
  17284. bool wait_writable() const override { return true; }
  17285. ssize_t read(char *ptr, size_t size) override {
  17286. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  17287. if (pos >= data.size()) return 0;
  17288. size_t limit =
  17289. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  17290. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  17291. std::memcpy(ptr, data.data() + pos, to_read);
  17292. pos += to_read;
  17293. return static_cast<ssize_t>(to_read);
  17294. }
  17295. ssize_t write(const char *, size_t) override { return -1; }
  17296. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  17297. ip = "127.0.0.1";
  17298. port = 0;
  17299. }
  17300. void get_local_ip_and_port(std::string &ip, int &port) const override {
  17301. ip = "127.0.0.1";
  17302. port = 0;
  17303. }
  17304. socket_t socket() const override { return INVALID_SOCKET; }
  17305. time_t duration() const override { return 0; }
  17306. };
  17307. TEST(StreamHandleTest, Basic) {
  17308. ClientImpl::StreamHandle handle;
  17309. EXPECT_FALSE(handle.is_valid());
  17310. handle.response = detail::make_unique<Response>();
  17311. handle.error = Error::Connection;
  17312. EXPECT_FALSE(handle.is_valid());
  17313. handle.error = Error::Success;
  17314. EXPECT_TRUE(handle.is_valid());
  17315. }
  17316. TEST(BodyReaderTest, Basic) {
  17317. MockStream stream("Hello, World!");
  17318. detail::BodyReader reader;
  17319. reader.stream = &stream;
  17320. reader.content_length = 13;
  17321. char buf[32];
  17322. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  17323. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  17324. EXPECT_TRUE(reader.eof);
  17325. }
  17326. TEST(BodyReaderTest, NoStream) {
  17327. detail::BodyReader reader;
  17328. char buf[32];
  17329. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17330. EXPECT_EQ(Error::Connection, reader.last_error);
  17331. }
  17332. TEST(BodyReaderTest, Error) {
  17333. MockStream stream("Hello, World!", 5);
  17334. detail::BodyReader reader;
  17335. reader.stream = &stream;
  17336. reader.content_length = 13;
  17337. char buf[32];
  17338. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  17339. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17340. EXPECT_EQ(Error::Read, reader.last_error);
  17341. }
  17342. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  17343. // Mock-based StreamHandle tests relying on private internals are removed.
  17344. class OpenStreamTest : public ::testing::Test {
  17345. protected:
  17346. void SetUp() override {
  17347. svr_.Get("/hello", [](const Request &, Response &res) {
  17348. res.set_content("Hello World!", "text/plain");
  17349. });
  17350. svr_.Get("/large", [](const Request &, Response &res) {
  17351. res.set_content(std::string(10000, 'X'), "text/plain");
  17352. });
  17353. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  17354. res.set_content("Hello World!", "image/jpeg");
  17355. res.set_header("Content-Encoding", "UTF-8");
  17356. });
  17357. svr_.Get("/chunked", [](const Request &, Response &res) {
  17358. res.set_chunked_content_provider("text/plain",
  17359. [](size_t offset, DataSink &sink) {
  17360. if (offset < 15) {
  17361. sink.write("chunk", 5);
  17362. return true;
  17363. }
  17364. sink.done();
  17365. return true;
  17366. });
  17367. });
  17368. svr_.Get("/compressible", [](const Request &, Response &res) {
  17369. res.set_chunked_content_provider("text/plain", [](size_t offset,
  17370. DataSink &sink) {
  17371. if (offset < 100 * 1024) {
  17372. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  17373. sink.write(chunk.data(), chunk.size());
  17374. return true;
  17375. }
  17376. sink.done();
  17377. return true;
  17378. });
  17379. });
  17380. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  17381. [](const Request & /*req*/, Response &res) {
  17382. auto i = new int(0);
  17383. res.set_header("Trailer", "Content-Length, X-Allowed");
  17384. res.set_chunked_content_provider(
  17385. "text/plain",
  17386. [i](size_t /*offset*/, DataSink &sink) {
  17387. switch (*i) {
  17388. case 0: sink.os << "123"; break;
  17389. case 1: sink.os << "456"; break;
  17390. case 2: sink.os << "789"; break;
  17391. case 3: {
  17392. sink.done_with_trailer(
  17393. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  17394. } break;
  17395. }
  17396. (*i)++;
  17397. return true;
  17398. },
  17399. [i](bool success) {
  17400. EXPECT_TRUE(success);
  17401. delete i;
  17402. });
  17403. });
  17404. // Echo headers endpoint for header-related tests
  17405. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  17406. std::string body;
  17407. for (const auto &h : req.headers) {
  17408. body.append(h.first);
  17409. body.push_back(':');
  17410. body.append(h.second);
  17411. body.push_back('\n');
  17412. }
  17413. res.set_content(body, "text/plain");
  17414. });
  17415. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  17416. std::string body;
  17417. for (const auto &h : req.headers) {
  17418. body.append(h.first);
  17419. body.push_back(':');
  17420. body.append(h.second);
  17421. body.push_back('\n');
  17422. }
  17423. res.set_content(body, "text/plain");
  17424. });
  17425. port_ = svr_.bind_to_any_port("127.0.0.1");
  17426. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17427. svr_.wait_until_ready();
  17428. }
  17429. void TearDown() override {
  17430. svr_.stop();
  17431. if (thread_.joinable()) thread_.join();
  17432. }
  17433. Server svr_;
  17434. std::thread thread_;
  17435. int port_ = 0;
  17436. };
  17437. TEST_F(OpenStreamTest, Basic) {
  17438. Client cli("127.0.0.1", port_);
  17439. auto handle = cli.open_stream("GET", "/hello");
  17440. EXPECT_TRUE(handle.is_valid());
  17441. EXPECT_EQ("Hello World!", read_all(handle));
  17442. }
  17443. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  17444. Client cli("127.0.0.1", port_);
  17445. auto handle = cli.open_stream("GET", "/unknown-encoding");
  17446. ASSERT_TRUE(handle.is_valid());
  17447. EXPECT_EQ("Hello World!", read_all(handle));
  17448. }
  17449. TEST_F(OpenStreamTest, SmallBuffer) {
  17450. Client cli("127.0.0.1", port_);
  17451. auto handle = cli.open_stream("GET", "/hello");
  17452. std::string result;
  17453. char buf[4];
  17454. ssize_t n;
  17455. while ((n = handle.read(buf, sizeof(buf))) > 0)
  17456. result.append(buf, static_cast<size_t>(n));
  17457. EXPECT_EQ("Hello World!", result);
  17458. }
  17459. TEST_F(OpenStreamTest, DefaultHeaders) {
  17460. Client cli("127.0.0.1", port_);
  17461. // open_stream GET should include Host, User-Agent and Accept-Encoding
  17462. {
  17463. auto handle = cli.open_stream("GET", "/echo-headers");
  17464. ASSERT_TRUE(handle.is_valid());
  17465. auto body = read_all(handle);
  17466. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  17467. std::string::npos);
  17468. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  17469. std::string::npos);
  17470. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  17471. }
  17472. // open_stream POST with body and no explicit content_type should NOT add
  17473. // text/plain Content-Type (behavior differs from non-streaming path), but
  17474. // should include Content-Length
  17475. {
  17476. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  17477. ASSERT_TRUE(handle.is_valid());
  17478. auto body = read_all(handle);
  17479. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  17480. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  17481. }
  17482. // open_stream POST with explicit Content-Type should preserve it
  17483. {
  17484. auto handle = cli.open_stream("POST", "/echo-headers", {},
  17485. {{"Content-Type", "application/custom"}},
  17486. "{}", "application/custom");
  17487. ASSERT_TRUE(handle.is_valid());
  17488. auto body = read_all(handle);
  17489. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  17490. }
  17491. // User-specified User-Agent must not be overwritten for stream API
  17492. {
  17493. auto handle = cli.open_stream("GET", "/echo-headers", {},
  17494. {{"User-Agent", "MyAgent/1.2"}});
  17495. ASSERT_TRUE(handle.is_valid());
  17496. auto body = read_all(handle);
  17497. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  17498. }
  17499. }
  17500. TEST_F(OpenStreamTest, Large) {
  17501. Client cli("127.0.0.1", port_);
  17502. auto handle = cli.open_stream("GET", "/large");
  17503. EXPECT_EQ(10000u, read_all(handle).size());
  17504. }
  17505. TEST_F(OpenStreamTest, ConnectionError) {
  17506. Client cli("127.0.0.1", 9999);
  17507. auto handle = cli.open_stream("GET", "/hello");
  17508. EXPECT_FALSE(handle.is_valid());
  17509. }
  17510. TEST_F(OpenStreamTest, Chunked) {
  17511. Client cli("127.0.0.1", port_);
  17512. auto handle = cli.open_stream("GET", "/chunked");
  17513. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17514. "Transfer-Encoding") == "chunked");
  17515. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  17516. }
  17517. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  17518. Client cli("127.0.0.1", port_);
  17519. auto handle =
  17520. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  17521. ASSERT_TRUE(handle.is_valid());
  17522. // Consume body to allow trailers to be received/parsed
  17523. auto body = read_all(handle);
  17524. // Explicitly parse trailers (ensure trailers are available for assertion)
  17525. handle.parse_trailers_if_needed();
  17526. EXPECT_EQ(std::string("123456789"), body);
  17527. // The response should include a Trailer header declaring both names
  17528. ASSERT_TRUE(handle.response);
  17529. EXPECT_TRUE(handle.response->has_header("Trailer"));
  17530. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  17531. handle.response->get_header_value("Trailer"));
  17532. // Prohibited trailer must not be present
  17533. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  17534. // Allowed trailer should be present
  17535. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  17536. EXPECT_EQ(std::string("yes"),
  17537. handle.response->get_trailer_value("X-Allowed"));
  17538. // Verify trailers are NOT present as regular headers
  17539. EXPECT_EQ(std::string(""),
  17540. handle.response->get_header_value("Content-Length"));
  17541. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  17542. }
  17543. static std::thread serve_single_response(std::promise<int> &port_promise,
  17544. const std::string &response) {
  17545. return std::thread([&port_promise, response] {
  17546. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17547. default_socket_options(srv);
  17548. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17549. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  17550. sockaddr_in addr{};
  17551. addr.sin_family = AF_INET;
  17552. addr.sin_port = htons(0); // Let OS assign a free port
  17553. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17554. int opt = 1;
  17555. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  17556. #ifdef _WIN32
  17557. reinterpret_cast<const char *>(&opt),
  17558. #else
  17559. &opt,
  17560. #endif
  17561. sizeof(opt));
  17562. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  17563. ::listen(srv, 1) != 0) {
  17564. port_promise.set_value(-1);
  17565. detail::close_socket(srv);
  17566. return;
  17567. }
  17568. socklen_t addr_len = sizeof(addr);
  17569. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  17570. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  17571. sockaddr_in cli_addr{};
  17572. socklen_t cli_len = sizeof(cli_addr);
  17573. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17574. if (cli != INVALID_SOCKET) {
  17575. // Read the complete HTTP request (until the blank line that terminates
  17576. // headers) before sending the response. If the server closes the socket
  17577. // while the client's request data is still unread in the kernel receive
  17578. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  17579. // connection on both sides: it discards the client's receive buffer
  17580. // (which already holds our response) and causes any in-progress write on
  17581. // the client to fail with ECONNRESET. Reading all request data first
  17582. // ensures close() emits a graceful FIN.
  17583. {
  17584. char rbuf[256];
  17585. std::string req;
  17586. while (req.find("\r\n\r\n") == std::string::npos) {
  17587. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  17588. if (n <= 0) { break; }
  17589. req.append(rbuf, static_cast<size_t>(n));
  17590. }
  17591. }
  17592. ::send(cli,
  17593. #ifdef _WIN32
  17594. static_cast<const char *>(response.c_str()),
  17595. static_cast<int>(response.size()),
  17596. #else
  17597. response.c_str(), response.size(),
  17598. #endif
  17599. 0);
  17600. detail::close_socket(cli);
  17601. }
  17602. detail::close_socket(srv);
  17603. });
  17604. }
  17605. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  17606. #ifndef _WIN32
  17607. signal(SIGPIPE, SIG_IGN);
  17608. #endif
  17609. std::promise<int> port_promise;
  17610. auto port_future = port_promise.get_future();
  17611. auto server_thread =
  17612. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  17613. "Content-Type: text/plain\r\n"
  17614. "Content-Length: not-a-number\r\n"
  17615. "Connection: close\r\n"
  17616. "\r\n"
  17617. "hello");
  17618. auto port = port_future.get();
  17619. ASSERT_GT(port, 0);
  17620. Client cli("127.0.0.1", port);
  17621. auto handle = cli.open_stream("GET", "/");
  17622. EXPECT_FALSE(handle.is_valid());
  17623. server_thread.join();
  17624. }
  17625. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  17626. #ifndef _WIN32
  17627. signal(SIGPIPE, SIG_IGN);
  17628. #endif
  17629. std::promise<int> port_promise;
  17630. auto port_future = port_promise.get_future();
  17631. auto server_thread = serve_single_response(
  17632. port_promise, "HTTP/1.1 200 OK\r\n"
  17633. "Content-Type: text/plain\r\n"
  17634. "Content-Length: 99999999999999999999999999\r\n"
  17635. "Connection: close\r\n"
  17636. "\r\n"
  17637. "hello");
  17638. auto port = port_future.get();
  17639. ASSERT_GT(port, 0);
  17640. // Historically std::stoull would throw std::out_of_range here and crash
  17641. // the process, then parsing silently clamped to a bogus framing length and
  17642. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  17643. // so the stream fails to open, matching the not-a-number case above. The
  17644. // process still must NOT terminate.
  17645. Client cli("127.0.0.1", port);
  17646. auto handle = cli.open_stream("GET", "/");
  17647. EXPECT_FALSE(handle.is_valid());
  17648. server_thread.join();
  17649. }
  17650. // Serves `response` to the single request `fn` makes with a fresh client.
  17651. template <typename Fn>
  17652. static void with_single_response(const std::string &response, Fn fn) {
  17653. #ifndef _WIN32
  17654. signal(SIGPIPE, SIG_IGN);
  17655. #endif
  17656. std::promise<int> port_promise;
  17657. auto port_future = port_promise.get_future();
  17658. auto server_thread = serve_single_response(port_promise, response);
  17659. auto se = detail::scope_exit([&] { server_thread.join(); });
  17660. auto port = port_future.get();
  17661. ASSERT_GT(port, 0);
  17662. Client cli("127.0.0.1", port);
  17663. fn(cli);
  17664. }
  17665. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  17666. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  17667. // the chunked coding and drop Content-Length, so a front-end that trusts
  17668. // Content-Length would disagree about where the body ends (response
  17669. // smuggling). The client must reject such a response.
  17670. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17671. for (const char *te : {"chunked", "gzip, chunked"}) {
  17672. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  17673. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  17674. "\r\n" + "Connection: close\r\n" + "\r\n" +
  17675. "5\r\nhello\r\n0\r\n\r\n";
  17676. with_single_response(response, [&](Client &cli) {
  17677. auto res = cli.Get("/");
  17678. EXPECT_FALSE(static_cast<bool>(res)) << te;
  17679. EXPECT_EQ(Error::Read, res.error()) << te;
  17680. });
  17681. with_single_response(response, [&](Client &cli) {
  17682. auto handle = cli.open_stream("GET", "/");
  17683. EXPECT_FALSE(handle.is_valid()) << te;
  17684. EXPECT_EQ(Error::Read, handle.error) << te;
  17685. });
  17686. }
  17687. }
  17688. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  17689. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  17690. // closing the connection (unlike a request, which must be rejected).
  17691. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  17692. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  17693. "Transfer-Encoding: chunked\r\n"
  17694. "Connection: close\r\n"
  17695. "\r\n"
  17696. "5\r\nhello\r\n0\r\n\r\n",
  17697. "HTTP/1.1 200 OK\r\n"
  17698. "Transfer-Encoding: gzip\r\n"
  17699. "Connection: close\r\n"
  17700. "\r\n"
  17701. "hello"}) {
  17702. with_single_response(response, [&](Client &cli) {
  17703. auto res = cli.Get("/");
  17704. ASSERT_TRUE(static_cast<bool>(res)) << response;
  17705. EXPECT_EQ("hello", res->body);
  17706. });
  17707. with_single_response(response, [&](Client &cli) {
  17708. auto handle = cli.open_stream("GET", "/");
  17709. ASSERT_TRUE(handle.is_valid()) << response;
  17710. EXPECT_EQ("hello", read_all(handle));
  17711. });
  17712. }
  17713. }
  17714. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  17715. // framing headers describe nothing to read and must not be rejected.
  17716. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  17717. const std::string framing = "Content-Length: 5\r\n"
  17718. "Transfer-Encoding: chunked\r\n"
  17719. "Connection: close\r\n"
  17720. "\r\n";
  17721. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17722. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  17723. });
  17724. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17725. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  17726. });
  17727. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  17728. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  17729. with_single_response(response, [&](Client &cli) {
  17730. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  17731. });
  17732. with_single_response(response, [&](Client &cli) {
  17733. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  17734. });
  17735. }
  17736. }
  17737. // A payload max length of 0 means no limit, however the body is framed.
  17738. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  17739. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  17740. "Transfer-Encoding: chunked\r\n"
  17741. "\r\n"
  17742. "5\r\nhello\r\n0\r\n\r\n",
  17743. "HTTP/1.1 200 OK\r\n"
  17744. "Connection: close\r\n"
  17745. "\r\n"
  17746. "hello"}) {
  17747. with_single_response(response, [&](Client &cli) {
  17748. cli.set_payload_max_length(0);
  17749. auto res = cli.Get("/");
  17750. ASSERT_TRUE(res) << response;
  17751. EXPECT_EQ("hello", res->body) << response;
  17752. });
  17753. }
  17754. }
  17755. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  17756. Server svr;
  17757. svr.set_payload_max_length(0);
  17758. svr.Post("/echo", [](const Request &req, Response &res) {
  17759. res.set_content(req.body, "text/plain");
  17760. });
  17761. auto port = svr.bind_to_any_port(HOST);
  17762. thread t = thread([&] { svr.listen_after_bind(); });
  17763. auto se = detail::scope_exit([&] {
  17764. svr.stop();
  17765. t.join();
  17766. ASSERT_FALSE(svr.is_running());
  17767. });
  17768. svr.wait_until_ready();
  17769. Client cli(HOST, port);
  17770. auto res = cli.Post(
  17771. "/echo",
  17772. [](size_t /*offset*/, DataSink &sink) {
  17773. sink.write("hello", 5);
  17774. sink.done();
  17775. return true;
  17776. },
  17777. "text/plain");
  17778. ASSERT_TRUE(res);
  17779. EXPECT_EQ(StatusCode::OK_200, res->status);
  17780. EXPECT_EQ("hello", res->body);
  17781. }
  17782. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17783. TEST_F(OpenStreamTest, Gzip) {
  17784. Client cli("127.0.0.1", port_);
  17785. auto handle = cli.open_stream("GET", "/compressible", {},
  17786. {{"Accept-Encoding", "gzip"}});
  17787. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  17788. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17789. }
  17790. #endif
  17791. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17792. TEST_F(OpenStreamTest, Brotli) {
  17793. Client cli("127.0.0.1", port_);
  17794. auto handle =
  17795. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  17796. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  17797. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17798. }
  17799. #endif
  17800. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17801. TEST_F(OpenStreamTest, Zstd) {
  17802. Client cli("127.0.0.1", port_);
  17803. auto handle = cli.open_stream("GET", "/compressible", {},
  17804. {{"Accept-Encoding", "zstd"}});
  17805. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  17806. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17807. }
  17808. #endif
  17809. #ifdef CPPHTTPLIB_SSL_ENABLED
  17810. class SSLOpenStreamTest : public ::testing::Test {
  17811. protected:
  17812. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  17813. void SetUp() override {
  17814. svr_.Get("/hello", [](const Request &, Response &res) {
  17815. res.set_content("Hello SSL World!", "text/plain");
  17816. });
  17817. svr_.Get("/chunked", [](const Request &, Response &res) {
  17818. res.set_chunked_content_provider("text/plain",
  17819. [](size_t offset, DataSink &sink) {
  17820. if (offset < 15) {
  17821. sink.write("chunk", 5);
  17822. return true;
  17823. }
  17824. sink.done();
  17825. return true;
  17826. });
  17827. });
  17828. svr_.Post("/echo", [](const Request &req, Response &res) {
  17829. res.set_content(req.body, req.get_header_value("Content-Type"));
  17830. });
  17831. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  17832. std::string body = req.body;
  17833. res.set_chunked_content_provider(
  17834. "text/plain", [body](size_t offset, DataSink &sink) {
  17835. if (offset < body.size()) {
  17836. sink.write(body.data() + offset, body.size() - offset);
  17837. }
  17838. sink.done();
  17839. return true;
  17840. });
  17841. });
  17842. port_ = svr_.bind_to_any_port("127.0.0.1");
  17843. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17844. svr_.wait_until_ready();
  17845. }
  17846. void TearDown() override {
  17847. svr_.stop();
  17848. if (thread_.joinable()) thread_.join();
  17849. }
  17850. SSLServer svr_;
  17851. std::thread thread_;
  17852. int port_ = 0;
  17853. };
  17854. TEST_F(SSLOpenStreamTest, Basic) {
  17855. SSLClient cli("127.0.0.1", port_);
  17856. cli.enable_server_certificate_verification(false);
  17857. auto handle = cli.open_stream("GET", "/hello");
  17858. ASSERT_TRUE(handle.is_valid());
  17859. EXPECT_EQ("Hello SSL World!", read_all(handle));
  17860. }
  17861. TEST_F(SSLOpenStreamTest, Chunked) {
  17862. SSLClient cli("127.0.0.1", port_);
  17863. cli.enable_server_certificate_verification(false);
  17864. auto handle = cli.open_stream("GET", "/chunked");
  17865. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17866. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17867. "Transfer-Encoding") == "chunked");
  17868. auto body = read_all(handle);
  17869. EXPECT_EQ("chunkchunkchunk", body);
  17870. }
  17871. TEST_F(SSLOpenStreamTest, Post) {
  17872. SSLClient cli("127.0.0.1", port_);
  17873. cli.enable_server_certificate_verification(false);
  17874. auto handle =
  17875. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  17876. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17877. EXPECT_EQ(200, handle.response->status);
  17878. auto body = read_all(handle);
  17879. EXPECT_EQ("Hello SSL POST", body);
  17880. }
  17881. TEST_F(SSLOpenStreamTest, PostChunked) {
  17882. SSLClient cli("127.0.0.1", port_);
  17883. cli.enable_server_certificate_verification(false);
  17884. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  17885. "Chunked SSL Data", "text/plain");
  17886. ASSERT_TRUE(handle.is_valid());
  17887. EXPECT_EQ(200, handle.response->status);
  17888. auto body = read_all(handle);
  17889. EXPECT_EQ("Chunked SSL Data", body);
  17890. }
  17891. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  17892. // Content-Length is terminated by the server closing the connection. When the
  17893. // SSL peer sends a close_notify after the body, the client must treat it as a
  17894. // clean EOF and return a successful response rather than an error.
  17895. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  17896. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17897. ASSERT_TRUE(svr.is_valid());
  17898. svr.set_keep_alive_max_count(1);
  17899. const std::string expected_body = "Hello from connection-close response!";
  17900. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  17901. res.set_content_provider("text/plain",
  17902. [&](size_t offset, DataSink &sink) -> bool {
  17903. if (offset < expected_body.size()) {
  17904. sink.write(expected_body.data() + offset,
  17905. expected_body.size() - offset);
  17906. }
  17907. sink.done();
  17908. return true;
  17909. });
  17910. });
  17911. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  17912. auto se = detail::scope_exit([&] {
  17913. svr.stop();
  17914. listen_thread.join();
  17915. ASSERT_FALSE(svr.is_running());
  17916. });
  17917. svr.wait_until_ready();
  17918. SSLClient cli(HOST, PORT);
  17919. cli.enable_server_certificate_verification(false);
  17920. auto res = cli.Get("/no-content-length");
  17921. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  17922. EXPECT_EQ(StatusCode::OK_200, res->status);
  17923. EXPECT_EQ(expected_body, res->body);
  17924. }
  17925. #endif // CPPHTTPLIB_SSL_ENABLED
  17926. //==============================================================================
  17927. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  17928. // results for various scenarios.
  17929. //==============================================================================
  17930. TEST(ParityTest, GetVsOpenStream) {
  17931. Server svr;
  17932. const std::string path = "/parity";
  17933. const std::string content = "Parity test content: hello world";
  17934. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17935. res.set_content(content, "text/plain");
  17936. });
  17937. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17938. auto se = detail::scope_exit([&] {
  17939. svr.stop();
  17940. t.join();
  17941. ASSERT_FALSE(svr.is_running());
  17942. });
  17943. svr.wait_until_ready();
  17944. Client cli(HOST, PORT);
  17945. // Non-stream path
  17946. auto r1 = cli.Get(path);
  17947. ASSERT_TRUE(r1);
  17948. EXPECT_EQ(StatusCode::OK_200, r1->status);
  17949. // Stream path
  17950. auto h = cli.open_stream("GET", path);
  17951. ASSERT_TRUE(h.is_valid());
  17952. EXPECT_EQ(r1->body, read_all(h));
  17953. }
  17954. // Helper to compress data with provided compressor type T
  17955. template <typename Compressor>
  17956. static std::string compress_payload_for_parity(const std::string &in) {
  17957. std::string out;
  17958. Compressor compressor;
  17959. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  17960. [&](const char *data, size_t n) {
  17961. out.append(data, n);
  17962. return true;
  17963. });
  17964. EXPECT_TRUE(ok);
  17965. return out;
  17966. }
  17967. // Helper function for compression parity tests
  17968. template <typename Compressor>
  17969. static void test_compression_parity(const std::string &original,
  17970. const std::string &path,
  17971. const std::string &encoding) {
  17972. const std::string compressed =
  17973. compress_payload_for_parity<Compressor>(original);
  17974. Server svr;
  17975. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17976. res.set_content(compressed, "application/octet-stream");
  17977. res.set_header("Content-Encoding", encoding);
  17978. });
  17979. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  17980. auto se = detail::scope_exit([&] {
  17981. svr.stop();
  17982. t.join();
  17983. ASSERT_FALSE(svr.is_running());
  17984. });
  17985. svr.wait_until_ready();
  17986. Client cli(HOST, PORT);
  17987. // Non-streaming
  17988. {
  17989. auto res = cli.Get(path);
  17990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17991. EXPECT_EQ(StatusCode::OK_200, res->status);
  17992. EXPECT_EQ(original, res->body);
  17993. }
  17994. // Streaming
  17995. {
  17996. auto h = cli.open_stream("GET", path);
  17997. ASSERT_TRUE(h.is_valid());
  17998. EXPECT_EQ(original, read_all(h));
  17999. }
  18000. }
  18001. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18002. TEST(ParityTest, Gzip) {
  18003. test_compression_parity<detail::gzip_compressor>(
  18004. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  18005. }
  18006. #endif
  18007. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18008. TEST(ParityTest, Brotli) {
  18009. test_compression_parity<detail::brotli_compressor>(
  18010. "Hello, brotli parity test payload", "/parity-br", "br");
  18011. }
  18012. #endif
  18013. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18014. TEST(ParityTest, Zstd) {
  18015. test_compression_parity<detail::zstd_compressor>(
  18016. "Zstandard parity test payload", "/parity-zstd", "zstd");
  18017. }
  18018. #endif
  18019. //==============================================================================
  18020. // New Stream API Tests
  18021. //==============================================================================
  18022. inline std::string read_body(httplib::stream::Result &result) {
  18023. std::string body;
  18024. while (result.next()) {
  18025. body.append(result.data(), result.size());
  18026. }
  18027. return body;
  18028. }
  18029. TEST(ClientConnectionTest, Basic) {
  18030. httplib::ClientConnection conn;
  18031. EXPECT_FALSE(conn.is_open());
  18032. conn.sock = 1;
  18033. EXPECT_TRUE(conn.is_open());
  18034. httplib::ClientConnection conn2(std::move(conn));
  18035. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  18036. conn2.sock = INVALID_SOCKET;
  18037. }
  18038. // Unified test server for all stream::* tests
  18039. class StreamApiTest : public ::testing::Test {
  18040. protected:
  18041. void SetUp() override {
  18042. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18043. res.set_content("Hello World!", "text/plain");
  18044. });
  18045. svr_.Get("/echo-params",
  18046. [](const httplib::Request &req, httplib::Response &res) {
  18047. std::string r;
  18048. for (const auto &p : req.params) {
  18049. if (!r.empty()) r += "&";
  18050. r += p.first + "=" + p.second;
  18051. }
  18052. res.set_content(r, "text/plain");
  18053. });
  18054. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18055. res.set_content(req.body, req.get_header_value("Content-Type"));
  18056. });
  18057. svr_.Post("/echo-headers",
  18058. [](const httplib::Request &req, httplib::Response &res) {
  18059. std::string r;
  18060. for (const auto &h : req.headers)
  18061. r += h.first + ": " + h.second + "\n";
  18062. res.set_content(r, "text/plain");
  18063. });
  18064. svr_.Post("/echo-params",
  18065. [](const httplib::Request &req, httplib::Response &res) {
  18066. std::string r = "params:";
  18067. for (const auto &p : req.params)
  18068. r += p.first + "=" + p.second + ";";
  18069. res.set_content(r + " body:" + req.body, "text/plain");
  18070. });
  18071. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  18072. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  18073. });
  18074. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18075. res.set_content("PUT:" + req.body, "text/plain");
  18076. });
  18077. svr_.Patch("/echo",
  18078. [](const httplib::Request &req, httplib::Response &res) {
  18079. res.set_content("PATCH:" + req.body, "text/plain");
  18080. });
  18081. svr_.Delete(
  18082. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  18083. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  18084. "text/plain");
  18085. });
  18086. svr_.Get("/head-test",
  18087. [](const httplib::Request &, httplib::Response &res) {
  18088. res.set_content("body for HEAD", "text/plain");
  18089. });
  18090. svr_.Options("/options",
  18091. [](const httplib::Request &, httplib::Response &res) {
  18092. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  18093. });
  18094. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  18095. svr_.wait_until_ready();
  18096. }
  18097. void TearDown() override {
  18098. svr_.stop();
  18099. if (thread_.joinable()) thread_.join();
  18100. }
  18101. httplib::Server svr_;
  18102. std::thread thread_;
  18103. };
  18104. // stream::Get tests
  18105. TEST_F(StreamApiTest, GetBasic) {
  18106. httplib::Client cli(HOST, PORT);
  18107. auto result = httplib::stream::Get(cli, "/hello");
  18108. ASSERT_TRUE(result.is_valid());
  18109. EXPECT_EQ(200, result.status());
  18110. EXPECT_EQ("Hello World!", read_body(result));
  18111. }
  18112. TEST_F(StreamApiTest, GetWithParams) {
  18113. httplib::Client cli(HOST, PORT);
  18114. httplib::Params params{{"foo", "bar"}};
  18115. auto result = httplib::stream::Get(cli, "/echo-params", params);
  18116. ASSERT_TRUE(result.is_valid());
  18117. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  18118. }
  18119. TEST_F(StreamApiTest, GetConnectionError) {
  18120. httplib::Client cli(HOST, 9999);
  18121. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  18122. }
  18123. TEST_F(StreamApiTest, Get404) {
  18124. httplib::Client cli(HOST, PORT);
  18125. auto result = httplib::stream::Get(cli, "/nonexistent");
  18126. EXPECT_TRUE(result.is_valid());
  18127. EXPECT_EQ(404, result.status());
  18128. }
  18129. // stream::Post tests
  18130. TEST_F(StreamApiTest, PostBasic) {
  18131. httplib::Client cli(HOST, PORT);
  18132. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  18133. "application/json");
  18134. ASSERT_TRUE(result.is_valid());
  18135. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  18136. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  18137. }
  18138. TEST_F(StreamApiTest, PostWithHeaders) {
  18139. httplib::Client cli(HOST, PORT);
  18140. httplib::Headers headers{{"X-Custom", "value"}};
  18141. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  18142. "text/plain");
  18143. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  18144. }
  18145. TEST_F(StreamApiTest, PostWithParams) {
  18146. httplib::Client cli(HOST, PORT);
  18147. httplib::Params params{{"k", "v"}};
  18148. auto result =
  18149. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  18150. auto body = read_body(result);
  18151. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  18152. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  18153. }
  18154. TEST_F(StreamApiTest, PostLarge) {
  18155. httplib::Client cli(HOST, PORT);
  18156. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  18157. size_t total = 0;
  18158. while (result.next()) {
  18159. total += result.size();
  18160. }
  18161. EXPECT_EQ(100u * 1024u, total);
  18162. }
  18163. // stream::Put/Patch tests
  18164. TEST_F(StreamApiTest, PutAndPatch) {
  18165. httplib::Client cli(HOST, PORT);
  18166. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  18167. EXPECT_EQ("PUT:test", read_body(put));
  18168. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  18169. EXPECT_EQ("PATCH:test", read_body(patch));
  18170. }
  18171. // stream::Delete tests
  18172. TEST_F(StreamApiTest, Delete) {
  18173. httplib::Client cli(HOST, PORT);
  18174. auto del1 = httplib::stream::Delete(cli, "/resource");
  18175. EXPECT_EQ("Deleted", read_body(del1));
  18176. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  18177. EXPECT_EQ("Deleted:data", read_body(del2));
  18178. }
  18179. // stream::Head/Options tests
  18180. TEST_F(StreamApiTest, HeadAndOptions) {
  18181. httplib::Client cli(HOST, PORT);
  18182. auto head = httplib::stream::Head(cli, "/head-test");
  18183. EXPECT_TRUE(head.is_valid());
  18184. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  18185. auto opts = httplib::stream::Options(cli, "/options");
  18186. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  18187. }
  18188. // SSL stream::* tests
  18189. #ifdef CPPHTTPLIB_SSL_ENABLED
  18190. class SSLStreamApiTest : public ::testing::Test {
  18191. protected:
  18192. void SetUp() override {
  18193. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18194. res.set_content("Hello SSL!", "text/plain");
  18195. });
  18196. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18197. res.set_content(req.body, "text/plain");
  18198. });
  18199. port_ = svr_.bind_to_any_port("127.0.0.1");
  18200. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18201. svr_.wait_until_ready();
  18202. }
  18203. void TearDown() override {
  18204. svr_.stop();
  18205. if (thread_.joinable()) thread_.join();
  18206. }
  18207. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  18208. std::thread thread_;
  18209. int port_ = 0;
  18210. };
  18211. TEST_F(SSLStreamApiTest, GetAndPost) {
  18212. httplib::SSLClient cli("127.0.0.1", port_);
  18213. cli.enable_server_certificate_verification(false);
  18214. auto get = httplib::stream::Get(cli, "/hello");
  18215. EXPECT_EQ("Hello SSL!", read_body(get));
  18216. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  18217. EXPECT_EQ("test", read_body(post));
  18218. }
  18219. #endif
  18220. // Tests for Error::Timeout and Error::ConnectionClosed error types
  18221. // These errors are set in SocketStream/SSLSocketStream and propagated through
  18222. // BodyReader
  18223. TEST(ErrorHandlingTest, StreamReadTimeout) {
  18224. // Test that read timeout during streaming is detected
  18225. // Use a large content-length response where server delays mid-stream
  18226. Server svr;
  18227. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18228. // Send a large response with delay in the middle
  18229. res.set_content_provider(
  18230. 1000, // content_length
  18231. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  18232. if (offset < 100) {
  18233. // Send first 100 bytes immediately
  18234. std::string data(100, 'A');
  18235. sink.write(data.c_str(), data.size());
  18236. return true;
  18237. }
  18238. // Then delay longer than client timeout
  18239. std::this_thread::sleep_for(std::chrono::seconds(3));
  18240. std::string data(900, 'B');
  18241. sink.write(data.c_str(), data.size());
  18242. return true;
  18243. });
  18244. });
  18245. auto port = 8091;
  18246. std::thread t([&]() { svr.listen("localhost", port); });
  18247. svr.wait_until_ready();
  18248. Client cli("localhost", port);
  18249. cli.set_read_timeout(1, 0); // 1 second timeout
  18250. auto handle = cli.open_stream("GET", "/slow-stream");
  18251. ASSERT_TRUE(handle.is_valid());
  18252. char buf[256];
  18253. ssize_t total = 0;
  18254. ssize_t n;
  18255. bool got_error = false;
  18256. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18257. total += n;
  18258. }
  18259. if (n < 0) {
  18260. got_error = true;
  18261. // Should be timeout or read error
  18262. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18263. handle.get_read_error() == Error::Read)
  18264. << "Actual error: " << to_string(handle.get_read_error());
  18265. }
  18266. // Either we got an error, or we got less data than expected
  18267. EXPECT_TRUE(got_error || total < 1000)
  18268. << "Expected timeout but got all " << total << " bytes";
  18269. svr.stop();
  18270. t.join();
  18271. }
  18272. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  18273. // Test connection closed detection via BodyReader
  18274. Server svr;
  18275. std::atomic<bool> close_now{false};
  18276. svr.Get("/will-close", [&](const Request &, Response &res) {
  18277. res.set_content_provider(
  18278. 10000, // Large content_length that we won't fully send
  18279. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18280. if (offset < 100) {
  18281. std::string data(100, 'X');
  18282. sink.write(data.c_str(), data.size());
  18283. return true;
  18284. }
  18285. // Wait for signal then abort
  18286. while (!close_now) {
  18287. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18288. }
  18289. return false; // Abort - server will close connection
  18290. });
  18291. });
  18292. auto port = 8092;
  18293. std::thread t([&]() { svr.listen("localhost", port); });
  18294. svr.wait_until_ready();
  18295. Client cli("localhost", port);
  18296. auto handle = cli.open_stream("GET", "/will-close");
  18297. ASSERT_TRUE(handle.is_valid());
  18298. char buf[256];
  18299. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18300. EXPECT_GT(n, 0) << "First read should succeed";
  18301. // Signal server to close
  18302. close_now = true;
  18303. // Keep reading until error or EOF
  18304. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18305. // Keep reading
  18306. }
  18307. // Should get an error since content_length wasn't satisfied
  18308. if (n < 0) {
  18309. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18310. handle.get_read_error() == Error::Read)
  18311. << "Actual error: " << to_string(handle.get_read_error());
  18312. }
  18313. svr.stop();
  18314. t.join();
  18315. }
  18316. #ifdef CPPHTTPLIB_SSL_ENABLED
  18317. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  18318. // Test that read timeout during SSL streaming is detected
  18319. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18320. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18321. res.set_content_provider(
  18322. 1000, "text/plain",
  18323. [](size_t offset, size_t /*length*/, DataSink &sink) {
  18324. if (offset < 100) {
  18325. std::string data(100, 'A');
  18326. sink.write(data.c_str(), data.size());
  18327. return true;
  18328. }
  18329. std::this_thread::sleep_for(std::chrono::seconds(3));
  18330. std::string data(900, 'B');
  18331. sink.write(data.c_str(), data.size());
  18332. return true;
  18333. });
  18334. });
  18335. auto port = 8093;
  18336. std::thread t([&]() { svr.listen("localhost", port); });
  18337. svr.wait_until_ready();
  18338. SSLClient cli("localhost", port);
  18339. cli.enable_server_certificate_verification(false);
  18340. cli.set_read_timeout(1, 0); // 1 second timeout
  18341. auto handle = cli.open_stream("GET", "/slow-stream");
  18342. ASSERT_TRUE(handle.is_valid());
  18343. char buf[256];
  18344. ssize_t total = 0;
  18345. ssize_t n;
  18346. bool got_error = false;
  18347. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18348. total += n;
  18349. }
  18350. if (n < 0) {
  18351. got_error = true;
  18352. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18353. handle.get_read_error() == Error::Read)
  18354. << "Actual error: " << to_string(handle.get_read_error());
  18355. }
  18356. EXPECT_TRUE(got_error || total < 1000)
  18357. << "Expected timeout but got all " << total << " bytes";
  18358. svr.stop();
  18359. t.join();
  18360. }
  18361. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  18362. // Test SSL connection closed detection
  18363. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18364. std::atomic<bool> close_now{false};
  18365. svr.Get("/will-close", [&](const Request &, Response &res) {
  18366. res.set_content_provider(
  18367. 10000, "text/plain",
  18368. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18369. if (offset < 100) {
  18370. std::string data(100, 'X');
  18371. sink.write(data.c_str(), data.size());
  18372. return true;
  18373. }
  18374. while (!close_now) {
  18375. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18376. }
  18377. return false;
  18378. });
  18379. });
  18380. auto port = 8094;
  18381. std::thread t([&]() { svr.listen("localhost", port); });
  18382. svr.wait_until_ready();
  18383. SSLClient cli("localhost", port);
  18384. cli.enable_server_certificate_verification(false);
  18385. auto handle = cli.open_stream("GET", "/will-close");
  18386. ASSERT_TRUE(handle.is_valid());
  18387. char buf[256];
  18388. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18389. EXPECT_GT(n, 0);
  18390. // Signal server to close
  18391. close_now = true;
  18392. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18393. // Keep reading
  18394. }
  18395. if (n < 0) {
  18396. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18397. handle.get_read_error() == Error::Read)
  18398. << "Actual error: " << to_string(handle.get_read_error());
  18399. }
  18400. svr.stop();
  18401. t.join();
  18402. }
  18403. #endif
  18404. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  18405. using namespace httplib;
  18406. // Create a test file
  18407. const char *fname = "etag_testfile.txt";
  18408. const char *content = "etag-content";
  18409. {
  18410. std::ofstream ofs(fname);
  18411. ofs << content;
  18412. ASSERT_TRUE(ofs.good());
  18413. }
  18414. Server svr;
  18415. svr.set_mount_point("/static", ".");
  18416. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18417. svr.wait_until_ready();
  18418. Client cli(HOST, PORT);
  18419. // First request: should get 200 with ETag header
  18420. auto res1 = cli.Get("/static/etag_testfile.txt");
  18421. ASSERT_TRUE(res1);
  18422. ASSERT_EQ(200, res1->status);
  18423. ASSERT_TRUE(res1->has_header("ETag"));
  18424. std::string etag = res1->get_header_value("ETag");
  18425. EXPECT_FALSE(etag.empty());
  18426. // Verify ETag format: W/"hex-hex"
  18427. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  18428. EXPECT_EQ('W', etag[0]);
  18429. EXPECT_EQ('/', etag[1]);
  18430. EXPECT_EQ('"', etag[2]);
  18431. EXPECT_EQ('"', etag.back());
  18432. // Exact match: expect 304 Not Modified
  18433. Headers h2 = {{"If-None-Match", etag}};
  18434. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  18435. ASSERT_TRUE(res2);
  18436. EXPECT_EQ(304, res2->status);
  18437. // Wildcard match: expect 304 Not Modified
  18438. Headers h3 = {{"If-None-Match", "*"}};
  18439. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  18440. ASSERT_TRUE(res3);
  18441. EXPECT_EQ(304, res3->status);
  18442. // Non-matching ETag: expect 200
  18443. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  18444. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  18445. ASSERT_TRUE(res4);
  18446. EXPECT_EQ(200, res4->status);
  18447. // Multiple ETags with one matching: expect 304
  18448. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  18449. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  18450. ASSERT_TRUE(res5);
  18451. EXPECT_EQ(304, res5->status);
  18452. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  18453. // that equivalent to the single comma-separated list above, so the match on
  18454. // the second line must still be found.
  18455. Headers h6;
  18456. h6.emplace("If-None-Match", "W/\"other\"");
  18457. h6.emplace("If-None-Match", etag);
  18458. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  18459. ASSERT_TRUE(res6);
  18460. EXPECT_EQ(304, res6->status);
  18461. svr.stop();
  18462. t.join();
  18463. std::remove(fname);
  18464. }
  18465. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  18466. using namespace httplib;
  18467. Server svr;
  18468. svr.set_mount_point("/static", ".");
  18469. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18470. svr.wait_until_ready();
  18471. Client cli(HOST, PORT);
  18472. // Send If-None-Match: * to a non-existent file
  18473. Headers h = {{"If-None-Match", "*"}};
  18474. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  18475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18476. EXPECT_EQ(404, res->status);
  18477. svr.stop();
  18478. t.join();
  18479. }
  18480. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  18481. using namespace httplib;
  18482. // Create a test file
  18483. const char *fname = "etag_boundary_testfile.txt";
  18484. const char *content = "boundary-test";
  18485. {
  18486. std::ofstream ofs(fname);
  18487. ofs << content;
  18488. ASSERT_TRUE(ofs.good());
  18489. }
  18490. Server svr;
  18491. svr.set_mount_point("/static", ".");
  18492. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18493. svr.wait_until_ready();
  18494. Client cli(HOST, PORT);
  18495. // Get the actual ETag
  18496. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  18497. ASSERT_TRUE(res1);
  18498. ASSERT_EQ(200, res1->status);
  18499. ASSERT_TRUE(res1->has_header("ETag"));
  18500. std::string etag = res1->get_header_value("ETag");
  18501. // Test 1: Very long ETag value (longer than actual ETag)
  18502. // Should NOT match and return 200 (not trigger out-of-bounds read)
  18503. Headers h1 = {{"If-None-Match", "W/"
  18504. "\"very-long-etag-value-that-is-much-longer-"
  18505. "than-the-actual-etag-value\""}};
  18506. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  18507. ASSERT_TRUE(res2);
  18508. EXPECT_EQ(200, res2->status); // Should not match
  18509. // Test 2: Long string followed by wildcard
  18510. // Should match on "*" and return 304 (without out-of-bounds read on the long
  18511. // string)
  18512. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  18513. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  18514. ASSERT_TRUE(res3);
  18515. EXPECT_EQ(304, res3->status); // Should match on "*"
  18516. // Test 3: Wildcard followed by long string
  18517. // Should match on "*" immediately and return 304
  18518. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  18519. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  18520. ASSERT_TRUE(res4);
  18521. EXPECT_EQ(304, res4->status); // Should match on "*"
  18522. // Test 4: Multiple long non-matching values
  18523. // Should NOT match and return 200 (test that all comparisons are safe)
  18524. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  18525. "W/\"second-long-non-matching-value\", "
  18526. "W/\"third-long-non-matching-value\""}};
  18527. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  18528. ASSERT_TRUE(res5);
  18529. EXPECT_EQ(200, res5->status); // Should not match
  18530. // Test 5: Single character that is not "*" (edge case)
  18531. Headers h5 = {{"If-None-Match", "X"}};
  18532. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  18533. ASSERT_TRUE(res6);
  18534. EXPECT_EQ(200, res6->status); // Should not match
  18535. svr.stop();
  18536. t.join();
  18537. std::remove(fname);
  18538. }
  18539. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  18540. using namespace httplib;
  18541. // Create a test file
  18542. const char *fname = "ims_testfile.txt";
  18543. const char *content = "if-modified-since-test";
  18544. {
  18545. std::ofstream ofs(fname);
  18546. ofs << content;
  18547. ASSERT_TRUE(ofs.good());
  18548. }
  18549. Server svr;
  18550. svr.set_mount_point("/static", ".");
  18551. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18552. svr.wait_until_ready();
  18553. Client cli(HOST, PORT);
  18554. // First request: should get 200 with Last-Modified header
  18555. auto res1 = cli.Get("/static/ims_testfile.txt");
  18556. ASSERT_TRUE(res1);
  18557. ASSERT_EQ(200, res1->status);
  18558. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18559. std::string last_modified = res1->get_header_value("Last-Modified");
  18560. EXPECT_FALSE(last_modified.empty());
  18561. // If-Modified-Since with same time: expect 304
  18562. Headers h2 = {{"If-Modified-Since", last_modified}};
  18563. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  18564. ASSERT_TRUE(res2);
  18565. EXPECT_EQ(304, res2->status);
  18566. // If-Modified-Since with future time: expect 304
  18567. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18568. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  18569. ASSERT_TRUE(res3);
  18570. EXPECT_EQ(304, res3->status);
  18571. // If-Modified-Since with past time: expect 200
  18572. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18573. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  18574. ASSERT_TRUE(res4);
  18575. EXPECT_EQ(200, res4->status);
  18576. // If-None-Match takes precedence over If-Modified-Since
  18577. // (send matching ETag with old If-Modified-Since -> should still be 304)
  18578. ASSERT_TRUE(res1->has_header("ETag"));
  18579. std::string etag = res1->get_header_value("ETag");
  18580. Headers h5 = {{"If-None-Match", etag},
  18581. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18582. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  18583. ASSERT_TRUE(res5);
  18584. EXPECT_EQ(304, res5->status);
  18585. svr.stop();
  18586. t.join();
  18587. std::remove(fname);
  18588. }
  18589. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  18590. using namespace httplib;
  18591. Server svr;
  18592. // Endpoint that returns compressible content
  18593. svr.Get("/compressible", [](const Request &, Response &res) {
  18594. // Return a large enough body to trigger compression
  18595. std::string body(1000, 'a');
  18596. res.set_content(body, "text/plain");
  18597. });
  18598. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18599. svr.wait_until_ready();
  18600. Client cli(HOST, PORT);
  18601. // Request with gzip support: should get Vary header when compressed
  18602. cli.set_compress(true);
  18603. auto res1 = cli.Get("/compressible");
  18604. ASSERT_TRUE(res1);
  18605. EXPECT_EQ(200, res1->status);
  18606. // If Content-Encoding is set, Vary should also be set
  18607. if (res1->has_header("Content-Encoding")) {
  18608. EXPECT_TRUE(res1->has_header("Vary"));
  18609. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  18610. }
  18611. // Request without Accept-Encoding header: should not have compression
  18612. Headers h_no_compress;
  18613. auto res2 = cli.Get("/compressible", h_no_compress);
  18614. ASSERT_TRUE(res2);
  18615. EXPECT_EQ(200, res2->status);
  18616. // Verify Vary header is present when compression is applied
  18617. // (the exact behavior depends on server configuration)
  18618. svr.stop();
  18619. t.join();
  18620. }
  18621. TEST(ETagTest, IfRangeWithETag) {
  18622. using namespace httplib;
  18623. // Create a test file with known content
  18624. const char *fname = "if_range_testfile.txt";
  18625. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  18626. {
  18627. std::ofstream ofs(fname);
  18628. ofs << content;
  18629. ASSERT_TRUE(ofs.good());
  18630. }
  18631. Server svr;
  18632. svr.set_mount_point("/static", ".");
  18633. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18634. svr.wait_until_ready();
  18635. Client cli(HOST, PORT);
  18636. // First request: get ETag
  18637. auto res1 = cli.Get("/static/if_range_testfile.txt");
  18638. ASSERT_TRUE(res1);
  18639. ASSERT_EQ(200, res1->status);
  18640. ASSERT_TRUE(res1->has_header("ETag"));
  18641. std::string etag = res1->get_header_value("ETag");
  18642. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  18643. // Since our server generates weak ETags (W/"..."), If-Range with our
  18644. // ETag should NOT result in partial content - it should return full content.
  18645. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  18646. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  18647. ASSERT_TRUE(res2);
  18648. // Weak ETag in If-Range -> full content (200), not partial (206)
  18649. EXPECT_EQ(200, res2->status);
  18650. EXPECT_EQ(content, res2->body);
  18651. EXPECT_FALSE(res2->has_header("Content-Range"));
  18652. // Range request with non-matching If-Range (ETag): should get 200 (full
  18653. // content)
  18654. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  18655. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  18656. ASSERT_TRUE(res3);
  18657. EXPECT_EQ(200, res3->status);
  18658. EXPECT_EQ(content, res3->body);
  18659. EXPECT_FALSE(res3->has_header("Content-Range"));
  18660. // Range request with strong ETag (hypothetical - our server doesn't generate
  18661. // strong ETags, but if client sends a strong ETag that doesn't match, it
  18662. // should return full content)
  18663. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  18664. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  18665. ASSERT_TRUE(res4);
  18666. EXPECT_EQ(200, res4->status);
  18667. EXPECT_EQ(content, res4->body);
  18668. EXPECT_FALSE(res4->has_header("Content-Range"));
  18669. svr.stop();
  18670. t.join();
  18671. std::remove(fname);
  18672. }
  18673. TEST(ETagTest, IfRangeWithDate) {
  18674. using namespace httplib;
  18675. // Create a test file
  18676. const char *fname = "if_range_date_testfile.txt";
  18677. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  18678. {
  18679. std::ofstream ofs(fname);
  18680. ofs << content;
  18681. ASSERT_TRUE(ofs.good());
  18682. }
  18683. Server svr;
  18684. svr.set_mount_point("/static", ".");
  18685. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18686. svr.wait_until_ready();
  18687. Client cli(HOST, PORT);
  18688. // First request: get Last-Modified
  18689. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  18690. ASSERT_TRUE(res1);
  18691. ASSERT_EQ(200, res1->status);
  18692. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18693. std::string last_modified = res1->get_header_value("Last-Modified");
  18694. // Range request with matching If-Range (date): should get 206
  18695. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  18696. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  18697. ASSERT_TRUE(res2);
  18698. EXPECT_EQ(206, res2->status);
  18699. EXPECT_EQ("FGHIJ", res2->body);
  18700. // Range request with old If-Range date: should get 200 (full content)
  18701. Headers h3 = {{"Range", "bytes=5-9"},
  18702. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18703. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  18704. ASSERT_TRUE(res3);
  18705. EXPECT_EQ(200, res3->status);
  18706. EXPECT_EQ(content, res3->body);
  18707. // Range request with future If-Range date: should get 206
  18708. Headers h4 = {{"Range", "bytes=0-4"},
  18709. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18710. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  18711. ASSERT_TRUE(res4);
  18712. EXPECT_EQ(206, res4->status);
  18713. EXPECT_EQ("ABCDE", res4->body);
  18714. svr.stop();
  18715. t.join();
  18716. std::remove(fname);
  18717. }
  18718. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  18719. using namespace httplib;
  18720. const char *fname = "etag_malformed.txt";
  18721. const char *content = "malformed-etag";
  18722. {
  18723. std::ofstream ofs(fname);
  18724. ofs << content;
  18725. ASSERT_TRUE(ofs.good());
  18726. }
  18727. Server svr;
  18728. svr.set_mount_point("/static", ".");
  18729. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18730. svr.wait_until_ready();
  18731. Client cli(HOST, PORT);
  18732. // baseline: should get 200 and an ETag
  18733. auto res1 = cli.Get("/static/etag_malformed.txt");
  18734. ASSERT_TRUE(res1);
  18735. ASSERT_EQ(200, res1->status);
  18736. ASSERT_TRUE(res1->has_header("ETag"));
  18737. // Malformed ETag value (missing quotes) should be treated as non-matching
  18738. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  18739. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  18740. ASSERT_TRUE(res_bad);
  18741. EXPECT_EQ(200, res_bad->status);
  18742. // Whitespace-only header value should be considered invalid / non-matching
  18743. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  18744. "Host: localhost\r\n"
  18745. "If-None-Match: \r\n"
  18746. "Connection: close\r\n"
  18747. "\r\n";
  18748. std::string out;
  18749. ASSERT_TRUE(send_request(5, raw_req, &out));
  18750. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18751. svr.stop();
  18752. t.join();
  18753. std::remove(fname);
  18754. }
  18755. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  18756. using namespace httplib;
  18757. const char *fname = "ims_invalid_format.txt";
  18758. const char *content = "ims-bad-format";
  18759. {
  18760. std::ofstream ofs(fname);
  18761. ofs << content;
  18762. ASSERT_TRUE(ofs.good());
  18763. }
  18764. Server svr;
  18765. svr.set_mount_point("/static", ".");
  18766. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18767. svr.wait_until_ready();
  18768. Client cli(HOST, PORT);
  18769. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  18770. ASSERT_TRUE(res1);
  18771. ASSERT_EQ(200, res1->status);
  18772. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18773. // If-Modified-Since with invalid format should not result in 304
  18774. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  18775. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  18776. ASSERT_TRUE(res_bad);
  18777. EXPECT_EQ(200, res_bad->status);
  18778. // If-Range with invalid date format should be treated as mismatch -> full
  18779. // content (200)
  18780. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  18781. {"If-Range", "invalid-date"}};
  18782. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  18783. ASSERT_TRUE(res_ifrange);
  18784. EXPECT_EQ(200, res_ifrange->status);
  18785. svr.stop();
  18786. t.join();
  18787. std::remove(fname);
  18788. }
  18789. TEST(ETagTest, IfRangeWithMalformedETag) {
  18790. using namespace httplib;
  18791. const char *fname = "ifrange_malformed.txt";
  18792. const std::string content = "0123456789";
  18793. {
  18794. std::ofstream ofs(fname);
  18795. ofs << content;
  18796. ASSERT_TRUE(ofs.good());
  18797. }
  18798. Server svr;
  18799. svr.set_mount_point("/static", ".");
  18800. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18801. svr.wait_until_ready();
  18802. Client cli(HOST, PORT);
  18803. // First request: get ETag
  18804. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  18805. ASSERT_TRUE(res1);
  18806. ASSERT_EQ(200, res1->status);
  18807. ASSERT_TRUE(res1->has_header("ETag"));
  18808. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  18809. // full content (200)
  18810. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  18811. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  18812. ASSERT_TRUE(res2);
  18813. EXPECT_EQ(200, res2->status);
  18814. EXPECT_EQ(content, res2->body);
  18815. svr.stop();
  18816. t.join();
  18817. std::remove(fname);
  18818. }
  18819. TEST(ETagTest, ExtremeLargeDateValues) {
  18820. using namespace httplib;
  18821. const char *fname = "ims_extreme_date.txt";
  18822. const char *content = "ims-extreme-date";
  18823. {
  18824. std::ofstream ofs(fname);
  18825. ofs << content;
  18826. ASSERT_TRUE(ofs.good());
  18827. }
  18828. Server svr;
  18829. svr.set_mount_point("/static", ".");
  18830. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18831. svr.wait_until_ready();
  18832. Client cli(HOST, PORT);
  18833. auto res1 = cli.Get(std::string("/static/") + fname);
  18834. ASSERT_TRUE(res1);
  18835. ASSERT_EQ(200, res1->status);
  18836. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18837. // Extremely large year that may overflow date parsing routines.
  18838. Headers h_large_date = {
  18839. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18840. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  18841. ASSERT_TRUE(res_bad);
  18842. // Expect server to treat this as invalid/mismatch and return full content
  18843. EXPECT_EQ(200, res_bad->status);
  18844. // If-Range with extremely large date should be treated as mismatch -> full
  18845. // content (200)
  18846. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  18847. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18848. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  18849. ASSERT_TRUE(res_ifrange);
  18850. EXPECT_EQ(200, res_ifrange->status);
  18851. svr.stop();
  18852. t.join();
  18853. std::remove(fname);
  18854. }
  18855. TEST(ETagTest, NegativeFileModificationTime) {
  18856. using namespace httplib;
  18857. const char *fname = "ims_negative_mtime.txt";
  18858. const std::string content = "negative-mtime";
  18859. {
  18860. std::ofstream ofs(fname);
  18861. ofs << content;
  18862. ASSERT_TRUE(ofs.good());
  18863. }
  18864. // Try to set file mtime to a negative value. This may fail on some
  18865. // platforms/filesystems; if it fails, the test will still verify server
  18866. // behaves safely by performing a regular conditional request.
  18867. #if defined(__APPLE__) || defined(__linux__)
  18868. bool set_negative = false;
  18869. do {
  18870. struct timeval times[2];
  18871. // access time: now
  18872. times[0].tv_sec = time(nullptr);
  18873. times[0].tv_usec = 0;
  18874. // modification time: negative (e.g., -1)
  18875. times[1].tv_sec = -1;
  18876. times[1].tv_usec = 0;
  18877. if (utimes(fname, times) == 0) { set_negative = true; }
  18878. } while (0);
  18879. #else
  18880. bool set_negative = false;
  18881. #endif
  18882. Server svr;
  18883. svr.set_mount_point("/static", ".");
  18884. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18885. svr.wait_until_ready();
  18886. Client cli(HOST, PORT);
  18887. auto res1 = cli.Get(std::string("/static/") + fname);
  18888. ASSERT_TRUE(res1);
  18889. ASSERT_EQ(200, res1->status);
  18890. bool has_last_modified = res1->has_header("Last-Modified");
  18891. std::string last_modified;
  18892. if (has_last_modified) {
  18893. last_modified = res1->get_header_value("Last-Modified");
  18894. }
  18895. if (set_negative) {
  18896. // If we successfully set a negative mtime, ensure server returns a
  18897. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  18898. // with an old date and ensure server handles it without crash.
  18899. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  18900. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  18901. ASSERT_TRUE(res2);
  18902. // Behavior may vary; at minimum ensure server responds (200 or 304).
  18903. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  18904. } else {
  18905. // Could not set negative mtime on this platform; fall back to verifying
  18906. // that normal invalid/malformed dates are treated safely (non-304).
  18907. Headers h_bad_date = {
  18908. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18909. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  18910. ASSERT_TRUE(res_bad);
  18911. EXPECT_EQ(200, res_bad->status);
  18912. }
  18913. svr.stop();
  18914. t.join();
  18915. std::remove(fname);
  18916. }
  18917. //==============================================================================
  18918. // Integration Tests with Server
  18919. //==============================================================================
  18920. class SSEIntegrationTest : public ::testing::Test {
  18921. protected:
  18922. void SetUp() override {
  18923. stop_server_.store(false);
  18924. events_.clear();
  18925. server_ = httplib::detail::make_unique<Server>();
  18926. setup_server();
  18927. start_server();
  18928. }
  18929. void TearDown() override {
  18930. stop_server_.store(true);
  18931. event_cv_.notify_all();
  18932. server_->stop();
  18933. if (server_thread_.joinable()) { server_thread_.join(); }
  18934. }
  18935. void setup_server() {
  18936. // Simple SSE endpoint
  18937. server_->Get("/events", [this](const Request &req, Response &res) {
  18938. auto last_id = req.get_header_value("Last-Event-ID");
  18939. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  18940. res.set_chunked_content_provider(
  18941. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  18942. std::unique_lock<std::mutex> lock(event_mutex_);
  18943. if (event_cv_.wait_for(
  18944. lock, std::chrono::milliseconds(200), [this] {
  18945. return !events_.empty() || stop_server_.load();
  18946. })) {
  18947. if (stop_server_.load()) { return false; }
  18948. if (!events_.empty()) {
  18949. std::string event = events_.front();
  18950. events_.erase(events_.begin());
  18951. sink.write(event.data(), event.size());
  18952. return true;
  18953. }
  18954. }
  18955. return !stop_server_.load();
  18956. });
  18957. });
  18958. // Endpoint that returns error
  18959. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  18960. res.status = 500;
  18961. res.set_content("Internal Server Error", "text/plain");
  18962. });
  18963. // Endpoint for custom event types
  18964. server_->Get("/custom-events", [](const Request &, Response &res) {
  18965. res.set_chunked_content_provider(
  18966. "text/event-stream", [](size_t offset, DataSink &sink) {
  18967. if (offset == 0) {
  18968. std::string event = "event: update\ndata: updated\n\n"
  18969. "event: delete\ndata: deleted\n\n";
  18970. sink.write(event.data(), event.size());
  18971. }
  18972. return false; // End stream after sending
  18973. });
  18974. });
  18975. }
  18976. void start_server() {
  18977. port_ = server_->bind_to_any_port(HOST);
  18978. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18979. // Wait for server to start
  18980. while (!server_->is_running()) {
  18981. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18982. }
  18983. }
  18984. int get_port() const { return port_; }
  18985. void send_event(const std::string &event) {
  18986. std::lock_guard<std::mutex> lock(event_mutex_);
  18987. events_.push_back(event);
  18988. event_cv_.notify_all();
  18989. }
  18990. std::unique_ptr<Server> server_;
  18991. std::thread server_thread_;
  18992. std::mutex event_mutex_;
  18993. std::condition_variable event_cv_;
  18994. std::vector<std::string> events_;
  18995. std::atomic<bool> stop_server_{false};
  18996. std::string last_received_event_id_;
  18997. int port_ = 0;
  18998. };
  18999. //==============================================================================
  19000. // SSE Parsing Tests
  19001. //==============================================================================
  19002. class SSEParsingTest : public SSEIntegrationTest {
  19003. protected:
  19004. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  19005. // A trailing sentinel event tells when the whole stream has been parsed.
  19006. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  19007. auto body = stream + "event: end\ndata: end\n\n";
  19008. server_->Get("/parse", [body](const Request &, Response &res) {
  19009. res.set_content(body, "text/event-stream");
  19010. });
  19011. return collect("/parse");
  19012. }
  19013. // Runs SSEClient against path until an "end" event arrives and returns the
  19014. // messages dispatched before it
  19015. std::vector<sse::SSEMessage> collect(const std::string &path) {
  19016. Client client(HOST, get_port());
  19017. sse::SSEClient sse(client, path);
  19018. std::mutex mutex;
  19019. std::condition_variable cv;
  19020. std::vector<sse::SSEMessage> messages;
  19021. auto done = false;
  19022. sse.on_message([&](const sse::SSEMessage &msg) {
  19023. std::lock_guard<std::mutex> lock(mutex);
  19024. // Ignore a replay from a reconnect that races with stop()
  19025. if (!done) { messages.push_back(msg); }
  19026. });
  19027. sse.on_event("end", [&](const sse::SSEMessage &) {
  19028. std::lock_guard<std::mutex> lock(mutex);
  19029. done = true;
  19030. cv.notify_all();
  19031. });
  19032. sse.set_reconnect_interval(100);
  19033. sse.start_async();
  19034. {
  19035. std::unique_lock<std::mutex> lock(mutex);
  19036. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  19037. }
  19038. sse.stop();
  19039. EXPECT_TRUE(done);
  19040. return messages;
  19041. }
  19042. };
  19043. TEST_F(SSEParsingTest, SingleLineData) {
  19044. auto msgs = parse("data: hello\n\n");
  19045. ASSERT_EQ(msgs.size(), 1u);
  19046. EXPECT_EQ(msgs[0].data, "hello");
  19047. EXPECT_EQ(msgs[0].event, "message");
  19048. }
  19049. TEST_F(SSEParsingTest, MultiLineData) {
  19050. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  19051. ASSERT_EQ(msgs.size(), 1u);
  19052. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  19053. }
  19054. TEST_F(SSEParsingTest, CustomEventType) {
  19055. auto msgs = parse("event: update\ndata: payload\n\n");
  19056. ASSERT_EQ(msgs.size(), 1u);
  19057. EXPECT_EQ(msgs[0].event, "update");
  19058. EXPECT_EQ(msgs[0].data, "payload");
  19059. }
  19060. TEST_F(SSEParsingTest, EventIdHandling) {
  19061. auto msgs = parse("id: 12345\ndata: test\n\n");
  19062. ASSERT_EQ(msgs.size(), 1u);
  19063. EXPECT_EQ(msgs[0].id, "12345");
  19064. }
  19065. TEST_F(SSEParsingTest, EmptyEventId) {
  19066. auto msgs = parse("id:\ndata: test\n\n");
  19067. ASSERT_EQ(msgs.size(), 1u);
  19068. EXPECT_EQ(msgs[0].id, "");
  19069. }
  19070. TEST_F(SSEParsingTest, CommentsIgnored) {
  19071. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  19072. ASSERT_EQ(msgs.size(), 1u);
  19073. EXPECT_EQ(msgs[0].data, "hello");
  19074. EXPECT_EQ(msgs[0].event, "message");
  19075. }
  19076. TEST_F(SSEParsingTest, ColonInValue) {
  19077. auto msgs = parse("data: hello:world:test\n\n");
  19078. ASSERT_EQ(msgs.size(), 1u);
  19079. EXPECT_EQ(msgs[0].data, "hello:world:test");
  19080. }
  19081. TEST_F(SSEParsingTest, FieldNameOnly) {
  19082. // A line without a colon is a field name with an empty value
  19083. auto msgs = parse("data\n\n");
  19084. ASSERT_EQ(msgs.size(), 1u);
  19085. EXPECT_EQ(msgs[0].data, "");
  19086. }
  19087. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  19088. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  19089. ASSERT_EQ(msgs.size(), 1u);
  19090. EXPECT_EQ(msgs[0].event, "update");
  19091. EXPECT_EQ(msgs[0].data, "hello");
  19092. }
  19093. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  19094. auto msgs = parse("data\r\n\r\n");
  19095. ASSERT_EQ(msgs.size(), 1u);
  19096. EXPECT_EQ(msgs[0].data, "");
  19097. }
  19098. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  19099. // Only a BOM at the start of the stream is ignored
  19100. auto msgs = parse("\xEF\xBB\xBF"
  19101. "data: first\n\n"
  19102. "\xEF\xBB\xBF"
  19103. "data: second\n\n");
  19104. ASSERT_EQ(msgs.size(), 1u);
  19105. EXPECT_EQ(msgs[0].data, "first");
  19106. }
  19107. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  19108. auto msgs = parse("unknown: value\ndata: hello\n\n");
  19109. ASSERT_EQ(msgs.size(), 1u);
  19110. EXPECT_EQ(msgs[0].data, "hello");
  19111. EXPECT_EQ(msgs[0].event, "message");
  19112. }
  19113. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  19114. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  19115. ASSERT_EQ(msgs.size(), 2u);
  19116. EXPECT_EQ(msgs[0].data, "hello");
  19117. EXPECT_EQ(msgs[1].data, "hello");
  19118. }
  19119. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  19120. // An event without data is not dispatched, and its type must not leak
  19121. // into the next event
  19122. auto msgs = parse("event: update\n\ndata: hello\n\n");
  19123. ASSERT_EQ(msgs.size(), 1u);
  19124. EXPECT_EQ(msgs[0].event, "message");
  19125. EXPECT_EQ(msgs[0].data, "hello");
  19126. }
  19127. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  19128. // The first connection sends only an id; the second echoes back the
  19129. // Last-Event-ID it was reconnected with
  19130. std::atomic<int> connection_count{0};
  19131. server_->Get("/id-only", [&](const Request &req, Response &res) {
  19132. if (connection_count++ == 0) {
  19133. res.set_content("id: 42\n\n", "text/event-stream");
  19134. } else {
  19135. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19136. "\n\nevent: end\ndata: end\n\n",
  19137. "text/event-stream");
  19138. }
  19139. });
  19140. auto msgs = collect("/id-only");
  19141. ASSERT_EQ(msgs.size(), 1u);
  19142. EXPECT_EQ(msgs[0].data, "42");
  19143. }
  19144. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  19145. // The first connection sets an id and then clears it with an empty one; the
  19146. // second reports whether it was reconnected with a Last-Event-ID
  19147. std::atomic<int> connection_count{0};
  19148. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  19149. if (connection_count++ == 0) {
  19150. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  19151. "text/event-stream");
  19152. } else {
  19153. res.set_content(
  19154. std::string("data: ") +
  19155. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  19156. "\n\nevent: end\ndata: end\n\n",
  19157. "text/event-stream");
  19158. }
  19159. });
  19160. auto msgs = collect("/id-clear");
  19161. ASSERT_EQ(msgs.size(), 3u);
  19162. EXPECT_EQ(msgs[0].id, "1");
  19163. EXPECT_EQ(msgs[1].id, "");
  19164. EXPECT_EQ(msgs[2].data, "not sent");
  19165. }
  19166. TEST_F(SSEParsingTest, CompleteEventParsing) {
  19167. auto msgs = parse("event: notification\nid: evt-42\n"
  19168. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  19169. ASSERT_EQ(msgs.size(), 1u);
  19170. EXPECT_EQ(msgs[0].event, "notification");
  19171. EXPECT_EQ(msgs[0].id, "evt-42");
  19172. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  19173. }
  19174. TEST(SSEMessageTest, Clear) {
  19175. sse::SSEMessage msg;
  19176. msg.event = "custom";
  19177. msg.data = "some data";
  19178. msg.id = "123";
  19179. msg.clear();
  19180. EXPECT_EQ(msg.event, "message");
  19181. EXPECT_EQ(msg.data, "");
  19182. EXPECT_EQ(msg.id, "");
  19183. }
  19184. //==============================================================================
  19185. // SSE Integration Tests
  19186. //==============================================================================
  19187. // Test: Successful connection and on_open callback
  19188. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  19189. // Add a simple endpoint that sends one event and closes
  19190. server_->Get("/simple-event", [](const Request &, Response &res) {
  19191. res.set_chunked_content_provider(
  19192. "text/event-stream", [](size_t offset, DataSink &sink) {
  19193. if (offset == 0) {
  19194. std::string event = "data: hello\n\n";
  19195. sink.write(event.data(), event.size());
  19196. }
  19197. return false; // Close stream after sending
  19198. });
  19199. });
  19200. Client client("localhost", get_port());
  19201. sse::SSEClient sse(client, "/simple-event");
  19202. std::atomic<bool> open_called{false};
  19203. std::atomic<bool> message_received{false};
  19204. sse.on_open([&open_called]() { open_called.store(true); });
  19205. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  19206. if (msg.data == "hello") { message_received.store(true); }
  19207. });
  19208. sse.set_reconnect_interval(100);
  19209. sse.set_max_reconnect_attempts(1);
  19210. // Start async
  19211. sse.start_async();
  19212. // Wait for message to be processed
  19213. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19214. sse.stop();
  19215. EXPECT_TRUE(open_called.load());
  19216. EXPECT_TRUE(message_received.load());
  19217. }
  19218. // Test: on_message callback
  19219. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  19220. // Endpoint that sends multiple events then closes
  19221. server_->Get("/multi-event", [](const Request &, Response &res) {
  19222. res.set_chunked_content_provider(
  19223. "text/event-stream", [](size_t offset, DataSink &sink) {
  19224. if (offset == 0) {
  19225. std::string events = "data: message1\n\ndata: message2\n\n";
  19226. sink.write(events.data(), events.size());
  19227. }
  19228. return false;
  19229. });
  19230. });
  19231. Client client("localhost", get_port());
  19232. sse::SSEClient sse(client, "/multi-event");
  19233. std::vector<std::string> received_messages;
  19234. std::mutex messages_mutex;
  19235. sse.on_message([&](const sse::SSEMessage &msg) {
  19236. std::lock_guard<std::mutex> lock(messages_mutex);
  19237. received_messages.push_back(msg.data);
  19238. });
  19239. sse.set_reconnect_interval(100);
  19240. sse.set_max_reconnect_attempts(1);
  19241. sse.start_async();
  19242. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19243. sse.stop();
  19244. std::lock_guard<std::mutex> lock(messages_mutex);
  19245. EXPECT_GE(received_messages.size(), 2u);
  19246. if (received_messages.size() >= 2) {
  19247. EXPECT_EQ(received_messages[0], "message1");
  19248. EXPECT_EQ(received_messages[1], "message2");
  19249. }
  19250. }
  19251. // Test: on_event for specific types
  19252. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  19253. Client client("localhost", get_port());
  19254. sse::SSEClient sse(client, "/custom-events");
  19255. std::atomic<bool> update_received{false};
  19256. std::atomic<bool> delete_received{false};
  19257. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  19258. if (msg.data == "updated") { update_received.store(true); }
  19259. });
  19260. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  19261. if (msg.data == "deleted") { delete_received.store(true); }
  19262. });
  19263. sse.set_max_reconnect_attempts(1);
  19264. sse.start_async();
  19265. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  19266. sse.stop();
  19267. EXPECT_TRUE(update_received.load());
  19268. EXPECT_TRUE(delete_received.load());
  19269. }
  19270. // Test: on_error callback on connection failure
  19271. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  19272. // Connect to a non-existent port
  19273. Client client("localhost", 59999);
  19274. sse::SSEClient sse(client, "/events");
  19275. std::atomic<bool> error_called{false};
  19276. Error received_error = Error::Success;
  19277. sse.on_error([&](Error err) {
  19278. error_called.store(true);
  19279. received_error = err;
  19280. });
  19281. sse.set_reconnect_interval(50);
  19282. sse.set_max_reconnect_attempts(1);
  19283. sse.start_async();
  19284. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19285. sse.stop();
  19286. EXPECT_TRUE(error_called.load());
  19287. EXPECT_NE(received_error, Error::Success);
  19288. }
  19289. // Test: Last-Event-ID header sent on reconnect
  19290. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  19291. // Endpoint that sends event with ID
  19292. server_->Get("/event-with-id", [](const Request &, Response &res) {
  19293. res.set_chunked_content_provider(
  19294. "text/event-stream", [](size_t offset, DataSink &sink) {
  19295. if (offset == 0) {
  19296. std::string event = "id: evt-123\ndata: test\n\n";
  19297. sink.write(event.data(), event.size());
  19298. }
  19299. return false;
  19300. });
  19301. });
  19302. Client client("localhost", get_port());
  19303. sse::SSEClient sse(client, "/event-with-id");
  19304. std::atomic<bool> id_received{false};
  19305. sse.on_message([&](const sse::SSEMessage &msg) {
  19306. if (!msg.id.empty()) { id_received.store(true); }
  19307. });
  19308. sse.set_reconnect_interval(100);
  19309. sse.set_max_reconnect_attempts(1);
  19310. sse.start_async();
  19311. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19312. sse.stop();
  19313. EXPECT_TRUE(id_received.load());
  19314. EXPECT_EQ(sse.last_event_id(), "evt-123");
  19315. }
  19316. // Test: Manual stop
  19317. TEST_F(SSEIntegrationTest, ManualStop) {
  19318. // Endpoint that sends one event and stays open briefly
  19319. std::atomic<bool> handler_running{true};
  19320. server_->Get("/stay-open", [&handler_running](const Request &,
  19321. Response &res) {
  19322. res.set_chunked_content_provider(
  19323. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  19324. if (offset == 0) {
  19325. std::string event = "data: connected\n\n";
  19326. sink.write(event.data(), event.size());
  19327. }
  19328. // Keep connection open while handler_running is true
  19329. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  19330. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19331. }
  19332. return false;
  19333. });
  19334. });
  19335. Client client("localhost", get_port());
  19336. sse::SSEClient sse(client, "/stay-open");
  19337. std::atomic<bool> connected{false};
  19338. sse.on_open([&connected]() { connected.store(true); });
  19339. sse.set_reconnect_interval(100);
  19340. sse.set_max_reconnect_attempts(1);
  19341. sse.start_async();
  19342. // Wait for connection to establish
  19343. for (int i = 0; i < 20 && !connected.load(); ++i) {
  19344. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19345. }
  19346. EXPECT_TRUE(connected.load());
  19347. EXPECT_TRUE(sse.is_connected());
  19348. // Signal handler to stop
  19349. handler_running.store(false);
  19350. // Stop SSE client
  19351. sse.stop();
  19352. EXPECT_FALSE(sse.is_connected());
  19353. }
  19354. // Test: SSEClient with custom headers
  19355. TEST_F(SSEIntegrationTest, CustomHeaders) {
  19356. // Setup a server endpoint that checks for custom header
  19357. std::atomic<bool> header_received{false};
  19358. server_->Get("/header-check", [&](const Request &req, Response &res) {
  19359. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  19360. header_received.store(true);
  19361. }
  19362. res.set_chunked_content_provider("text/event-stream",
  19363. [](size_t, DataSink &) { return false; });
  19364. });
  19365. Client client("localhost", get_port());
  19366. Headers headers = {{"X-Custom-Header", "custom-value"}};
  19367. sse::SSEClient sse(client, "/header-check", headers);
  19368. sse.set_max_reconnect_attempts(1);
  19369. sse.start_async();
  19370. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19371. sse.stop();
  19372. EXPECT_TRUE(header_received.load());
  19373. }
  19374. // Test: Reconnect interval configuration
  19375. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  19376. Client client("localhost", get_port());
  19377. sse::SSEClient sse(client, "/events");
  19378. auto &result = sse.set_reconnect_interval(500);
  19379. // Builder pattern should return reference to self
  19380. EXPECT_EQ(&result, &sse);
  19381. }
  19382. // Test: Max reconnect attempts
  19383. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  19384. // Connect to non-existent port to force reconnects
  19385. Client client("localhost", 59998);
  19386. sse::SSEClient sse(client, "/events");
  19387. std::atomic<int> error_count{0};
  19388. sse.on_error([&](Error) { error_count.fetch_add(1); });
  19389. sse.set_reconnect_interval(50);
  19390. sse.set_max_reconnect_attempts(2);
  19391. auto start = std::chrono::steady_clock::now();
  19392. sse.start(); // Blocking call
  19393. auto end = std::chrono::steady_clock::now();
  19394. // Should have stopped after 2 failed attempts
  19395. EXPECT_GE(error_count.load(), 2);
  19396. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  19397. auto duration =
  19398. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  19399. #ifdef _WIN32
  19400. // Windows is much slower for socket connection failures
  19401. EXPECT_LT(duration.count(), 7000);
  19402. #else
  19403. EXPECT_LT(duration.count(), 1000);
  19404. #endif
  19405. }
  19406. // Test: Multi-line data in integration
  19407. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  19408. // Endpoint with multi-line data
  19409. server_->Get("/multiline-data", [](const Request &, Response &res) {
  19410. res.set_chunked_content_provider(
  19411. "text/event-stream", [](size_t offset, DataSink &sink) {
  19412. if (offset == 0) {
  19413. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  19414. sink.write(event.data(), event.size());
  19415. }
  19416. return false;
  19417. });
  19418. });
  19419. Client client("localhost", get_port());
  19420. sse::SSEClient sse(client, "/multiline-data");
  19421. std::string received_data;
  19422. std::mutex data_mutex;
  19423. sse.on_message([&](const sse::SSEMessage &msg) {
  19424. std::lock_guard<std::mutex> lock(data_mutex);
  19425. received_data = msg.data;
  19426. });
  19427. sse.set_reconnect_interval(100);
  19428. sse.set_max_reconnect_attempts(1);
  19429. sse.start_async();
  19430. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19431. sse.stop();
  19432. std::lock_guard<std::mutex> lock(data_mutex);
  19433. EXPECT_EQ(received_data, "line1\nline2\nline3");
  19434. }
  19435. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  19436. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  19437. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  19438. DataSink &sink) {
  19439. if (offset == 0) {
  19440. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  19441. sink.write(events.data(), events.size());
  19442. }
  19443. return false;
  19444. });
  19445. });
  19446. Client client("localhost", get_port());
  19447. sse::SSEClient sse(client, "/empty-data-lines");
  19448. std::mutex mutex;
  19449. std::condition_variable cv;
  19450. std::vector<std::string> received;
  19451. sse.on_message([&](const sse::SSEMessage &msg) {
  19452. std::lock_guard<std::mutex> lock(mutex);
  19453. received.push_back(msg.data);
  19454. cv.notify_all();
  19455. });
  19456. sse.set_max_reconnect_attempts(1);
  19457. sse.start_async();
  19458. {
  19459. std::unique_lock<std::mutex> lock(mutex);
  19460. cv.wait_for(lock, std::chrono::seconds(2),
  19461. [&] { return received.size() >= 3; });
  19462. }
  19463. sse.stop();
  19464. ASSERT_GE(received.size(), 3u);
  19465. EXPECT_EQ(received[0], "");
  19466. EXPECT_EQ(received[1], "\nhello");
  19467. EXPECT_EQ(received[2], "");
  19468. }
  19469. // Test: Auto-reconnect after server disconnection
  19470. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  19471. std::atomic<int> connection_count{0};
  19472. std::atomic<int> message_count{0};
  19473. // Endpoint that sends one event and closes, forcing reconnect
  19474. server_->Get("/reconnect-test",
  19475. [&connection_count](const Request &, Response &res) {
  19476. connection_count.fetch_add(1);
  19477. res.set_chunked_content_provider(
  19478. "text/event-stream", [](size_t offset, DataSink &sink) {
  19479. if (offset == 0) {
  19480. std::string event = "data: hello\n\n";
  19481. sink.write(event.data(), event.size());
  19482. }
  19483. return false; // Close connection after sending
  19484. });
  19485. });
  19486. Client client("localhost", get_port());
  19487. sse::SSEClient sse(client, "/reconnect-test");
  19488. sse.on_message([&message_count](const sse::SSEMessage &) {
  19489. message_count.fetch_add(1);
  19490. });
  19491. sse.set_reconnect_interval(100);
  19492. sse.set_max_reconnect_attempts(3);
  19493. sse.start_async();
  19494. // Wait long enough for multiple reconnects
  19495. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19496. sse.stop();
  19497. // Should have connected multiple times (initial + reconnects)
  19498. EXPECT_GE(connection_count.load(), 2);
  19499. // Should have received messages from multiple connections
  19500. EXPECT_GE(message_count.load(), 2);
  19501. }
  19502. // Test: A retry field that is not all ASCII digits is ignored
  19503. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  19504. std::atomic<int> connection_count{0};
  19505. server_->Get("/bad-retry",
  19506. [&connection_count](const Request &, Response &res) {
  19507. connection_count.fetch_add(1);
  19508. res.set_chunked_content_provider(
  19509. "text/event-stream", [](size_t offset, DataSink &sink) {
  19510. if (offset == 0) {
  19511. std::string event = "retry: -1\ndata: hello\n\n";
  19512. sink.write(event.data(), event.size());
  19513. }
  19514. return false;
  19515. });
  19516. });
  19517. Client client("localhost", get_port());
  19518. sse::SSEClient sse(client, "/bad-retry");
  19519. sse.set_reconnect_interval(10000);
  19520. sse.start_async();
  19521. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19522. sse.stop();
  19523. EXPECT_EQ(connection_count.load(), 1);
  19524. }
  19525. // Test: A retry field of all ASCII digits sets the reconnection time
  19526. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  19527. std::atomic<int> connection_count{0};
  19528. server_->Get("/zero-retry",
  19529. [&connection_count](const Request &, Response &res) {
  19530. connection_count.fetch_add(1);
  19531. res.set_chunked_content_provider(
  19532. "text/event-stream", [](size_t offset, DataSink &sink) {
  19533. if (offset == 0) {
  19534. std::string event = "retry: 0\ndata: hello\n\n";
  19535. sink.write(event.data(), event.size());
  19536. }
  19537. return false;
  19538. });
  19539. });
  19540. Client client("localhost", get_port());
  19541. sse::SSEClient sse(client, "/zero-retry");
  19542. sse.set_reconnect_interval(10000);
  19543. sse.start_async();
  19544. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19545. sse.stop();
  19546. // The server-supplied interval is applied, but never below 100ms, so
  19547. // "retry: 0" does not cause a busy reconnect loop
  19548. EXPECT_GE(connection_count.load(), 2);
  19549. EXPECT_LE(connection_count.load(), 10);
  19550. }
  19551. // Test: Last-Event-ID sent on reconnect
  19552. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  19553. std::atomic<int> connection_count{0};
  19554. std::vector<std::string> received_last_event_ids;
  19555. std::mutex id_mutex;
  19556. // Endpoint that checks Last-Event-ID header and sends event with ID
  19557. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  19558. int conn = connection_count.fetch_add(1);
  19559. // Capture the Last-Event-ID header from each connection
  19560. {
  19561. std::lock_guard<std::mutex> lock(id_mutex);
  19562. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  19563. }
  19564. res.set_chunked_content_provider(
  19565. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  19566. if (offset == 0) {
  19567. std::string event =
  19568. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  19569. sink.write(event.data(), event.size());
  19570. }
  19571. return false;
  19572. });
  19573. });
  19574. Client client("localhost", get_port());
  19575. sse::SSEClient sse(client, "/reconnect-with-id");
  19576. sse.set_reconnect_interval(100);
  19577. sse.set_max_reconnect_attempts(3);
  19578. sse.start_async();
  19579. // Wait for at least 2 connections
  19580. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19581. sse.stop();
  19582. // Verify behavior
  19583. std::lock_guard<std::mutex> lock(id_mutex);
  19584. EXPECT_GE(received_last_event_ids.size(), 2u);
  19585. // First connection should have no Last-Event-ID
  19586. if (!received_last_event_ids.empty()) {
  19587. EXPECT_EQ(received_last_event_ids[0], "");
  19588. }
  19589. // Second connection should have Last-Event-ID from first connection
  19590. if (received_last_event_ids.size() >= 2) {
  19591. EXPECT_EQ(received_last_event_ids[1], "event-0");
  19592. }
  19593. }
  19594. // Test: set_headers updates headers used on reconnect
  19595. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  19596. std::vector<std::string> received_tokens;
  19597. std::mutex token_mutex;
  19598. // Endpoint that captures Authorization header
  19599. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  19600. {
  19601. std::lock_guard<std::mutex> lock(token_mutex);
  19602. received_tokens.push_back(req.get_header_value("Authorization"));
  19603. }
  19604. res.set_chunked_content_provider(
  19605. "text/event-stream", [](size_t offset, DataSink &sink) {
  19606. if (offset == 0) {
  19607. std::string event = "data: hello\n\n";
  19608. sink.write(event.data(), event.size());
  19609. }
  19610. return false; // Close connection to trigger reconnect
  19611. });
  19612. });
  19613. Client client("localhost", get_port());
  19614. Headers headers = {{"Authorization", "Bearer old-token"}};
  19615. sse::SSEClient sse(client, "/auth-check", headers);
  19616. // Update headers on each successful connection
  19617. sse.on_open(
  19618. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  19619. sse.set_reconnect_interval(100);
  19620. sse.set_max_reconnect_attempts(3);
  19621. sse.start_async();
  19622. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19623. sse.stop();
  19624. std::lock_guard<std::mutex> lock(token_mutex);
  19625. ASSERT_GE(received_tokens.size(), 2u);
  19626. // First connection uses original header
  19627. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  19628. // Second connection uses updated header from set_headers
  19629. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  19630. }
  19631. // Test: 401 allows reconnection (so on_error can refresh headers)
  19632. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  19633. std::atomic<int> connection_count{0};
  19634. // Endpoint: returns 401 on first attempt, 200 on second
  19635. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  19636. int conn = connection_count.fetch_add(1);
  19637. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  19638. res.status = StatusCode::Unauthorized_401;
  19639. res.set_content("Unauthorized", "text/plain");
  19640. return;
  19641. }
  19642. res.set_chunked_content_provider(
  19643. "text/event-stream", [](size_t offset, DataSink &sink) {
  19644. if (offset == 0) {
  19645. std::string event = "data: authenticated\n\n";
  19646. sink.write(event.data(), event.size());
  19647. }
  19648. return false;
  19649. });
  19650. });
  19651. Client client("localhost", get_port());
  19652. Headers headers = {{"Authorization", "Bearer expired"}};
  19653. sse::SSEClient sse(client, "/auth-retry", headers);
  19654. std::atomic<bool> message_received{false};
  19655. // Refresh token on error
  19656. sse.on_error(
  19657. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  19658. sse.on_message([&](const sse::SSEMessage &msg) {
  19659. if (msg.data == "authenticated") { message_received.store(true); }
  19660. });
  19661. sse.set_reconnect_interval(100);
  19662. sse.set_max_reconnect_attempts(3);
  19663. sse.start_async();
  19664. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19665. sse.stop();
  19666. // Should have reconnected after 401 and succeeded with new token
  19667. EXPECT_GE(connection_count.load(), 2);
  19668. EXPECT_TRUE(message_received.load());
  19669. }
  19670. TEST(Issue2318Test, EmptyHostString) {
  19671. {
  19672. httplib::Client cli_empty("", PORT);
  19673. auto res = cli_empty.Get("/");
  19674. ASSERT_FALSE(res);
  19675. EXPECT_EQ(httplib::Error::Connection, res.error());
  19676. }
  19677. {
  19678. httplib::Client cli(" ", PORT);
  19679. auto res = cli.Get("/");
  19680. ASSERT_FALSE(res);
  19681. EXPECT_EQ(httplib::Error::Connection, res.error());
  19682. }
  19683. }
  19684. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19685. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  19686. Server svr;
  19687. // Set a small payload limit (1KB)
  19688. svr.set_payload_max_length(1024);
  19689. svr.Post("/test", [&](const Request &req, Response &res) {
  19690. res.set_content("Body size: " + std::to_string(req.body.size()),
  19691. "text/plain");
  19692. });
  19693. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19694. auto se = detail::scope_exit([&] {
  19695. svr.stop();
  19696. listen_thread.join();
  19697. });
  19698. svr.wait_until_ready();
  19699. // Create data that compresses well but exceeds limit when decompressed
  19700. // 8KB of repeated null bytes compresses to a very small size
  19701. std::string original_data(8 * 1024, '\0');
  19702. // Compress the data using gzip
  19703. std::string compressed_data;
  19704. detail::gzip_compressor compressor;
  19705. compressor.compress(original_data.data(), original_data.size(), true,
  19706. [&](const char *data, size_t size) {
  19707. compressed_data.append(data, size);
  19708. return true;
  19709. });
  19710. // Verify compression worked (compressed should be much smaller)
  19711. ASSERT_LT(compressed_data.size(), original_data.size());
  19712. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  19713. // Send compressed data with Content-Encoding: gzip
  19714. Client cli(HOST, PORT);
  19715. Headers headers = {{"Content-Encoding", "gzip"}};
  19716. auto res =
  19717. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  19718. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  19719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19720. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  19721. }
  19722. #endif
  19723. // ============================================================================
  19724. // OpenSSL-Specific Tests
  19725. // ============================================================================
  19726. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  19727. X509 *readCertificate(const std::string &strFileName) {
  19728. std::ifstream inStream(strFileName);
  19729. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  19730. std::istreambuf_iterator<char>());
  19731. if (strCertPEM.empty()) return (nullptr);
  19732. BIO *pbCert = BIO_new(BIO_s_mem());
  19733. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  19734. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  19735. BIO_free(pbCert);
  19736. return (pCert);
  19737. }
  19738. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  19739. std::ifstream inStream(strFileName);
  19740. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  19741. std::istreambuf_iterator<char>());
  19742. if (strPrivateKeyPEM.empty()) return (nullptr);
  19743. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  19744. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  19745. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  19746. BIO_free(pbPrivKey);
  19747. return (pPrivateKey);
  19748. }
  19749. TEST(BindServerTest, UpdateCerts) {
  19750. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19751. int port = svr.bind_to_any_port("0.0.0.0");
  19752. ASSERT_TRUE(svr.is_valid());
  19753. ASSERT_TRUE(port > 0);
  19754. X509 *cert = readCertificate(SERVER_CERT_FILE);
  19755. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  19756. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  19757. ASSERT_TRUE(cert != nullptr);
  19758. ASSERT_TRUE(ca_cert != nullptr);
  19759. ASSERT_TRUE(key != nullptr);
  19760. X509_STORE *cert_store = X509_STORE_new();
  19761. X509_STORE_add_cert(cert_store, ca_cert);
  19762. // svr.update_certs(cert, key, cert_store); // deprecated
  19763. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  19764. CLIENT_CA_CERT_FILE);
  19765. ASSERT_TRUE(svr.is_valid());
  19766. svr.stop();
  19767. X509_STORE_free(cert_store);
  19768. X509_free(cert);
  19769. X509_free(ca_cert);
  19770. EVP_PKEY_free(key);
  19771. }
  19772. // Test that update_certs() updates client CA list correctly
  19773. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  19774. // Start with file-based constructor
  19775. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19776. ASSERT_TRUE(svr.is_valid());
  19777. // Initially no client CA list should be set
  19778. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19779. ASSERT_TRUE(ssl_ctx != nullptr);
  19780. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  19781. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  19782. EXPECT_EQ(0, count_before);
  19783. // Now update with client CA (PEM string)
  19784. std::string cert_pem, key_pem, ca_pem;
  19785. read_file(SERVER_CERT_FILE, cert_pem);
  19786. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  19787. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  19788. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  19789. ASSERT_TRUE(svr.is_valid());
  19790. // Now client CA list should be set
  19791. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  19792. ASSERT_TRUE(ca_list_after != nullptr);
  19793. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  19794. }
  19795. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  19796. // Test that the file-path SSLServer constructor properly sets the client CA
  19797. // list that is sent to clients during the TLS handshake (CertificateRequest)
  19798. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19799. ASSERT_TRUE(svr.is_valid());
  19800. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19801. ASSERT_TRUE(ssl_ctx != nullptr);
  19802. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  19803. ASSERT_TRUE(ca_list != nullptr);
  19804. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  19805. }
  19806. #endif
  19807. // ============================================================================
  19808. // MbedTLS-Specific Tests
  19809. // ============================================================================
  19810. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  19811. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  19812. using namespace httplib::tls;
  19813. // Track if callback was invoked
  19814. bool callback_invoked = false;
  19815. // The callback receives void* ctx which is actually MbedTlsContext*
  19816. // We can access the mbedtls_ssl_config via the context
  19817. auto setup_callback = [&callback_invoked](void *ctx) {
  19818. callback_invoked = true;
  19819. // Cast to MbedTlsContext* to access the ssl config
  19820. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  19821. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  19822. // Use static variables to hold certificate data (simplified for test)
  19823. static mbedtls_x509_crt own_cert;
  19824. static mbedtls_pk_context own_key;
  19825. static mbedtls_x509_crt ca_chain;
  19826. static bool initialized = false;
  19827. if (!initialized) {
  19828. mbedtls_x509_crt_init(&own_cert);
  19829. mbedtls_pk_init(&own_key);
  19830. mbedtls_x509_crt_init(&ca_chain);
  19831. // Load server certificate
  19832. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  19833. return false;
  19834. }
  19835. // Load server private key.
  19836. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  19837. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  19838. #if MBEDTLS_VERSION_MAJOR == 3
  19839. ,
  19840. mbedtls_ctr_drbg_random, nullptr
  19841. #endif
  19842. ) != 0) {
  19843. return false;
  19844. }
  19845. // Load CA chain for client verification
  19846. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  19847. return false;
  19848. }
  19849. initialized = true;
  19850. }
  19851. // Configure the SSL config
  19852. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  19853. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  19854. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  19855. // Set minimum TLS version using mbedTLS native API
  19856. #if MBEDTLS_VERSION_MAJOR >= 3
  19857. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  19858. #else
  19859. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  19860. MBEDTLS_SSL_MINOR_VERSION_3);
  19861. #endif
  19862. return true;
  19863. };
  19864. SSLServer svr(setup_callback);
  19865. ASSERT_TRUE(svr.is_valid());
  19866. ASSERT_TRUE(callback_invoked);
  19867. svr.Get("/test", [&](const Request &req, Response &res) {
  19868. res.set_content("test", "text/plain");
  19869. auto cert = req.peer_cert();
  19870. ASSERT_TRUE(static_cast<bool>(cert));
  19871. auto common_name = cert.subject_cn();
  19872. EXPECT_EQ("Common Name", common_name);
  19873. });
  19874. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19875. auto se = detail::scope_exit([&] {
  19876. svr.stop();
  19877. t.join();
  19878. ASSERT_FALSE(svr.is_running());
  19879. });
  19880. svr.wait_until_ready();
  19881. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  19882. cli.enable_server_certificate_verification(false);
  19883. cli.set_connection_timeout(30);
  19884. auto res = cli.Get("/test");
  19885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19886. ASSERT_EQ(StatusCode::OK_200, res->status);
  19887. }
  19888. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  19889. // context (owning mbedtls_ssl_config) before shutting down a still-open
  19890. // keep-alive SSL session, which reads through that config in
  19891. // mbedtls_ssl_close_notify.
  19892. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  19893. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19894. ASSERT_TRUE(svr.is_valid());
  19895. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19896. res.set_content("test", "text/plain");
  19897. });
  19898. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19899. auto se = detail::scope_exit([&] {
  19900. svr.stop();
  19901. t.join();
  19902. ASSERT_FALSE(svr.is_running());
  19903. });
  19904. svr.wait_until_ready();
  19905. {
  19906. SSLClient cli(HOST, PORT);
  19907. cli.enable_server_certificate_verification(false);
  19908. cli.set_keep_alive(true);
  19909. auto res = cli.Get("/test");
  19910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19911. ASSERT_EQ(StatusCode::OK_200, res->status);
  19912. // cli is destructed here with the keep-alive SSL session still open.
  19913. }
  19914. }
  19915. #endif
  19916. // WebSocket Tests
  19917. TEST(WebSocketTest, RSVBitsMustBeZero) {
  19918. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  19919. // defining the meaning of these bits has been negotiated.
  19920. auto make_frame = [](uint8_t first_byte) {
  19921. std::string frame;
  19922. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  19923. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  19924. frame += "Hello";
  19925. return frame;
  19926. };
  19927. // RSV1 set (0x40)
  19928. {
  19929. detail::BufferStream strm;
  19930. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  19931. ws::Opcode opcode;
  19932. std::string payload;
  19933. bool fin;
  19934. EXPECT_EQ(
  19935. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19936. ws::impl::FrameRead::Fail);
  19937. }
  19938. // RSV2 set (0x20)
  19939. {
  19940. detail::BufferStream strm;
  19941. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  19942. ws::Opcode opcode;
  19943. std::string payload;
  19944. bool fin;
  19945. EXPECT_EQ(
  19946. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19947. ws::impl::FrameRead::Fail);
  19948. }
  19949. // RSV3 set (0x10)
  19950. {
  19951. detail::BufferStream strm;
  19952. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  19953. ws::Opcode opcode;
  19954. std::string payload;
  19955. bool fin;
  19956. EXPECT_EQ(
  19957. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19958. ws::impl::FrameRead::Fail);
  19959. }
  19960. // No RSV bits set - should succeed
  19961. {
  19962. detail::BufferStream strm;
  19963. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  19964. ws::Opcode opcode;
  19965. std::string payload;
  19966. bool fin;
  19967. EXPECT_EQ(
  19968. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19969. ws::impl::FrameRead::Ok);
  19970. EXPECT_EQ(ws::Opcode::Text, opcode);
  19971. EXPECT_EQ("Hello", payload);
  19972. EXPECT_TRUE(fin);
  19973. }
  19974. }
  19975. TEST(WebSocketTest, ControlFrameValidation) {
  19976. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  19977. // payload length <= 125.
  19978. // Ping with FIN=0 - must be rejected
  19979. {
  19980. detail::BufferStream strm;
  19981. std::string frame;
  19982. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  19983. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19984. strm.write(frame.data(), frame.size());
  19985. ws::Opcode opcode;
  19986. std::string payload;
  19987. bool fin;
  19988. EXPECT_EQ(
  19989. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19990. ws::impl::FrameRead::Fail);
  19991. }
  19992. // Close with FIN=0 - must be rejected
  19993. {
  19994. detail::BufferStream strm;
  19995. std::string frame;
  19996. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  19997. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19998. strm.write(frame.data(), frame.size());
  19999. ws::Opcode opcode;
  20000. std::string payload;
  20001. bool fin;
  20002. EXPECT_EQ(
  20003. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20004. ws::impl::FrameRead::Fail);
  20005. }
  20006. // Ping with payload_len=126 (extended length) - must be rejected
  20007. {
  20008. detail::BufferStream strm;
  20009. std::string frame;
  20010. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20011. frame += static_cast<char>(126); // payload_len=126 (>125)
  20012. frame += static_cast<char>(0x00); // extended length high byte
  20013. frame += static_cast<char>(126); // extended length low byte
  20014. frame += std::string(126, 'x');
  20015. strm.write(frame.data(), frame.size());
  20016. ws::Opcode opcode;
  20017. std::string payload;
  20018. bool fin;
  20019. EXPECT_EQ(
  20020. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20021. ws::impl::FrameRead::Fail);
  20022. }
  20023. // Ping with FIN=1 and payload_len=125 - should succeed
  20024. {
  20025. detail::BufferStream strm;
  20026. std::string frame;
  20027. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20028. frame += static_cast<char>(125); // payload_len=125
  20029. frame += std::string(125, 'x');
  20030. strm.write(frame.data(), frame.size());
  20031. ws::Opcode opcode;
  20032. std::string payload;
  20033. bool fin;
  20034. EXPECT_EQ(
  20035. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20036. ws::impl::FrameRead::Ok);
  20037. EXPECT_EQ(ws::Opcode::Ping, opcode);
  20038. EXPECT_EQ(125u, payload.size());
  20039. EXPECT_TRUE(fin);
  20040. }
  20041. }
  20042. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  20043. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  20044. // length MUST be 0.
  20045. // MSB set - must be rejected
  20046. {
  20047. detail::BufferStream strm;
  20048. std::string frame;
  20049. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20050. frame += static_cast<char>(127); // 64-bit extended length
  20051. frame += static_cast<char>(0x80); // MSB set (invalid)
  20052. frame += std::string(7, '\0'); // remaining 7 bytes of length
  20053. strm.write(frame.data(), frame.size());
  20054. ws::Opcode opcode;
  20055. std::string payload;
  20056. bool fin;
  20057. EXPECT_EQ(
  20058. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20059. ws::impl::FrameRead::Fail);
  20060. }
  20061. // MSB clear - should pass length parsing (will be rejected by max_len,
  20062. // but that's a different check; use a small length to verify)
  20063. {
  20064. detail::BufferStream strm;
  20065. std::string frame;
  20066. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20067. frame += static_cast<char>(127); // 64-bit extended length
  20068. frame += std::string(7, '\0'); // high bytes = 0
  20069. frame += static_cast<char>(0x03); // length = 3
  20070. frame += "abc";
  20071. strm.write(frame.data(), frame.size());
  20072. ws::Opcode opcode;
  20073. std::string payload;
  20074. bool fin;
  20075. EXPECT_EQ(
  20076. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20077. ws::impl::FrameRead::Ok);
  20078. EXPECT_EQ(ws::Opcode::Text, opcode);
  20079. EXPECT_EQ("abc", payload);
  20080. }
  20081. }
  20082. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  20083. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  20084. // Valid UTF-8
  20085. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  20086. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  20087. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  20088. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  20089. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  20090. // Invalid UTF-8
  20091. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  20092. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  20093. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  20094. EXPECT_FALSE(
  20095. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  20096. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  20097. }
  20098. TEST(WebSocketTest, ConnectAndDisconnect) {
  20099. Server svr;
  20100. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20101. std::string msg;
  20102. while (ws.read(msg)) {}
  20103. });
  20104. auto port = svr.bind_to_any_port(HOST);
  20105. std::thread t([&]() { svr.listen_after_bind(); });
  20106. svr.wait_until_ready();
  20107. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20108. auto res = client.connect();
  20109. ASSERT_TRUE(res);
  20110. EXPECT_EQ(Error::Success, res.error());
  20111. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  20112. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  20113. EXPECT_TRUE(client.is_open());
  20114. client.close();
  20115. EXPECT_FALSE(client.is_open());
  20116. svr.stop();
  20117. t.join();
  20118. }
  20119. TEST(WebSocketTest, ValidURL) {
  20120. ws::WebSocketClient ws1("ws://localhost:8080/path");
  20121. EXPECT_TRUE(ws1.is_valid());
  20122. ws::WebSocketClient ws2("ws://example.com/path");
  20123. EXPECT_TRUE(ws2.is_valid());
  20124. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  20125. EXPECT_TRUE(ws3.is_valid());
  20126. #ifdef CPPHTTPLIB_SSL_ENABLED
  20127. ws::WebSocketClient wss1("wss://example.com/path");
  20128. EXPECT_TRUE(wss1.is_valid());
  20129. ws::WebSocketClient wss2("wss://example.com:443/path");
  20130. EXPECT_TRUE(wss2.is_valid());
  20131. #endif
  20132. }
  20133. TEST(WebSocketTest, InvalidURL) {
  20134. // No scheme
  20135. ws::WebSocketClient ws1("localhost:8080/path");
  20136. EXPECT_FALSE(ws1.is_valid());
  20137. // No path
  20138. ws::WebSocketClient ws2("ws://localhost:8080");
  20139. EXPECT_FALSE(ws2.is_valid());
  20140. // Empty string
  20141. ws::WebSocketClient ws3("");
  20142. EXPECT_FALSE(ws3.is_valid());
  20143. // Missing host
  20144. ws::WebSocketClient ws4("ws://:8080/path");
  20145. EXPECT_FALSE(ws4.is_valid());
  20146. // Port number overflow — should not crash
  20147. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  20148. EXPECT_FALSE(ws5.is_valid());
  20149. // Port out of range
  20150. ws::WebSocketClient ws6("ws://localhost:99999/path");
  20151. EXPECT_FALSE(ws6.is_valid());
  20152. }
  20153. TEST(WebSocketTest, UnsupportedScheme) {
  20154. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  20155. ws::WebSocketClient ws1("http://localhost:8080/path");
  20156. EXPECT_FALSE(ws1.is_valid());
  20157. ws::WebSocketClient ws2("https://localhost:8080/path");
  20158. EXPECT_FALSE(ws2.is_valid());
  20159. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  20160. EXPECT_FALSE(ws3.is_valid());
  20161. #else
  20162. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  20163. std::invalid_argument);
  20164. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  20165. std::invalid_argument);
  20166. #endif
  20167. }
  20168. TEST(WebSocketTest, ConnectWhenInvalid) {
  20169. ws::WebSocketClient ws("not a valid url");
  20170. EXPECT_FALSE(ws.is_valid());
  20171. auto res = ws.connect();
  20172. EXPECT_FALSE(res);
  20173. EXPECT_EQ(Error::Connection, res.error());
  20174. EXPECT_EQ(-1, res.status());
  20175. }
  20176. TEST(WebSocketTest, ConnectRefusedReportsError) {
  20177. // Grab a port that is free, then close it again so nothing listens there
  20178. Server svr;
  20179. auto port = svr.bind_to_any_port(HOST);
  20180. svr.stop();
  20181. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20182. auto res = client.connect();
  20183. ASSERT_FALSE(res);
  20184. EXPECT_EQ(Error::Connection, res.error());
  20185. EXPECT_EQ(-1, res.status());
  20186. }
  20187. TEST(WebSocketTest, DefaultPort) {
  20188. ws::WebSocketClient ws1("ws://example.com/path");
  20189. EXPECT_TRUE(ws1.is_valid());
  20190. // ws:// defaults to port 80 (verified by successful parse)
  20191. #ifdef CPPHTTPLIB_SSL_ENABLED
  20192. ws::WebSocketClient ws2("wss://example.com/path");
  20193. EXPECT_TRUE(ws2.is_valid());
  20194. // wss:// defaults to port 443 (verified by successful parse)
  20195. #endif
  20196. }
  20197. TEST(WebSocketTest, IPv6LiteralAddress) {
  20198. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  20199. EXPECT_TRUE(ws1.is_valid());
  20200. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  20201. EXPECT_TRUE(ws2.is_valid());
  20202. }
  20203. TEST(WebSocketTest, ComplexPath) {
  20204. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  20205. EXPECT_TRUE(ws1.is_valid());
  20206. ws::WebSocketClient ws2("ws://localhost:8080/");
  20207. EXPECT_TRUE(ws2.is_valid());
  20208. }
  20209. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  20210. Server svr;
  20211. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20212. std::string msg;
  20213. while (ws.read(msg)) {}
  20214. });
  20215. auto port = svr.bind_to_any_port(HOST);
  20216. std::thread t([&]() { svr.listen_after_bind(); });
  20217. svr.wait_until_ready();
  20218. auto another_host = "example.com";
  20219. auto wrong_ip = "192.0.2.1";
  20220. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20221. client.set_hostname_addr_map({{another_host, wrong_ip}});
  20222. ASSERT_TRUE(client.connect());
  20223. EXPECT_TRUE(client.is_open());
  20224. client.close();
  20225. svr.stop();
  20226. t.join();
  20227. }
  20228. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  20229. Server svr;
  20230. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20231. std::string msg;
  20232. while (ws.read(msg)) {}
  20233. });
  20234. auto port = svr.bind_to_any_port(HOST);
  20235. std::thread t([&]() { svr.listen_after_bind(); });
  20236. svr.wait_until_ready();
  20237. auto wrong_ip = "192.0.2.1";
  20238. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20239. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  20240. client.set_connection_timeout(1);
  20241. client.set_read_timeout(1);
  20242. client.set_write_timeout(1);
  20243. EXPECT_FALSE(client.connect());
  20244. EXPECT_FALSE(client.is_open());
  20245. svr.stop();
  20246. t.join();
  20247. }
  20248. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  20249. // A mapped value that is not an IP literal must be resolved. HOST resolves
  20250. // from the hosts file, so this test needs no external DNS. "target.invalid"
  20251. // (RFC 6761) is only a map key and the Host header value.
  20252. auto host = "target.invalid";
  20253. Server svr;
  20254. std::string received_host;
  20255. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20256. received_host = req.get_header_value("Host");
  20257. std::string msg;
  20258. while (ws.read(msg)) {}
  20259. });
  20260. auto port = svr.bind_to_any_port(HOST);
  20261. std::thread t([&]() { svr.listen_after_bind(); });
  20262. // ASSERT_* below returns from the test body, which would leave t joinable
  20263. // and make ~thread call std::terminate.
  20264. auto se = detail::scope_exit([&] {
  20265. svr.stop();
  20266. if (t.joinable()) { t.join(); }
  20267. });
  20268. svr.wait_until_ready();
  20269. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  20270. std::to_string(port) + "/ws");
  20271. client.set_hostname_addr_map({{host, HOST}});
  20272. ASSERT_TRUE(client.connect());
  20273. EXPECT_TRUE(client.is_open());
  20274. client.close();
  20275. svr.stop();
  20276. t.join();
  20277. // The mapping only redirects the connection; the identity stays host_.
  20278. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  20279. }
  20280. class WebSocketIntegrationTest : public ::testing::Test {
  20281. protected:
  20282. void SetUp() override {
  20283. server_ = httplib::detail::make_unique<Server>();
  20284. setup_server();
  20285. start_server();
  20286. }
  20287. void TearDown() override {
  20288. server_->stop();
  20289. if (server_thread_.joinable()) { server_thread_.join(); }
  20290. }
  20291. void setup_server() {
  20292. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20293. std::string msg;
  20294. ws::ReadResult ret;
  20295. while ((ret = ws.read(msg))) {
  20296. if (ret == ws::Binary) {
  20297. ws.send(msg.data(), msg.size());
  20298. } else {
  20299. ws.send(msg);
  20300. }
  20301. }
  20302. });
  20303. server_->WebSocket("/ws-echo-string",
  20304. [](const Request &, ws::WebSocket &ws) {
  20305. std::string msg;
  20306. while (ws.read(msg)) {
  20307. ws.send("echo: " + msg);
  20308. }
  20309. });
  20310. server_->WebSocket(
  20311. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  20312. // Echo back request metadata
  20313. ws.send("path:" + req.path);
  20314. ws.send("header:" + req.get_header_value("X-Test-Header"));
  20315. std::string msg;
  20316. while (ws.read(msg)) {}
  20317. });
  20318. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  20319. std::string msg;
  20320. ws.read(msg); // wait for a message
  20321. ws.close();
  20322. });
  20323. server_->WebSocket("/ws-close-status",
  20324. [](const Request &, ws::WebSocket &ws) {
  20325. std::string msg;
  20326. ws.read(msg); // wait for a message
  20327. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  20328. });
  20329. server_->WebSocket(
  20330. "/ws-subprotocol",
  20331. [](const Request &, ws::WebSocket &ws) {
  20332. std::string msg;
  20333. while (ws.read(msg)) {
  20334. ws.send(msg);
  20335. }
  20336. },
  20337. [](const std::vector<std::string> &protocols) -> std::string {
  20338. for (const auto &p : protocols) {
  20339. if (p == "graphql-ws") { return p; }
  20340. }
  20341. return "";
  20342. });
  20343. server_->WebSocket(
  20344. "/ws-subprotocol-unoffered",
  20345. [](const Request &, ws::WebSocket &ws) {
  20346. std::string msg;
  20347. while (ws.read(msg)) {
  20348. ws.send(msg);
  20349. }
  20350. },
  20351. [](const std::vector<std::string> &) -> std::string {
  20352. return "admin";
  20353. });
  20354. }
  20355. void start_server() {
  20356. port_ = server_->bind_to_any_port(HOST);
  20357. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20358. server_->wait_until_ready();
  20359. }
  20360. std::unique_ptr<Server> server_;
  20361. std::thread server_thread_;
  20362. int port_ = 0;
  20363. };
  20364. TEST_F(WebSocketIntegrationTest, TextEcho) {
  20365. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20366. "/ws-echo");
  20367. ASSERT_TRUE(client.connect());
  20368. ASSERT_TRUE(client.is_open());
  20369. ASSERT_TRUE(client.send("Hello WebSocket"));
  20370. std::string msg;
  20371. EXPECT_EQ(ws::Text, client.read(msg));
  20372. EXPECT_EQ("Hello WebSocket", msg);
  20373. client.close();
  20374. }
  20375. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  20376. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20377. "/ws-echo");
  20378. ASSERT_TRUE(client.connect());
  20379. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  20380. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  20381. std::string msg;
  20382. EXPECT_EQ(ws::Binary, client.read(msg));
  20383. EXPECT_EQ(binary_data, msg);
  20384. client.close();
  20385. }
  20386. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  20387. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20388. "/ws-echo");
  20389. ASSERT_TRUE(client.connect());
  20390. for (int i = 0; i < 10; i++) {
  20391. auto text = "message " + std::to_string(i);
  20392. ASSERT_TRUE(client.send(text));
  20393. std::string msg;
  20394. ASSERT_TRUE(client.read(msg));
  20395. EXPECT_EQ(text, msg);
  20396. }
  20397. client.close();
  20398. }
  20399. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  20400. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20401. "/ws-close");
  20402. ASSERT_TRUE(client.connect());
  20403. // Send a message to trigger the server to close
  20404. ASSERT_TRUE(client.send("trigger close"));
  20405. // The server will close, so read should return false
  20406. std::string msg;
  20407. EXPECT_FALSE(client.read(msg));
  20408. EXPECT_FALSE(client.is_open());
  20409. }
  20410. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  20411. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20412. "/ws-echo");
  20413. ASSERT_TRUE(client.connect());
  20414. // 128KB message
  20415. std::string large_data(128 * 1024, 'X');
  20416. ASSERT_TRUE(client.send(large_data));
  20417. std::string msg;
  20418. ASSERT_TRUE(client.read(msg));
  20419. EXPECT_EQ(large_data, msg);
  20420. client.close();
  20421. }
  20422. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  20423. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20424. "/ws-echo");
  20425. ASSERT_TRUE(client.connect());
  20426. const int num_threads = 4;
  20427. std::vector<std::thread> threads;
  20428. std::atomic<int> send_count{0};
  20429. for (int t = 0; t < num_threads; t++) {
  20430. threads.emplace_back([&client, &send_count, t]() {
  20431. for (int i = 0; i < 5; i++) {
  20432. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  20433. if (client.send(text)) { send_count++; }
  20434. }
  20435. });
  20436. }
  20437. for (auto &th : threads) {
  20438. th.join();
  20439. }
  20440. int received = 0;
  20441. std::string msg;
  20442. while (received < send_count.load()) {
  20443. if (!client.read(msg)) { break; }
  20444. received++;
  20445. }
  20446. EXPECT_EQ(send_count.load(), received);
  20447. client.close();
  20448. }
  20449. TEST_F(WebSocketIntegrationTest, ReadString) {
  20450. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20451. "/ws-echo-string");
  20452. ASSERT_TRUE(client.connect());
  20453. ASSERT_TRUE(client.send("hello"));
  20454. std::string msg;
  20455. ASSERT_TRUE(client.read(msg));
  20456. EXPECT_EQ("echo: hello", msg);
  20457. ASSERT_TRUE(client.send("world"));
  20458. ASSERT_TRUE(client.read(msg));
  20459. EXPECT_EQ("echo: world", msg);
  20460. client.close();
  20461. }
  20462. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  20463. Headers headers = {{"X-Test-Header", "test-value"}};
  20464. ws::WebSocketClient client(
  20465. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  20466. ASSERT_TRUE(client.connect());
  20467. std::string msg;
  20468. ASSERT_TRUE(client.read(msg));
  20469. EXPECT_EQ("path:/ws-request-info", msg);
  20470. ASSERT_TRUE(client.read(msg));
  20471. EXPECT_EQ("header:test-value", msg);
  20472. client.close();
  20473. }
  20474. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  20475. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20476. "/ws-echo");
  20477. client.set_read_timeout(1, 0); // 1 second
  20478. ASSERT_TRUE(client.connect());
  20479. // Don't send anything — server echo handler waits for a message, so read()
  20480. // should time out. The connection survives it: nothing was consumed.
  20481. std::string msg;
  20482. EXPECT_EQ(client.read(msg), ws::Timeout);
  20483. EXPECT_TRUE(client.is_open());
  20484. // And it is still usable afterwards.
  20485. EXPECT_TRUE(client.send("after timeout"));
  20486. EXPECT_EQ(client.read(msg), ws::Text);
  20487. EXPECT_EQ(msg, "after timeout");
  20488. }
  20489. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  20490. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20491. "/ws-echo");
  20492. client.set_read_timeout(1, 0);
  20493. ASSERT_TRUE(client.connect());
  20494. ASSERT_TRUE(client.send("first"));
  20495. std::string msg;
  20496. ASSERT_EQ(client.read(msg), ws::Text);
  20497. ASSERT_EQ(msg, "first");
  20498. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  20499. // not be used with a read timeout: it would reprocess the previous message.
  20500. EXPECT_EQ(client.read(msg), ws::Timeout);
  20501. EXPECT_EQ(msg, "first");
  20502. }
  20503. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  20504. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20505. "/ws-echo");
  20506. ASSERT_TRUE(client.connect());
  20507. // Setting it once the connection is open reaches the live stream, not just
  20508. // the seed for the next connect().
  20509. client.set_read_timeout(1, 0);
  20510. std::string msg;
  20511. EXPECT_EQ(client.read(msg), ws::Timeout);
  20512. EXPECT_TRUE(client.is_open());
  20513. }
  20514. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  20515. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20516. "/ws-echo");
  20517. client.set_read_timeout(5, 0);
  20518. ASSERT_TRUE(client.connect());
  20519. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20520. // The server should reject it and close the connection.
  20521. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  20522. client.send(oversized);
  20523. // The server's read() should have failed due to payload limit,
  20524. // so our read() should return false (connection closed).
  20525. std::string msg;
  20526. EXPECT_FALSE(client.read(msg));
  20527. }
  20528. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  20529. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20530. "/ws-echo");
  20531. client.set_read_timeout(10, 0);
  20532. ASSERT_TRUE(client.connect());
  20533. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20534. // This should succeed.
  20535. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  20536. ASSERT_TRUE(client.send(at_limit));
  20537. std::string msg;
  20538. ASSERT_TRUE(client.read(msg));
  20539. EXPECT_EQ(at_limit.size(), msg.size());
  20540. client.close();
  20541. }
  20542. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  20543. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20544. "/nonexistent");
  20545. auto res = client.connect();
  20546. EXPECT_FALSE(res);
  20547. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20548. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  20549. EXPECT_FALSE(client.is_open());
  20550. }
  20551. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  20552. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20553. "/ws-echo");
  20554. ASSERT_TRUE(client.connect());
  20555. ASSERT_TRUE(client.send(""));
  20556. std::string msg;
  20557. EXPECT_EQ(ws::Text, client.read(msg));
  20558. EXPECT_EQ("", msg);
  20559. client.close();
  20560. }
  20561. TEST_F(WebSocketIntegrationTest, Reconnect) {
  20562. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20563. "/ws-echo");
  20564. // First connection
  20565. ASSERT_TRUE(client.connect());
  20566. ASSERT_TRUE(client.send("first"));
  20567. std::string msg;
  20568. ASSERT_TRUE(client.read(msg));
  20569. EXPECT_EQ("first", msg);
  20570. client.close();
  20571. EXPECT_FALSE(client.is_open());
  20572. // Reconnect using the same client object
  20573. ASSERT_TRUE(client.connect());
  20574. ASSERT_TRUE(client.is_open());
  20575. ASSERT_TRUE(client.send("second"));
  20576. ASSERT_TRUE(client.read(msg));
  20577. EXPECT_EQ("second", msg);
  20578. client.close();
  20579. }
  20580. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  20581. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20582. "/ws-close-status");
  20583. ASSERT_TRUE(client.connect());
  20584. // Trigger the server to close with GoingAway status
  20585. ASSERT_TRUE(client.send("trigger"));
  20586. // read() should return false after receiving the close frame
  20587. std::string msg;
  20588. EXPECT_FALSE(client.read(msg));
  20589. EXPECT_FALSE(client.is_open());
  20590. }
  20591. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  20592. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20593. "/ws-echo");
  20594. ASSERT_TRUE(client.connect());
  20595. client.close(ws::CloseStatus::GoingAway, "client leaving");
  20596. EXPECT_FALSE(client.is_open());
  20597. }
  20598. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  20599. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  20600. ws::WebSocketClient client(
  20601. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20602. ASSERT_TRUE(client.connect());
  20603. // Server should have selected graphql-ws
  20604. EXPECT_EQ("graphql-ws", client.subprotocol());
  20605. client.close();
  20606. }
  20607. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  20608. Headers headers;
  20609. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  20610. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  20611. ws::WebSocketClient client(
  20612. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20613. ASSERT_TRUE(client.connect());
  20614. // The offer on the second field line counts too, so graphql-ws is selected
  20615. EXPECT_EQ("graphql-ws", client.subprotocol());
  20616. client.close();
  20617. }
  20618. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  20619. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  20620. ws::WebSocketClient client(
  20621. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20622. ASSERT_TRUE(client.connect());
  20623. // Server should not have selected any subprotocol
  20624. EXPECT_TRUE(client.subprotocol().empty());
  20625. client.close();
  20626. }
  20627. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  20628. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  20629. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20630. "/ws-subprotocol-unoffered",
  20631. headers);
  20632. ASSERT_TRUE(client.connect());
  20633. EXPECT_TRUE(client.subprotocol().empty());
  20634. client.close();
  20635. }
  20636. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  20637. // Connect without requesting any subprotocol
  20638. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20639. "/ws-subprotocol");
  20640. ASSERT_TRUE(client.connect());
  20641. EXPECT_TRUE(client.subprotocol().empty());
  20642. client.close();
  20643. }
  20644. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  20645. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20646. "/ws-echo");
  20647. client.set_tcp_nodelay(true);
  20648. client.set_connection_timeout(3, 0);
  20649. bool socket_options_called = false;
  20650. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  20651. ASSERT_TRUE(client.connect());
  20652. ASSERT_TRUE(client.is_open());
  20653. EXPECT_TRUE(socket_options_called);
  20654. ASSERT_TRUE(client.send("hello"));
  20655. std::string msg;
  20656. auto result = client.read(msg);
  20657. EXPECT_EQ(result, ws::ReadResult::Text);
  20658. EXPECT_EQ(msg, "hello");
  20659. client.close();
  20660. }
  20661. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  20662. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20663. "/ws-echo");
  20664. client.set_connection_timeout(std::chrono::seconds(3));
  20665. client.set_write_timeout(std::chrono::seconds(3));
  20666. // A sub-second remainder exercises the seconds/microseconds split.
  20667. client.set_read_timeout(std::chrono::milliseconds(1500));
  20668. ASSERT_TRUE(client.connect());
  20669. auto start = std::chrono::steady_clock::now();
  20670. std::string msg;
  20671. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  20672. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  20673. std::chrono::steady_clock::now() - start)
  20674. .count();
  20675. // Above 1s so that dropping the microseconds half of the split fails here.
  20676. // Ignoring the setter altogether would not reach this line at all: a client
  20677. // waits forever by default.
  20678. EXPECT_GE(elapsed, 1400);
  20679. EXPECT_LT(elapsed, 30000);
  20680. }
  20681. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  20682. Server svr;
  20683. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  20684. if (!req.has_header("Authorization")) {
  20685. res.status = StatusCode::Unauthorized_401;
  20686. res.set_content("Unauthorized", "text/plain");
  20687. return Server::HandlerResponse::Handled;
  20688. }
  20689. return Server::HandlerResponse::Unhandled;
  20690. });
  20691. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20692. std::string msg;
  20693. while (ws.read(msg)) {
  20694. ws.send(msg);
  20695. }
  20696. });
  20697. auto port = svr.bind_to_any_port("localhost");
  20698. std::thread t([&]() { svr.listen_after_bind(); });
  20699. svr.wait_until_ready();
  20700. // Without Authorization header - should be rejected before upgrade
  20701. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  20702. EXPECT_FALSE(client1.connect());
  20703. // The rejection is framed like any other HTTP response
  20704. {
  20705. Client cli("localhost", port);
  20706. Headers headers = {{"Upgrade", "websocket"},
  20707. {"Connection", "Upgrade"},
  20708. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20709. {"Sec-WebSocket-Version", "13"}};
  20710. auto res = cli.Get("/ws", headers);
  20711. ASSERT_TRUE(res);
  20712. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20713. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20714. EXPECT_EQ("Unauthorized", res->body);
  20715. }
  20716. // With Authorization header - should succeed
  20717. Headers headers = {{"Authorization", "Bearer token123"}};
  20718. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  20719. headers);
  20720. ASSERT_TRUE(client2.connect());
  20721. ASSERT_TRUE(client2.send("hello"));
  20722. std::string msg;
  20723. ASSERT_TRUE(client2.read(msg));
  20724. EXPECT_EQ("hello", msg);
  20725. client2.close();
  20726. svr.stop();
  20727. t.join();
  20728. }
  20729. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  20730. Server svr;
  20731. std::atomic<int> pre_request_calls{0};
  20732. std::atomic<bool> route_matched{false};
  20733. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  20734. pre_request_calls++;
  20735. if (req.matched_route == "/ws/:id") { route_matched = true; }
  20736. if (req.get_header_value("Authorization") != "Bearer token123") {
  20737. res.status = StatusCode::Unauthorized_401;
  20738. res.set_content("Unauthorized", "text/plain");
  20739. return Server::HandlerResponse::Handled;
  20740. }
  20741. return Server::HandlerResponse::Unhandled;
  20742. });
  20743. std::atomic<bool> handler_called{false};
  20744. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  20745. handler_called = true;
  20746. ws.send(req.matched_route + " " + req.path_params.at("id"));
  20747. });
  20748. auto port = svr.bind_to_any_port("localhost");
  20749. std::thread t([&]() { svr.listen_after_bind(); });
  20750. svr.wait_until_ready();
  20751. // Without Authorization header - should be rejected before upgrade
  20752. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  20753. "/ws/1");
  20754. EXPECT_FALSE(client1.connect());
  20755. EXPECT_FALSE(handler_called);
  20756. EXPECT_EQ(1, pre_request_calls);
  20757. EXPECT_TRUE(route_matched);
  20758. // The rejection is an ordinary HTTP response, not a protocol switch
  20759. {
  20760. Client cli("localhost", port);
  20761. Headers headers = {{"Upgrade", "websocket"},
  20762. {"Connection", "Upgrade"},
  20763. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20764. {"Sec-WebSocket-Version", "13"}};
  20765. auto res = cli.Get("/ws/1", headers);
  20766. ASSERT_TRUE(res);
  20767. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20768. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20769. EXPECT_EQ("Unauthorized", res->body);
  20770. }
  20771. EXPECT_FALSE(handler_called);
  20772. // With Authorization header - should succeed
  20773. Headers headers = {{"Authorization", "Bearer token123"}};
  20774. ws::WebSocketClient client2(
  20775. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  20776. ASSERT_TRUE(client2.connect());
  20777. std::string msg;
  20778. ASSERT_TRUE(client2.read(msg));
  20779. EXPECT_EQ("/ws/:id 2", msg);
  20780. EXPECT_TRUE(handler_called);
  20781. client2.close();
  20782. svr.stop();
  20783. t.join();
  20784. }
  20785. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  20786. Server svr;
  20787. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20788. // A read timeout is how a handler gets control back. Without it, a handler
  20789. // parked in read() can never write on the connection it is reading.
  20790. ws.set_read_timeout(std::chrono::milliseconds(100));
  20791. std::string msg;
  20792. while (ws.is_open()) {
  20793. auto r = ws.read(msg);
  20794. if (r == httplib::ws::Timeout) {
  20795. ws.send("tick");
  20796. continue;
  20797. }
  20798. if (r == httplib::ws::Fail) { break; }
  20799. ws.send(msg);
  20800. }
  20801. });
  20802. auto port = svr.bind_to_any_port("localhost");
  20803. std::thread t([&]() { svr.listen_after_bind(); });
  20804. svr.wait_until_ready();
  20805. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20806. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  20807. ASSERT_TRUE(client.connect());
  20808. // The client sends nothing, so anything it receives came out of the
  20809. // handler's timeout path.
  20810. std::string msg;
  20811. ASSERT_EQ(client.read(msg), ws::Text);
  20812. EXPECT_EQ("tick", msg);
  20813. client.close();
  20814. svr.stop();
  20815. t.join();
  20816. }
  20817. // Stream::read may return fewer bytes than asked for. This is that contract at
  20818. // its worst -- one byte per call -- which is what a frame header straddling a
  20819. // read buffer's boundary looks like to the frame parser.
  20820. class WsByteAtATimeStream : public Stream {
  20821. public:
  20822. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  20823. bool is_readable() const override { return true; }
  20824. bool wait_readable() const override { return true; }
  20825. bool wait_writable() const override { return true; }
  20826. ssize_t read(char *ptr, size_t size) override {
  20827. if (size == 0 || pos_ >= data_.size()) { return 0; }
  20828. *ptr = data_[pos_++];
  20829. return 1;
  20830. }
  20831. ssize_t write(const char *, size_t size) override {
  20832. return static_cast<ssize_t>(size);
  20833. }
  20834. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20835. ip = "127.0.0.1";
  20836. port = 0;
  20837. }
  20838. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20839. ip = "127.0.0.1";
  20840. port = 0;
  20841. }
  20842. socket_t socket() const override { return INVALID_SOCKET; }
  20843. time_t duration() const override { return 0; }
  20844. private:
  20845. std::string data_;
  20846. size_t pos_ = 0;
  20847. };
  20848. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  20849. // A 200-byte payload uses the 16-bit extended length, so the header, the
  20850. // length and the mask key are all multi-byte fields here. Each used to be
  20851. // read with a single read() call, which fails as soon as one is split.
  20852. std::string body(200, 'x');
  20853. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  20854. std::string frame;
  20855. frame += static_cast<char>(0x81); // FIN + Text
  20856. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  20857. frame += static_cast<char>(body.size() >> 8);
  20858. frame += static_cast<char>(body.size() & 0xff);
  20859. for (size_t i = 0; i < 4; i++) {
  20860. frame += static_cast<char>(mask[i]);
  20861. }
  20862. for (size_t i = 0; i < body.size(); i++) {
  20863. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  20864. }
  20865. WsByteAtATimeStream strm(frame);
  20866. ws::Opcode opcode;
  20867. std::string payload;
  20868. bool fin = false;
  20869. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  20870. /*expect_masked=*/true, 1024),
  20871. ws::impl::FrameRead::Ok);
  20872. EXPECT_TRUE(fin);
  20873. EXPECT_EQ(opcode, ws::Opcode::Text);
  20874. EXPECT_EQ(payload, body);
  20875. }
  20876. TEST(WebSocketTest, QueryStringInHandshake) {
  20877. Server svr;
  20878. std::mutex mtx;
  20879. std::string received_target;
  20880. std::string received_token;
  20881. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20882. {
  20883. std::lock_guard<std::mutex> lock(mtx);
  20884. received_target = req.target;
  20885. if (req.has_param("token")) {
  20886. received_token = req.get_param_value("token");
  20887. }
  20888. }
  20889. std::string msg;
  20890. while (ws.read(msg)) {
  20891. ws.send(msg);
  20892. }
  20893. });
  20894. auto port = svr.bind_to_any_port("localhost");
  20895. std::thread t([&]() { svr.listen_after_bind(); });
  20896. svr.wait_until_ready();
  20897. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  20898. "/ws?token=ABC&session=123");
  20899. ASSERT_TRUE(client.connect());
  20900. // Round-trip ensures the handler has run and captured the request.
  20901. ASSERT_TRUE(client.send("hello"));
  20902. std::string msg;
  20903. ASSERT_TRUE(client.read(msg));
  20904. EXPECT_EQ("hello", msg);
  20905. client.close();
  20906. {
  20907. std::lock_guard<std::mutex> lock(mtx);
  20908. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  20909. EXPECT_EQ("ABC", received_token);
  20910. }
  20911. svr.stop();
  20912. t.join();
  20913. }
  20914. // Run a handshake against a throwaway server and hand the request the server
  20915. // received back to the caller, so tests can assert on the headers the client
  20916. // actually put on the wire.
  20917. static void capture_websocket_handshake_request(
  20918. const Headers &client_headers,
  20919. std::function<void(const Request &, int port)> verify) {
  20920. Server svr;
  20921. std::mutex mtx;
  20922. Request received;
  20923. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20924. {
  20925. std::lock_guard<std::mutex> lock(mtx);
  20926. received = req;
  20927. }
  20928. std::string msg;
  20929. while (ws.read(msg)) {
  20930. ws.send(msg);
  20931. }
  20932. });
  20933. auto port = svr.bind_to_any_port("localhost");
  20934. std::thread t([&]() { svr.listen_after_bind(); });
  20935. auto se = detail::scope_exit([&] {
  20936. svr.stop();
  20937. t.join();
  20938. });
  20939. svr.wait_until_ready();
  20940. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  20941. client_headers);
  20942. ASSERT_TRUE(client.connect());
  20943. ASSERT_TRUE(client.send("hello"));
  20944. std::string msg;
  20945. ASSERT_TRUE(client.read(msg));
  20946. client.close();
  20947. {
  20948. std::lock_guard<std::mutex> lock(mtx);
  20949. verify(received, port);
  20950. }
  20951. }
  20952. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  20953. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  20954. // Non-default port must be present in the Host header. Default ports
  20955. // (80/443) are omitted; that logic is covered by
  20956. // MakeHostAndPortStringTest.
  20957. EXPECT_EQ("localhost:" + std::to_string(port),
  20958. req.get_header_value("Host"));
  20959. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  20960. req.get_header_value("User-Agent"));
  20961. EXPECT_FALSE(req.has_header("Accept"));
  20962. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  20963. EXPECT_FALSE(req.has_header("Content-Length"));
  20964. });
  20965. }
  20966. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  20967. capture_websocket_handshake_request(
  20968. {{"Host", "example.com"},
  20969. {"User-Agent", "custom-agent"},
  20970. {"X-Custom", "value"}},
  20971. [](const Request &req, int) {
  20972. EXPECT_EQ("example.com", req.get_header_value("Host"));
  20973. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  20974. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  20975. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  20976. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  20977. });
  20978. }
  20979. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  20980. capture_websocket_handshake_request(
  20981. {{"Upgrade", "bogus"},
  20982. {"Connection", "close"},
  20983. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  20984. {"Sec-WebSocket-Version", "8"}},
  20985. [](const Request &req, int) {
  20986. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  20987. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  20988. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  20989. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  20990. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  20991. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  20992. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  20993. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  20994. req.get_header_value("Sec-WebSocket-Key"));
  20995. });
  20996. }
  20997. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  20998. // A header the client refuses to send must abort the handshake before any
  20999. // part of it reaches the wire; a lone request line would otherwise sit in
  21000. // the peer's buffer as a truncated request.
  21001. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21002. ASSERT_NE(INVALID_SOCKET, srv);
  21003. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  21004. sockaddr_in addr{};
  21005. addr.sin_family = AF_INET;
  21006. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  21007. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21008. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  21009. ASSERT_EQ(0, ::listen(srv, 1));
  21010. sockaddr_in bound{};
  21011. socklen_t bound_len = sizeof(bound);
  21012. ASSERT_EQ(
  21013. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  21014. auto port = ntohs(bound.sin_port);
  21015. ssize_t received = -1;
  21016. std::thread t([&] {
  21017. // Bound every blocking call so a regression fails the test with a bad
  21018. // value instead of hanging the suite.
  21019. fd_set rfds;
  21020. FD_ZERO(&rfds);
  21021. FD_SET(srv, &rfds);
  21022. timeval tv{5, 0};
  21023. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  21024. 0) {
  21025. return;
  21026. }
  21027. sockaddr_in cli_addr{};
  21028. socklen_t cli_len = sizeof(cli_addr);
  21029. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21030. if (cli == INVALID_SOCKET) { return; }
  21031. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  21032. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21033. char buf[4096];
  21034. received = ::recv(cli, buf, sizeof(buf), 0);
  21035. });
  21036. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  21037. // connect() has already shut the socket down by the time it returns false,
  21038. // so the peer sees EOF without waiting for the client to be destroyed.
  21039. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  21040. {{"X-Bad", "a\r\nInjected: 1"}});
  21041. EXPECT_FALSE(client.connect());
  21042. t.join();
  21043. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  21044. EXPECT_EQ(0, received);
  21045. }
  21046. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  21047. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  21048. // contains "upgrade" as a substring is a different token and must not
  21049. // start a WebSocket handshake.
  21050. auto make_request = [](const std::vector<std::string> &connection_values) {
  21051. Request req;
  21052. req.method = "GET";
  21053. req.headers.emplace("Upgrade", "websocket");
  21054. for (const auto &value : connection_values) {
  21055. req.headers.emplace("Connection", value);
  21056. }
  21057. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21058. req.headers.emplace("Sec-WebSocket-Version", "13");
  21059. return req;
  21060. };
  21061. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  21062. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  21063. EXPECT_TRUE(
  21064. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  21065. EXPECT_TRUE(
  21066. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  21067. EXPECT_TRUE(
  21068. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  21069. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  21070. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  21071. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  21072. EXPECT_FALSE(
  21073. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  21074. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  21075. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21076. }
  21077. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  21078. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  21079. // asks recipients to match each protocol-name case-insensitively, and RFC
  21080. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  21081. // client naming websocket alongside another protocol, or on a second field
  21082. // line, is offering websocket; a value that merely contains "websocket" as a
  21083. // substring is a different protocol name and is not.
  21084. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  21085. Request req;
  21086. req.method = "GET";
  21087. for (const auto &value : upgrade_values) {
  21088. req.headers.emplace("Upgrade", value);
  21089. }
  21090. req.headers.emplace("Connection", "Upgrade");
  21091. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21092. req.headers.emplace("Sec-WebSocket-Version", "13");
  21093. return req;
  21094. };
  21095. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  21096. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  21097. EXPECT_TRUE(
  21098. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  21099. EXPECT_TRUE(
  21100. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  21101. EXPECT_TRUE(
  21102. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  21103. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  21104. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  21105. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  21106. EXPECT_FALSE(
  21107. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  21108. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  21109. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21110. }
  21111. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  21112. Server svr;
  21113. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  21114. auto port = svr.bind_to_any_port("localhost");
  21115. std::thread t([&]() { svr.listen_after_bind(); });
  21116. auto se = detail::scope_exit([&] {
  21117. svr.stop();
  21118. t.join();
  21119. });
  21120. svr.wait_until_ready();
  21121. Headers headers = {{"Upgrade", "websocket"},
  21122. {"Connection", "notupgrade"},
  21123. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21124. {"Sec-WebSocket-Version", "13"}};
  21125. Client cli("localhost", port);
  21126. auto res = cli.Get("/ws", headers);
  21127. // The route exists only as a WebSocket route, so a request that fails the
  21128. // handshake check falls through to ordinary routing.
  21129. ASSERT_TRUE(res);
  21130. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  21131. }
  21132. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  21133. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  21134. // Connection value is the only thing left for the client to reject.
  21135. Server svr;
  21136. svr.Get("/ws", [](const Request &req, Response &res) {
  21137. res.status = StatusCode::SwitchingProtocol_101;
  21138. res.set_header("Upgrade", "websocket");
  21139. res.set_header("Connection", "notupgrade");
  21140. res.set_header("Sec-WebSocket-Accept",
  21141. detail::websocket_accept_key(
  21142. req.get_header_value("Sec-WebSocket-Key")));
  21143. });
  21144. auto port = svr.bind_to_any_port("localhost");
  21145. std::thread t([&]() { svr.listen_after_bind(); });
  21146. auto se = detail::scope_exit([&] {
  21147. svr.stop();
  21148. t.join();
  21149. });
  21150. svr.wait_until_ready();
  21151. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21152. auto res = client.connect();
  21153. EXPECT_FALSE(res);
  21154. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21155. EXPECT_FALSE(client.is_open());
  21156. }
  21157. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  21158. Server svr;
  21159. svr.Get("/ws", [](const Request &req, Response &res) {
  21160. res.status = StatusCode::SwitchingProtocol_101;
  21161. res.set_header("Upgrade", "websocket");
  21162. res.set_header("Connection", "Upgrade");
  21163. res.set_header("Sec-WebSocket-Accept",
  21164. detail::websocket_accept_key(
  21165. req.get_header_value("Sec-WebSocket-Key")));
  21166. res.set_header("Sec-WebSocket-Protocol", "admin");
  21167. });
  21168. auto port = svr.bind_to_any_port("localhost");
  21169. std::thread t([&]() { svr.listen_after_bind(); });
  21170. auto se = detail::scope_exit([&] {
  21171. svr.stop();
  21172. t.join();
  21173. });
  21174. svr.wait_until_ready();
  21175. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  21176. // Server selects a subprotocol the client never offered
  21177. {
  21178. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21179. ws::WebSocketClient client(url, headers);
  21180. auto res = client.connect();
  21181. EXPECT_FALSE(res);
  21182. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21183. EXPECT_FALSE(client.is_open());
  21184. EXPECT_TRUE(client.subprotocol().empty());
  21185. }
  21186. // Client offered none but the server named one anyway
  21187. {
  21188. ws::WebSocketClient client(url);
  21189. auto res = client.connect();
  21190. EXPECT_FALSE(res);
  21191. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21192. EXPECT_FALSE(client.is_open());
  21193. EXPECT_TRUE(client.subprotocol().empty());
  21194. }
  21195. }
  21196. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  21197. // The socket path doubles as the URL host, so it must not contain '/'.
  21198. const char *shard = getenv("GTEST_SHARD_INDEX");
  21199. const std::string sock_path =
  21200. shard ? std::string("httplib-ws-") + shard + ".sock"
  21201. : std::string("httplib-ws.sock");
  21202. std::remove(sock_path.c_str());
  21203. Server svr;
  21204. std::mutex mtx;
  21205. std::string received_host;
  21206. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21207. {
  21208. std::lock_guard<std::mutex> lock(mtx);
  21209. received_host = req.get_header_value("Host");
  21210. }
  21211. std::string msg;
  21212. while (ws.read(msg)) {
  21213. ws.send(msg);
  21214. }
  21215. });
  21216. svr.set_address_family(AF_UNIX);
  21217. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  21218. auto se = detail::scope_exit([&] {
  21219. svr.stop();
  21220. t.join();
  21221. std::remove(sock_path.c_str());
  21222. });
  21223. svr.wait_until_ready();
  21224. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  21225. client.set_address_family(AF_UNIX);
  21226. ASSERT_TRUE(client.connect());
  21227. ASSERT_TRUE(client.send("hello"));
  21228. std::string msg;
  21229. ASSERT_TRUE(client.read(msg));
  21230. client.close();
  21231. {
  21232. std::lock_guard<std::mutex> lock(mtx);
  21233. // There is no host:port for a Unix socket, so the same "localhost"
  21234. // placeholder the HTTP client uses is expected.
  21235. EXPECT_EQ("localhost", received_host);
  21236. }
  21237. }
  21238. // Two threads must never parse WebSocket frames from the same stream.
  21239. // close() used to read the peer's Close reply with its own frame read, so it
  21240. // raced a reader thread that was in the middle of a payload: the payload loop
  21241. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  21242. // so bytes taken by close() were replaced with bytes from further along the
  21243. // stream. The message kept its length and silently changed content.
  21244. //
  21245. // The raw peer below sends a frame header plus part of the payload, waits for
  21246. // the handler to call close(), and only then sends the rest. Whichever thread
  21247. // would win the race for those bytes, the message must arrive intact, because
  21248. // close() must not touch the stream while read() owns it.
  21249. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  21250. #ifndef _WIN32
  21251. signal(SIGPIPE, SIG_IGN);
  21252. #endif
  21253. const size_t payload_len = 120; // fits the 7-bit length field
  21254. const size_t prefix_len = 8;
  21255. const int attempts = 8;
  21256. std::string expected(payload_len, '\0');
  21257. for (size_t i = 0; i < payload_len; i++) {
  21258. expected[i] = static_cast<char>('a' + i % 26);
  21259. }
  21260. std::atomic<bool> peer_stalled{false};
  21261. std::atomic<bool> handler_done{false};
  21262. std::mutex received_mutex;
  21263. std::vector<std::string> received;
  21264. // Bound every wait, so a regression fails the test instead of hanging the
  21265. // suite.
  21266. auto wait_for = [](const std::atomic<bool> &flag) {
  21267. for (int i = 0; i < 500 && !flag; i++) {
  21268. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21269. }
  21270. };
  21271. Server svr;
  21272. svr.set_websocket_ping_interval(0);
  21273. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  21274. std::thread reader([&]() {
  21275. std::string msg;
  21276. while (ws.read(msg)) {
  21277. std::lock_guard<std::mutex> guard(received_mutex);
  21278. received.push_back(msg);
  21279. }
  21280. });
  21281. // Wait until the peer stalls mid-payload, so the reader thread is parked
  21282. // inside read_websocket_frame() when close() runs.
  21283. wait_for(peer_stalled);
  21284. ws.close();
  21285. reader.join();
  21286. handler_done = true;
  21287. });
  21288. auto port = svr.bind_to_any_port("127.0.0.1");
  21289. std::thread t([&]() { svr.listen_after_bind(); });
  21290. auto se = detail::scope_exit([&] {
  21291. svr.stop();
  21292. t.join();
  21293. });
  21294. svr.wait_until_ready();
  21295. auto send_bytes = [](socket_t s, const std::string &data) {
  21296. #ifdef _WIN32
  21297. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  21298. #else
  21299. auto n = ::send(s, data.data(), data.size(), 0);
  21300. #endif
  21301. return n == static_cast<decltype(n)>(data.size());
  21302. };
  21303. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  21304. // Every length used here fits the 7-bit length field.
  21305. auto masked_header = [](uint8_t first_byte, size_t len) {
  21306. std::string h;
  21307. h += static_cast<char>(first_byte);
  21308. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  21309. h.append(4, '\0'); // mask key
  21310. return h;
  21311. };
  21312. for (int attempt = 0; attempt < attempts; attempt++) {
  21313. peer_stalled = false;
  21314. handler_done = false;
  21315. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  21316. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  21317. auto se_sock = detail::scope_exit([&] {
  21318. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  21319. });
  21320. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21321. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  21322. sockaddr_in addr{};
  21323. addr.sin_family = AF_INET;
  21324. addr.sin_port = htons(static_cast<uint16_t>(port));
  21325. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21326. ASSERT_EQ(
  21327. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  21328. << "attempt " << attempt;
  21329. ASSERT_TRUE(send_bytes(sock,
  21330. "GET /ws HTTP/1.1\r\n"
  21331. "Host: 127.0.0.1\r\n"
  21332. "Upgrade: websocket\r\n"
  21333. "Connection: Upgrade\r\n"
  21334. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  21335. "Sec-WebSocket-Version: 13\r\n"
  21336. "\r\n"))
  21337. << "attempt " << attempt;
  21338. std::string response;
  21339. while (response.find("\r\n\r\n") == std::string::npos) {
  21340. char buf[512];
  21341. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  21342. if (n <= 0) { break; }
  21343. response.append(buf, static_cast<size_t>(n));
  21344. }
  21345. ASSERT_NE(std::string::npos, response.find(" 101 "))
  21346. << "attempt " << attempt;
  21347. // Send the header of a Binary message but only the first prefix_len bytes
  21348. // of its payload, leaving the reader thread stalled inside the payload.
  21349. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  21350. expected.substr(0, prefix_len)))
  21351. << "attempt " << attempt;
  21352. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21353. peer_stalled = true;
  21354. // Let close() send its Close frame and park in its own read before the
  21355. // rest of the payload arrives, so both threads are waiting for it.
  21356. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21357. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  21358. close_frame += static_cast<char>(0x03); // status 1000
  21359. close_frame += static_cast<char>(0xE8);
  21360. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  21361. << "attempt " << attempt;
  21362. // Closing the peer releases the reader thread even on the buggy path,
  21363. // where it waits for bytes another thread already consumed.
  21364. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21365. detail::close_socket(sock);
  21366. sock = INVALID_SOCKET;
  21367. wait_for(handler_done);
  21368. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  21369. }
  21370. std::lock_guard<std::mutex> guard(received_mutex);
  21371. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  21372. << "a message in flight when close() ran was dropped";
  21373. for (size_t i = 0; i < received.size(); i++) {
  21374. EXPECT_EQ(expected, received[i]) << "message " << i;
  21375. }
  21376. }
  21377. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21378. class WebSocketSSLIntegrationTest : public ::testing::Test {
  21379. protected:
  21380. void SetUp() override {
  21381. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  21382. SERVER_PRIVATE_KEY_FILE);
  21383. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21384. std::string msg;
  21385. ws::ReadResult ret;
  21386. while ((ret = ws.read(msg))) {
  21387. if (ret == ws::Binary) {
  21388. ws.send(msg.data(), msg.size());
  21389. } else {
  21390. ws.send(msg);
  21391. }
  21392. }
  21393. });
  21394. port_ = server_->bind_to_any_port(HOST);
  21395. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21396. server_->wait_until_ready();
  21397. }
  21398. void TearDown() override {
  21399. server_->stop();
  21400. if (server_thread_.joinable()) { server_thread_.join(); }
  21401. }
  21402. std::unique_ptr<SSLServer> server_;
  21403. std::thread server_thread_;
  21404. int port_ = 0;
  21405. };
  21406. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  21407. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21408. "/ws-echo");
  21409. client.enable_server_certificate_verification(false);
  21410. ASSERT_TRUE(client.connect());
  21411. ASSERT_TRUE(client.is_open());
  21412. ASSERT_TRUE(client.send("Hello WSS"));
  21413. std::string msg;
  21414. EXPECT_EQ(ws::Text, client.read(msg));
  21415. EXPECT_EQ("Hello WSS", msg);
  21416. client.close();
  21417. }
  21418. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  21419. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  21420. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  21421. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  21422. // client (without calling close() first) is the only path that runs
  21423. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  21424. // bug exactly.
  21425. //
  21426. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  21427. // when linked against an instrumented libssl; run under Valgrind to catch it
  21428. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  21429. // suite (the freed session otherwise stalls on the close handshake) — this test
  21430. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  21431. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  21432. {
  21433. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21434. "/ws-echo");
  21435. client.enable_server_certificate_verification(false);
  21436. client.set_read_timeout(2, 0);
  21437. client.set_write_timeout(2, 0);
  21438. ASSERT_TRUE(client.connect());
  21439. ASSERT_TRUE(client.is_open());
  21440. ASSERT_TRUE(client.send("still open"));
  21441. // Intentionally do NOT call client.close(): leaving scope runs
  21442. // shutdown_and_close() with the WebSocket still open, which must send the
  21443. // close frame while the TLS session is still alive.
  21444. }
  21445. }
  21446. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  21447. // shutdown_and_close() at the start of connect(), reproducing the same
  21448. // use-after-free within the test body rather than at scope exit. The second
  21449. // connect must succeed and echo, proving the close handshake ran over a live
  21450. // session. See the note above about memory-tool requirements.
  21451. TEST_F(WebSocketSSLIntegrationTest,
  21452. ReconnectWhileOpenSendsCloseOverLiveSession) {
  21453. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21454. "/ws-echo");
  21455. client.enable_server_certificate_verification(false);
  21456. client.set_read_timeout(2, 0);
  21457. client.set_write_timeout(2, 0);
  21458. ASSERT_TRUE(client.connect());
  21459. ASSERT_TRUE(client.is_open());
  21460. ASSERT_TRUE(client.send("still open"));
  21461. // Reconnect without closing first: connect() calls shutdown_and_close() on
  21462. // the still-open connection, which must not touch a freed TLS session.
  21463. ASSERT_TRUE(client.connect());
  21464. ASSERT_TRUE(client.is_open());
  21465. ASSERT_TRUE(client.send("after reconnect"));
  21466. std::string msg;
  21467. EXPECT_EQ(ws::Text, client.read(msg));
  21468. EXPECT_EQ("after reconnect", msg);
  21469. client.close();
  21470. }
  21471. #endif
  21472. #ifdef CPPHTTPLIB_SSL_ENABLED
  21473. class WebSocketSSLCATest : public ::testing::Test {
  21474. protected:
  21475. void SetUp() override {
  21476. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  21477. SERVER_PRIVATE_KEY_FILE);
  21478. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21479. std::string msg;
  21480. while (ws.read(msg)) {
  21481. ws.send(msg);
  21482. }
  21483. });
  21484. port_ = server_->bind_to_any_port("127.0.0.1");
  21485. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21486. server_->wait_until_ready();
  21487. }
  21488. void TearDown() override {
  21489. server_->stop();
  21490. if (server_thread_.joinable()) { server_thread_.join(); }
  21491. }
  21492. std::string url() const {
  21493. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  21494. }
  21495. std::unique_ptr<SSLServer> server_;
  21496. std::thread server_thread_;
  21497. int port_ = 0;
  21498. };
  21499. // A custom CA loaded as PEM verifies the server with full certificate
  21500. // verification enabled
  21501. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  21502. ws::WebSocketClient client(url());
  21503. std::string cert;
  21504. read_file(SERVER_CERT2_FILE, cert);
  21505. client.load_ca_cert_store(cert.c_str(), cert.size());
  21506. ASSERT_TRUE(client.connect());
  21507. ASSERT_TRUE(client.send("hello"));
  21508. std::string msg;
  21509. EXPECT_EQ(ws::Text, client.read(msg));
  21510. EXPECT_EQ("hello", msg);
  21511. client.close();
  21512. }
  21513. // A custom CA that does not cover the server must fail verification (the
  21514. // custom CA is exclusive; system certs are not loaded alongside it)
  21515. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  21516. ws::WebSocketClient client(url());
  21517. std::string cert;
  21518. read_file(CLIENT_CA_CERT_FILE, cert);
  21519. client.load_ca_cert_store(cert.c_str(), cert.size());
  21520. auto res = client.connect();
  21521. ASSERT_FALSE(res);
  21522. EXPECT_EQ(Error::SSLServerVerification, res.error());
  21523. EXPECT_EQ(-1, res.status());
  21524. EXPECT_NE(0u, res.ssl_backend_error());
  21525. }
  21526. // The same CA as a file path rather than PEM in memory
  21527. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  21528. ws::WebSocketClient client(url());
  21529. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21530. ASSERT_TRUE(client.connect());
  21531. ASSERT_TRUE(client.send("hello"));
  21532. std::string msg;
  21533. EXPECT_EQ(ws::Text, client.read(msg));
  21534. EXPECT_EQ("hello", msg);
  21535. client.close();
  21536. }
  21537. // ...and a CA file that does not cover the server still fails, so it is the
  21538. // path above that decides the outcome
  21539. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  21540. ws::WebSocketClient client(url());
  21541. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21542. ASSERT_FALSE(client.connect());
  21543. }
  21544. // Regression test: reconnecting with a native custom CA store used to reuse
  21545. // a store handle the previous TLS context had already freed (use-after-free
  21546. // under the OpenSSL backend). The context now lives as long as the client.
  21547. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  21548. ws::WebSocketClient client(url());
  21549. std::string cert;
  21550. read_file(SERVER_CERT2_FILE, cert);
  21551. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  21552. ASSERT_TRUE(client.connect());
  21553. client.close();
  21554. ASSERT_TRUE(client.connect());
  21555. ASSERT_TRUE(client.send("again"));
  21556. std::string msg;
  21557. EXPECT_EQ(ws::Text, client.read(msg));
  21558. EXPECT_EQ("again", msg);
  21559. client.close();
  21560. }
  21561. // Regression test: a certificate with a trusted chain but no identity match
  21562. // for the server IP must be rejected. The Mbed TLS backend used to skip
  21563. // verification entirely for IP hosts, so this connection succeeded there.
  21564. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  21565. // chain verification while the identity check must still fail.
  21566. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  21567. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21568. ASSERT_TRUE(svr.is_valid());
  21569. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21570. std::string msg;
  21571. while (ws.read(msg)) {
  21572. ws.send(msg);
  21573. }
  21574. });
  21575. auto port = svr.bind_to_any_port("127.0.0.1");
  21576. auto t = std::thread([&]() { svr.listen_after_bind(); });
  21577. auto se = detail::scope_exit([&] {
  21578. svr.stop();
  21579. t.join();
  21580. });
  21581. svr.wait_until_ready();
  21582. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  21583. "/echo");
  21584. std::string cert;
  21585. read_file(SERVER_CERT_FILE, cert);
  21586. client.load_ca_cert_store(cert.c_str(), cert.size());
  21587. ASSERT_FALSE(client.connect());
  21588. }
  21589. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  21590. // SNI, so nothing binds the host name to the TLS session. These bind the
  21591. // server to "localhost" instead, the only shape that exercises the SNI and
  21592. // hostname-verification path with certificate verification left enabled.
  21593. class WebSocketSSLDnsHostTest : public ::testing::Test {
  21594. protected:
  21595. void Start(const char *cert_file) {
  21596. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  21597. SERVER_PRIVATE_KEY_FILE);
  21598. ASSERT_TRUE(server_->is_valid());
  21599. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21600. std::string msg;
  21601. while (ws.read(msg)) {
  21602. ws.send(msg);
  21603. }
  21604. });
  21605. port_ = server_->bind_to_any_port("localhost");
  21606. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21607. server_->wait_until_ready();
  21608. }
  21609. void TearDown() override {
  21610. if (server_) { server_->stop(); }
  21611. if (server_thread_.joinable()) { server_thread_.join(); }
  21612. }
  21613. std::string url() const {
  21614. return "wss://localhost:" + std::to_string(port_) + "/echo";
  21615. }
  21616. std::unique_ptr<SSLServer> server_;
  21617. std::thread server_thread_;
  21618. int port_ = 0;
  21619. };
  21620. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  21621. // out and the connection is usable
  21622. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  21623. Start(SERVER_CERT2_FILE);
  21624. ws::WebSocketClient client(url());
  21625. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21626. ASSERT_TRUE(client.connect());
  21627. ASSERT_TRUE(client.send("hello"));
  21628. std::string msg;
  21629. EXPECT_EQ(ws::Text, client.read(msg));
  21630. EXPECT_EQ("hello", msg);
  21631. client.close();
  21632. }
  21633. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  21634. // while the identity check must still reject "localhost"
  21635. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  21636. Start(SERVER_CERT_FILE);
  21637. ws::WebSocketClient client(url());
  21638. client.set_ca_cert_path(SERVER_CERT_FILE);
  21639. auto res = client.connect();
  21640. ASSERT_FALSE(res);
  21641. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  21642. EXPECT_EQ(-1, res.status());
  21643. }
  21644. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  21645. // disabled: the chain is still checked, only the identity check is skipped
  21646. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  21647. Start(SERVER_CERT_FILE);
  21648. ws::WebSocketClient client(url());
  21649. client.set_ca_cert_path(SERVER_CERT_FILE);
  21650. client.enable_server_hostname_verification(false);
  21651. ASSERT_TRUE(client.connect());
  21652. ASSERT_TRUE(client.send("hello"));
  21653. std::string msg;
  21654. EXPECT_EQ(ws::Text, client.read(msg));
  21655. EXPECT_EQ("hello", msg);
  21656. client.close();
  21657. }
  21658. // A CA that did not sign the server certificate fails the chain, even though
  21659. // the name would match
  21660. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  21661. Start(SERVER_CERT2_FILE);
  21662. ws::WebSocketClient client(url());
  21663. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21664. ASSERT_FALSE(client.connect());
  21665. }
  21666. // With verification disabled, neither the chain nor the name is checked
  21667. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  21668. Start(SERVER_CERT_FILE);
  21669. ws::WebSocketClient client(url());
  21670. client.enable_server_certificate_verification(false);
  21671. ASSERT_TRUE(client.connect());
  21672. ASSERT_TRUE(client.send("hello"));
  21673. std::string msg;
  21674. EXPECT_EQ(ws::Text, client.read(msg));
  21675. EXPECT_EQ("hello", msg);
  21676. client.close();
  21677. }
  21678. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  21679. protected:
  21680. void SetUp() override {
  21681. server_ = httplib::detail::make_unique<SSLServer>(
  21682. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21683. ASSERT_TRUE(server_->is_valid());
  21684. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21685. std::string msg;
  21686. while (ws.read(msg)) {
  21687. ws.send(msg);
  21688. }
  21689. });
  21690. port_ = server_->bind_to_any_port("localhost");
  21691. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21692. server_->wait_until_ready();
  21693. }
  21694. void TearDown() override {
  21695. server_->stop();
  21696. if (server_thread_.joinable()) { server_thread_.join(); }
  21697. }
  21698. std::string url() const {
  21699. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  21700. }
  21701. void ConnectWithClientCert(const std::string &client_cert_file,
  21702. const std::string &client_private_key_file,
  21703. const char *private_key_password) {
  21704. std::string cert_pem, key_pem;
  21705. read_file(client_cert_file, cert_pem);
  21706. read_file(client_private_key_file, key_pem);
  21707. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  21708. key_pem.c_str(), key_pem.size(),
  21709. private_key_password};
  21710. ws::WebSocketClient client(url(), pem);
  21711. ASSERT_TRUE(client.is_valid());
  21712. client.enable_server_certificate_verification(false);
  21713. ASSERT_TRUE(client.connect());
  21714. ASSERT_TRUE(client.send("hello"));
  21715. std::string msg;
  21716. EXPECT_EQ(ws::Text, client.read(msg));
  21717. EXPECT_EQ("hello", msg);
  21718. client.close();
  21719. }
  21720. std::unique_ptr<SSLServer> server_;
  21721. std::thread server_thread_;
  21722. int port_ = 0;
  21723. };
  21724. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  21725. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  21726. }
  21727. // Control for the tests above: the fixture's server really does require a
  21728. // client certificate, so it is the PEM the constructor installed that decides
  21729. // the outcome.
  21730. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  21731. ws::WebSocketClient client(url());
  21732. ASSERT_TRUE(client.is_valid());
  21733. client.enable_server_certificate_verification(false);
  21734. EXPECT_FALSE(client.connect());
  21735. }
  21736. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  21737. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  21738. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  21739. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  21740. }
  21741. #endif
  21742. #if !defined(_WIN32)
  21743. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  21744. auto secret_dir = std::string("./symlink_test_secret");
  21745. auto served_dir = std::string("./symlink_test_served");
  21746. auto secret_file = secret_dir + "/secret.txt";
  21747. auto symlink_path = served_dir + "/escape";
  21748. // Setup: create directories and files
  21749. mkdir(secret_dir.c_str(), 0755);
  21750. mkdir(served_dir.c_str(), 0755);
  21751. {
  21752. std::ofstream ofs(secret_file);
  21753. ofs << "SECRET_DATA";
  21754. }
  21755. // Create symlink using absolute path so it resolves correctly
  21756. #ifdef PATH_MAX
  21757. char abs_secret[PATH_MAX];
  21758. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  21759. #else
  21760. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  21761. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  21762. ASSERT_NE(nullptr, abs_secret);
  21763. #endif
  21764. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  21765. auto se = detail::scope_exit([&] {
  21766. unlink(symlink_path.c_str());
  21767. unlink(secret_file.c_str());
  21768. rmdir(served_dir.c_str());
  21769. rmdir(secret_dir.c_str());
  21770. });
  21771. Server svr;
  21772. svr.set_mount_point("/", served_dir);
  21773. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  21774. auto se2 = detail::scope_exit([&] {
  21775. svr.stop();
  21776. listen_thread.join();
  21777. });
  21778. svr.wait_until_ready();
  21779. Client cli("localhost", PORT);
  21780. // Symlink pointing outside base dir should be blocked
  21781. auto res = cli.Get("/escape/secret.txt");
  21782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21783. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  21784. }
  21785. #endif
  21786. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  21787. // "GET /smuggled" request), reads the first response, and only then sends the
  21788. // embedded request as the body. Returns how many times /smuggled ran.
  21789. //
  21790. // The body is sent AFTER receiving the first response (as in the original
  21791. // PoC) so that the stream_line_reader cannot buffer it together with the
  21792. // headers of the first request.
  21793. static int count_smuggled_requests(const std::string &outer_head,
  21794. std::string &first_response) {
  21795. Server svr;
  21796. svr.set_mount_point("/", "./www");
  21797. std::atomic<int> smuggled_count(0);
  21798. svr.Get("/smuggled", [&](const Request &, Response &res) {
  21799. smuggled_count++;
  21800. res.set_content("oops", "text/plain");
  21801. });
  21802. svr.Post("/post", [&](const Request &req, Response &res) {
  21803. res.set_content(req.body, "text/plain");
  21804. });
  21805. auto port = svr.bind_to_any_port("localhost");
  21806. thread t = thread([&] { svr.listen_after_bind(); });
  21807. auto se = detail::scope_exit([&] {
  21808. svr.stop();
  21809. t.join();
  21810. });
  21811. svr.wait_until_ready();
  21812. auto error = Error::Success;
  21813. auto sock = detail::create_client_socket(
  21814. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  21815. /*connection_timeout_sec=*/2, 0,
  21816. /*read_timeout_sec=*/2, 0,
  21817. /*write_timeout_sec=*/2, 0, std::string(), error);
  21818. EXPECT_NE(INVALID_SOCKET, sock);
  21819. if (sock == INVALID_SOCKET) { return -1; }
  21820. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21821. // The "smuggled" request will be sent as the body of the outer request
  21822. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  21823. "Host: localhost\r\n"
  21824. "Connection: close\r\n"
  21825. "\r\n";
  21826. auto head = outer_head;
  21827. auto len = std::to_string(smuggled.size());
  21828. for (auto pos = head.find("{len}"); pos != std::string::npos;
  21829. pos = head.find("{len}", pos + len.size())) {
  21830. head.replace(pos, 5, len);
  21831. }
  21832. // Step 1: Send only the outer request headers (no body yet)
  21833. auto sent = send(sock, head.data(), head.size(), 0);
  21834. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  21835. // Step 2: Read the first response
  21836. char buf[4096];
  21837. for (;;) {
  21838. auto n = recv(sock, buf, sizeof(buf), 0);
  21839. if (n <= 0) break;
  21840. first_response.append(buf, static_cast<size_t>(n));
  21841. // Stop once we have a complete response (headers + body)
  21842. auto hdr_end = first_response.find("\r\n\r\n");
  21843. if (hdr_end != std::string::npos) {
  21844. // Check for Content-Length to know when the body is complete
  21845. auto cl_pos = first_response.find("Content-Length:");
  21846. if (cl_pos != std::string::npos) {
  21847. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  21848. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  21849. auto cl = std::stoul(
  21850. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  21851. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  21852. } else {
  21853. break; // No Content-Length, assume headers-only response
  21854. }
  21855. }
  21856. }
  21857. // Step 3: Now send the body, which looks like a new HTTP request. On a
  21858. // vulnerable server the keep-alive loop reads this as a second request. The
  21859. // server may already have closed the connection, so the result is ignored.
  21860. send(sock, smuggled.data(), smuggled.size(), 0);
  21861. // Half-close so that a server which drained the body sees EOF and closes,
  21862. // instead of the read below waiting for the read timeout.
  21863. #ifdef _WIN32
  21864. ::shutdown(sock, SD_SEND);
  21865. #else
  21866. ::shutdown(sock, SHUT_WR);
  21867. #endif
  21868. // Step 4: Read until the server closes the connection
  21869. for (;;) {
  21870. auto n = recv(sock, buf, sizeof(buf), 0);
  21871. if (n <= 0) break;
  21872. }
  21873. return smuggled_count.load();
  21874. }
  21875. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  21876. // A GET request with Content-Length to a static file handler must have its
  21877. // body drained before the keep-alive connection is reused. Otherwise the
  21878. // unread body bytes are interpreted as the next HTTP request.
  21879. std::string first_response;
  21880. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  21881. "Host: localhost\r\n"
  21882. "Content-Length: {len}\r\n"
  21883. "\r\n",
  21884. first_response));
  21885. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  21886. }
  21887. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  21888. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  21889. // be answered with 400 and the connection closed. Treating it as "no body"
  21890. // leaves the body to be parsed as the next request.
  21891. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  21892. const char *targets[] = {
  21893. "GET /file", // handler that never reads the body
  21894. "GET /not-found", // no handler matches (404)
  21895. "POST /post", // handler that reads the body
  21896. };
  21897. for (auto target : targets) {
  21898. for (auto value : values) {
  21899. std::string first_response;
  21900. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  21901. " HTTP/1.1\r\n"
  21902. "Host: localhost\r\n"
  21903. "Content-Length: " +
  21904. value + "\r\n\r\n",
  21905. first_response))
  21906. << target << " with Content-Length: " << value;
  21907. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  21908. << target << " with Content-Length: " << value;
  21909. }
  21910. }
  21911. }
  21912. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  21913. // A 400 for an unparseable request line leaves the rest of the message
  21914. // unread, so the connection must be closed rather than reused.
  21915. std::string first_response;
  21916. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  21917. "Host: localhost\r\n"
  21918. "Content-Length: {len}\r\n"
  21919. "\r\n",
  21920. first_response));
  21921. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  21922. }
  21923. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  21924. // Same as above for a header block that fails to parse.
  21925. std::string first_response;
  21926. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  21927. "Host: localhost\r\n"
  21928. "Bad Header\r\n"
  21929. "Content-Length: {len}\r\n"
  21930. "\r\n",
  21931. first_response));
  21932. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  21933. }
  21934. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  21935. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  21936. // server must not read another request on that connection, even when the
  21937. // request had no body to drain.
  21938. std::string first_response;
  21939. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  21940. "Host: localhost\r\n"
  21941. "\r\n",
  21942. first_response));
  21943. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  21944. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  21945. }
  21946. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21947. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  21948. // must be rejected with 400 Bad Request.
  21949. Server svr;
  21950. svr.Post("/test", [&](const Request &, Response &res) {
  21951. res.set_content("ok", "text/plain");
  21952. });
  21953. thread t = thread([&] { svr.listen(HOST, PORT); });
  21954. auto se = detail::scope_exit([&] {
  21955. svr.stop();
  21956. t.join();
  21957. ASSERT_FALSE(svr.is_running());
  21958. });
  21959. svr.wait_until_ready();
  21960. // Exact "chunked"
  21961. {
  21962. auto req = "POST /test HTTP/1.1\r\n"
  21963. "Host: localhost\r\n"
  21964. "Content-Length: 5\r\n"
  21965. "Transfer-Encoding: chunked\r\n"
  21966. "Connection: close\r\n"
  21967. "\r\n"
  21968. "hello";
  21969. std::string response;
  21970. ASSERT_TRUE(send_request(1, req, &response));
  21971. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21972. response.substr(0, response.find("\r\n")));
  21973. }
  21974. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  21975. {
  21976. auto req = "POST /test HTTP/1.1\r\n"
  21977. "Host: localhost\r\n"
  21978. "Content-Length: 5\r\n"
  21979. "Transfer-Encoding: gzip, chunked\r\n"
  21980. "Connection: close\r\n"
  21981. "\r\n"
  21982. "hello";
  21983. std::string response;
  21984. ASSERT_TRUE(send_request(1, req, &response));
  21985. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21986. response.substr(0, response.find("\r\n")));
  21987. }
  21988. }
  21989. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  21990. Server svr;
  21991. svr.Post("/test", [&](const Request &, Response &res) {
  21992. res.set_content("ok", "text/plain");
  21993. });
  21994. thread t = thread([&] { svr.listen(HOST, PORT); });
  21995. auto se = detail::scope_exit([&] {
  21996. svr.stop();
  21997. t.join();
  21998. ASSERT_FALSE(svr.is_running());
  21999. });
  22000. svr.wait_until_ready();
  22001. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  22002. // length cannot be determined, so the server must answer 400 and close
  22003. // rather than treat the request as bodyless and leave the body in the
  22004. // socket for the next request to pick up.
  22005. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  22006. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  22007. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  22008. std::string response;
  22009. ASSERT_TRUE(send_request(1, req, &response));
  22010. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22011. response.substr(0, response.find("\r\n")))
  22012. << transfer_encoding;
  22013. }
  22014. // RFC 9110 5.3: the codings may also be split across several
  22015. // Transfer-Encoding lines, which combine in the order they were received.
  22016. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  22017. // just like the single-line "chunked, gzip" above.
  22018. {
  22019. auto req = "POST /test HTTP/1.1\r\n"
  22020. "Host: localhost\r\n"
  22021. "Transfer-Encoding: chunked\r\n"
  22022. "Transfer-Encoding: gzip\r\n"
  22023. "\r\n"
  22024. "0\r\n\r\n";
  22025. std::string response;
  22026. ASSERT_TRUE(send_request(1, req, &response));
  22027. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22028. response.substr(0, response.find("\r\n")));
  22029. }
  22030. // A sequence ending in chunked stays valid.
  22031. auto req = "POST /test HTTP/1.1\r\n"
  22032. "Host: localhost\r\n"
  22033. "Transfer-Encoding: gzip, chunked\r\n"
  22034. "Connection: close\r\n"
  22035. "\r\n"
  22036. "0\r\n\r\n";
  22037. std::string response;
  22038. ASSERT_TRUE(send_request(1, req, &response));
  22039. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  22040. // ...including when it is spread over several lines.
  22041. auto split_req = "POST /test HTTP/1.1\r\n"
  22042. "Host: localhost\r\n"
  22043. "Transfer-Encoding: gzip\r\n"
  22044. "Transfer-Encoding: chunked\r\n"
  22045. "Connection: close\r\n"
  22046. "\r\n"
  22047. "0\r\n\r\n";
  22048. std::string split_response;
  22049. ASSERT_TRUE(send_request(1, split_req, &split_response));
  22050. EXPECT_EQ("HTTP/1.1 200 OK",
  22051. split_response.substr(0, split_response.find("\r\n")));
  22052. }
  22053. // Regression for issue #2450: a DELETE without Content-Length on a
  22054. // keep-alive connection must not let the post-response drain consume the
  22055. // next request's bytes.
  22056. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  22057. Server svr;
  22058. std::atomic<int> delete_count(0);
  22059. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  22060. delete_count++;
  22061. res.status = StatusCode::NoContent_204;
  22062. });
  22063. auto port = svr.bind_to_any_port(HOST);
  22064. thread t = thread([&] { svr.listen_after_bind(); });
  22065. auto se = detail::scope_exit([&] {
  22066. svr.stop();
  22067. t.join();
  22068. });
  22069. svr.wait_until_ready();
  22070. auto error = Error::Success;
  22071. auto sock = detail::create_client_socket(
  22072. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22073. /*connection_timeout_sec=*/2, 0,
  22074. /*read_timeout_sec=*/2, 0,
  22075. /*write_timeout_sec=*/2, 0, std::string(), error);
  22076. ASSERT_NE(INVALID_SOCKET, sock);
  22077. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22078. auto send_request_and_read_response = [&](const std::string &req,
  22079. std::string &out) -> bool {
  22080. auto sent = send(sock, req.data(), req.size(), 0);
  22081. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  22082. char buf[4096];
  22083. for (;;) {
  22084. auto n = recv(sock, buf, sizeof(buf), 0);
  22085. if (n <= 0) { return !out.empty(); }
  22086. out.append(buf, static_cast<size_t>(n));
  22087. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  22088. }
  22089. };
  22090. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  22091. "Host: localhost\r\n"
  22092. "\r\n";
  22093. std::string resp1;
  22094. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  22095. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  22096. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  22097. "Host: localhost\r\n"
  22098. "Connection: close\r\n"
  22099. "\r\n";
  22100. std::string resp2;
  22101. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  22102. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  22103. EXPECT_EQ(2, delete_count.load());
  22104. }
  22105. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  22106. Server svr;
  22107. svr.Post("/ingest", [&](const Request &, Response &res,
  22108. const ContentReader &content_reader) {
  22109. auto consumed = content_reader([](const char *, size_t) { return false; });
  22110. EXPECT_FALSE(consumed);
  22111. res.status = StatusCode::Conflict_409;
  22112. res.set_header("Connection", "close");
  22113. });
  22114. auto port = svr.bind_to_any_port(HOST);
  22115. thread t = thread([&] { svr.listen_after_bind(); });
  22116. auto se = detail::scope_exit([&] {
  22117. svr.stop();
  22118. t.join();
  22119. });
  22120. svr.wait_until_ready();
  22121. auto error = Error::Success;
  22122. auto sock = detail::create_client_socket(
  22123. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22124. /*connection_timeout_sec=*/2, 0,
  22125. /*read_timeout_sec=*/1, 0,
  22126. /*write_timeout_sec=*/2, 0, std::string(), error);
  22127. ASSERT_NE(INVALID_SOCKET, sock);
  22128. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22129. std::string request = "POST /ingest HTTP/1.1\r\n"
  22130. "Host: localhost\r\n"
  22131. "Transfer-Encoding: chunked\r\n"
  22132. "\r\n"
  22133. "4\r\n"
  22134. "data\r\n";
  22135. auto sent = send(sock, request.data(), request.size(), 0);
  22136. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  22137. std::string response;
  22138. ssize_t received = 0;
  22139. do {
  22140. char buf[4096];
  22141. received = recv(sock, buf, sizeof(buf), 0);
  22142. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  22143. } while (received > 0);
  22144. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  22145. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  22146. EXPECT_EQ(0, received);
  22147. }
  22148. namespace no_proxy_test {
  22149. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  22150. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  22151. // calling listen().
  22152. class ScopedServer {
  22153. public:
  22154. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  22155. ~ScopedServer() {
  22156. svr_.stop();
  22157. if (th_.joinable()) { th_.join(); }
  22158. }
  22159. Server &svr() { return svr_; }
  22160. int port() const { return port_; }
  22161. void listen() {
  22162. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22163. svr_.wait_until_ready();
  22164. }
  22165. private:
  22166. Server svr_;
  22167. std::thread th_;
  22168. int port_ = 0;
  22169. };
  22170. class ProxyAndTargetServers {
  22171. public:
  22172. ProxyAndTargetServers() {
  22173. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  22174. proxy_hits_++;
  22175. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22176. res.set_content("via-proxy", "text/plain");
  22177. });
  22178. target_.Get(".*", [this](const Request &req, Response &res) {
  22179. target_hits_++;
  22180. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22181. res.set_content("direct", "text/plain");
  22182. });
  22183. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  22184. target_port_ = target_.bind_to_any_port("127.0.0.1");
  22185. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  22186. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  22187. proxy_mock_.wait_until_ready();
  22188. target_.wait_until_ready();
  22189. }
  22190. ~ProxyAndTargetServers() {
  22191. proxy_mock_.stop();
  22192. target_.stop();
  22193. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  22194. if (target_thread_.joinable()) { target_thread_.join(); }
  22195. }
  22196. Server &proxy_mock() { return proxy_mock_; }
  22197. Server &target() { return target_; }
  22198. int proxy_port() const { return proxy_port_; }
  22199. int target_port() const { return target_port_; }
  22200. int proxy_hits() const { return proxy_hits_.load(); }
  22201. int target_hits() const { return target_hits_.load(); }
  22202. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  22203. void reset_counters() {
  22204. proxy_hits_ = 0;
  22205. target_hits_ = 0;
  22206. last_had_proxy_authz_ = false;
  22207. }
  22208. private:
  22209. Server proxy_mock_;
  22210. Server target_;
  22211. std::thread proxy_thread_;
  22212. std::thread target_thread_;
  22213. int proxy_port_ = 0;
  22214. int target_port_ = 0;
  22215. std::atomic<int> proxy_hits_{0};
  22216. std::atomic<int> target_hits_{0};
  22217. std::atomic<bool> last_had_proxy_authz_{false};
  22218. };
  22219. inline std::unique_ptr<Client> make_client(const std::string &host,
  22220. ProxyAndTargetServers &s) {
  22221. auto cli = detail::make_unique<Client>(host, s.target_port());
  22222. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  22223. cli->set_proxy("127.0.0.1", s.proxy_port());
  22224. return cli;
  22225. }
  22226. } // namespace no_proxy_test
  22227. using no_proxy_test::make_client;
  22228. using no_proxy_test::ProxyAndTargetServers;
  22229. TEST(NoProxyTest, ExactHostnameBypasses) {
  22230. ProxyAndTargetServers s;
  22231. auto cli = make_client("example.com", s);
  22232. cli->set_no_proxy({"example.com"});
  22233. auto res = cli->Get("/");
  22234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22235. EXPECT_EQ(0, s.proxy_hits());
  22236. EXPECT_EQ(1, s.target_hits());
  22237. }
  22238. TEST(NoProxyTest, SubdomainBypasses) {
  22239. ProxyAndTargetServers s;
  22240. auto cli = make_client("foo.example.com", s);
  22241. cli->set_no_proxy({"example.com"});
  22242. auto res = cli->Get("/");
  22243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22244. EXPECT_EQ(0, s.proxy_hits());
  22245. EXPECT_EQ(1, s.target_hits());
  22246. }
  22247. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  22248. // Regression guard: "evilexample.com" must not be considered a subdomain
  22249. // of "example.com". Without the dot-boundary rule, a naive endsWith
  22250. // check would let traffic bypass the proxy and leak credentials direct
  22251. // to the attacker host.
  22252. ProxyAndTargetServers s;
  22253. auto cli = make_client("evilexample.com", s);
  22254. cli->set_no_proxy({"example.com"});
  22255. auto res = cli->Get("/");
  22256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22257. EXPECT_GE(s.proxy_hits(), 1);
  22258. EXPECT_EQ(0, s.target_hits());
  22259. }
  22260. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  22261. ProxyAndTargetServers s;
  22262. auto cli = make_client("example.com.evil.com", s);
  22263. cli->set_no_proxy({"example.com"});
  22264. auto res = cli->Get("/");
  22265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22266. EXPECT_GE(s.proxy_hits(), 1);
  22267. EXPECT_EQ(0, s.target_hits());
  22268. }
  22269. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  22270. ProxyAndTargetServers s;
  22271. auto cli = make_client("example.com", s);
  22272. cli->set_no_proxy({".example.com"});
  22273. auto res = cli->Get("/");
  22274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22275. EXPECT_EQ(0, s.proxy_hits());
  22276. EXPECT_EQ(1, s.target_hits());
  22277. }
  22278. TEST(NoProxyTest, CaseInsensitiveHostname) {
  22279. ProxyAndTargetServers s;
  22280. auto cli = make_client("Example.COM", s);
  22281. cli->set_no_proxy({"EXAMPLE.com"});
  22282. auto res = cli->Get("/");
  22283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22284. EXPECT_EQ(0, s.proxy_hits());
  22285. EXPECT_EQ(1, s.target_hits());
  22286. }
  22287. TEST(NoProxyTest, TrailingDotIsNormalized) {
  22288. ProxyAndTargetServers s;
  22289. auto cli = make_client("example.com.", s);
  22290. cli->set_no_proxy({"example.com"});
  22291. auto res = cli->Get("/");
  22292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22293. EXPECT_EQ(0, s.proxy_hits());
  22294. EXPECT_EQ(1, s.target_hits());
  22295. }
  22296. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  22297. // Trailing dots must be normalized on BOTH sides — host and entry.
  22298. // An implementation that only strips the host-side trailing dot would
  22299. // fail to match host "example.com" against entry "example.com." because
  22300. // a literal substring search would compare 11 chars against 12.
  22301. ProxyAndTargetServers s;
  22302. auto cli = make_client("example.com", s);
  22303. cli->set_no_proxy({"example.com."});
  22304. auto res = cli->Get("/");
  22305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22306. EXPECT_EQ(0, s.proxy_hits());
  22307. EXPECT_EQ(1, s.target_hits());
  22308. }
  22309. TEST(NoProxyTest, WildcardBypassesEverything) {
  22310. ProxyAndTargetServers s;
  22311. auto cli = make_client("anything.invalid.test", s);
  22312. cli->set_no_proxy({"*"});
  22313. auto res = cli->Get("/");
  22314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22315. EXPECT_EQ(0, s.proxy_hits());
  22316. EXPECT_EQ(1, s.target_hits());
  22317. }
  22318. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  22319. ProxyAndTargetServers s;
  22320. Client cli("127.0.0.1", s.target_port());
  22321. cli.set_proxy("127.0.0.1", s.proxy_port());
  22322. cli.set_no_proxy({"127.0.0.1"});
  22323. auto res = cli.Get("/");
  22324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22325. EXPECT_EQ(0, s.proxy_hits());
  22326. EXPECT_EQ(1, s.target_hits());
  22327. }
  22328. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  22329. ProxyAndTargetServers s;
  22330. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  22331. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  22332. cli.set_proxy("127.0.0.1", s.proxy_port());
  22333. cli.set_no_proxy({"::1"});
  22334. auto res = cli.Get("/");
  22335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22336. EXPECT_EQ(0, s.proxy_hits());
  22337. EXPECT_EQ(1, s.target_hits());
  22338. }
  22339. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  22340. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  22341. // must still be recognized as IPv6 for CIDR matching. Implementations
  22342. // that detect IPv6 only when the host begins with '[' would parse the
  22343. // host as a hostname and miss the match.
  22344. ProxyAndTargetServers s;
  22345. Client cli("fe80::1", s.target_port());
  22346. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22347. cli.set_proxy("127.0.0.1", s.proxy_port());
  22348. cli.set_no_proxy({"fe80::/10"});
  22349. auto res = cli.Get("/");
  22350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22351. EXPECT_EQ(0, s.proxy_hits());
  22352. EXPECT_EQ(1, s.target_hits());
  22353. }
  22354. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  22355. ProxyAndTargetServers s;
  22356. Client cli("::1", s.target_port());
  22357. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  22358. cli.set_proxy("127.0.0.1", s.proxy_port());
  22359. cli.set_no_proxy({"[::1]"});
  22360. auto res = cli.Get("/");
  22361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22362. EXPECT_EQ(0, s.proxy_hits());
  22363. EXPECT_EQ(1, s.target_hits());
  22364. }
  22365. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  22366. ProxyAndTargetServers s;
  22367. Client cli("fe80::1", s.target_port());
  22368. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22369. cli.set_proxy("127.0.0.1", s.proxy_port());
  22370. cli.set_no_proxy({"[fe80::]/10"});
  22371. auto res = cli.Get("/");
  22372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22373. EXPECT_EQ(0, s.proxy_hits());
  22374. EXPECT_EQ(1, s.target_hits());
  22375. }
  22376. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  22377. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  22378. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  22379. // tricks via address-family conversion.
  22380. ProxyAndTargetServers s;
  22381. Client cli("::ffff:127.0.0.1", s.target_port());
  22382. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  22383. cli.set_proxy("127.0.0.1", s.proxy_port());
  22384. cli.set_no_proxy({"127.0.0.1"});
  22385. auto res = cli.Get("/");
  22386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22387. EXPECT_GE(s.proxy_hits(), 1);
  22388. EXPECT_EQ(0, s.target_hits());
  22389. }
  22390. TEST(NoProxyTest, IPv4CidrMatch) {
  22391. ProxyAndTargetServers s;
  22392. Client cli("127.0.0.1", s.target_port());
  22393. cli.set_proxy("127.0.0.1", s.proxy_port());
  22394. cli.set_no_proxy({"127.0.0.0/8"});
  22395. auto res = cli.Get("/");
  22396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22397. EXPECT_EQ(0, s.proxy_hits());
  22398. EXPECT_EQ(1, s.target_hits());
  22399. }
  22400. TEST(NoProxyTest, IPv4CidrNonMatch) {
  22401. ProxyAndTargetServers s;
  22402. Client cli("127.0.0.1", s.target_port());
  22403. cli.set_proxy("127.0.0.1", s.proxy_port());
  22404. cli.set_no_proxy({"10.0.0.0/8"});
  22405. auto res = cli.Get("/");
  22406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22407. EXPECT_GE(s.proxy_hits(), 1);
  22408. EXPECT_EQ(0, s.target_hits());
  22409. }
  22410. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  22411. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  22412. // IPv4 target matches.
  22413. ProxyAndTargetServers s;
  22414. Client cli("127.0.0.1", s.target_port());
  22415. cli.set_proxy("127.0.0.1", s.proxy_port());
  22416. cli.set_no_proxy({"0.0.0.0/0"});
  22417. auto res = cli.Get("/");
  22418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22419. EXPECT_EQ(0, s.proxy_hits());
  22420. EXPECT_EQ(1, s.target_hits());
  22421. }
  22422. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  22423. ProxyAndTargetServers s;
  22424. Client cli("127.0.0.1", s.target_port());
  22425. cli.set_proxy("127.0.0.1", s.proxy_port());
  22426. cli.set_no_proxy({"127.0.0.1"});
  22427. auto res = cli.Get("/");
  22428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22429. EXPECT_EQ(0, s.proxy_hits());
  22430. EXPECT_EQ(1, s.target_hits());
  22431. }
  22432. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  22433. ProxyAndTargetServers s;
  22434. Client cli("127.0.0.1", s.target_port());
  22435. cli.set_proxy("127.0.0.1", s.proxy_port());
  22436. cli.set_no_proxy({"127.0.0.0/33"});
  22437. auto res = cli.Get("/");
  22438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22439. EXPECT_GE(s.proxy_hits(), 1);
  22440. EXPECT_EQ(0, s.target_hits());
  22441. }
  22442. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  22443. // Empty prefix after the slash must be rejected, not silently treated as /32.
  22444. ProxyAndTargetServers s;
  22445. Client cli("127.0.0.1", s.target_port());
  22446. cli.set_proxy("127.0.0.1", s.proxy_port());
  22447. cli.set_no_proxy({"127.0.0.1/"});
  22448. auto res = cli.Get("/");
  22449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22450. EXPECT_GE(s.proxy_hits(), 1);
  22451. EXPECT_EQ(0, s.target_hits());
  22452. }
  22453. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  22454. ProxyAndTargetServers s;
  22455. auto cli = make_client("internal.corp", s);
  22456. cli->set_proxy_basic_auth("u", "p");
  22457. cli->set_no_proxy({"internal.corp"});
  22458. auto res = cli->Get("/");
  22459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22460. EXPECT_EQ(1, s.target_hits());
  22461. EXPECT_EQ(0, s.proxy_hits());
  22462. EXPECT_FALSE(s.last_had_proxy_authz())
  22463. << "Proxy-Authorization must not be sent direct to the target";
  22464. }
  22465. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  22466. ProxyAndTargetServers s;
  22467. auto cli = make_client("public.example", s);
  22468. cli->set_proxy_basic_auth("u", "p");
  22469. cli->set_no_proxy({"internal.corp"}); // does not match
  22470. auto res = cli->Get("/");
  22471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22472. EXPECT_GE(s.proxy_hits(), 1);
  22473. EXPECT_TRUE(s.last_had_proxy_authz());
  22474. }
  22475. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  22476. ProxyAndTargetServers s;
  22477. auto cli = make_client("anything.test", s);
  22478. auto res = cli->Get("/");
  22479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22480. EXPECT_GE(s.proxy_hits(), 1);
  22481. EXPECT_EQ(0, s.target_hits());
  22482. }
  22483. TEST(NoProxyTest, PortSpecificEntryRejected) {
  22484. ProxyAndTargetServers s;
  22485. auto cli = make_client("example.com", s);
  22486. cli->set_no_proxy({"example.com:8080"});
  22487. auto res = cli->Get("/");
  22488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22489. EXPECT_GE(s.proxy_hits(), 1);
  22490. EXPECT_EQ(0, s.target_hits());
  22491. }
  22492. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  22493. ProxyAndTargetServers s;
  22494. auto cli = make_client("anything.test", s);
  22495. cli->set_no_proxy({"", " ", "\t"});
  22496. auto res = cli->Get("/");
  22497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22498. EXPECT_GE(s.proxy_hits(), 1);
  22499. EXPECT_EQ(0, s.target_hits());
  22500. }
  22501. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  22502. // An entry with leading/trailing whitespace must still match — env-style
  22503. // values are commonly pasted with stray spaces and an implementation
  22504. // that feeds the raw token directly to inet_pton would fail to match
  22505. // valid CIDRs because of the spaces.
  22506. ProxyAndTargetServers s;
  22507. Client cli("127.0.0.1", s.target_port());
  22508. cli.set_proxy("127.0.0.1", s.proxy_port());
  22509. cli.set_no_proxy({" 127.0.0.0/8 "});
  22510. auto res = cli.Get("/");
  22511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22512. EXPECT_EQ(0, s.proxy_hits());
  22513. EXPECT_EQ(1, s.target_hits());
  22514. }
  22515. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  22516. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  22517. // go direct and must NOT carry Proxy-Authorization.
  22518. std::atomic<int> proxy_hits{0};
  22519. std::atomic<int> target_hits{0};
  22520. std::atomic<bool> target_saw_authz{false};
  22521. no_proxy_test::ScopedServer proxy_mock, target;
  22522. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  22523. proxy_hits++;
  22524. res.status = 302;
  22525. res.set_header("Location", "http://127.0.0.1:" +
  22526. std::to_string(target.port()) + "/landed");
  22527. });
  22528. target.svr().Get(".*", [&](const Request &req, Response &res) {
  22529. target_hits++;
  22530. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  22531. res.set_content("direct", "text/plain");
  22532. });
  22533. proxy_mock.listen();
  22534. target.listen();
  22535. Client cli("public.example", target.port());
  22536. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22537. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22538. cli.set_proxy_basic_auth("u", "p");
  22539. cli.set_no_proxy({"127.0.0.1"});
  22540. cli.set_follow_location(true);
  22541. auto res = cli.Get("/redir");
  22542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22543. EXPECT_GE(proxy_hits.load(), 1);
  22544. EXPECT_GE(target_hits.load(), 1);
  22545. EXPECT_FALSE(target_saw_authz.load());
  22546. }
  22547. #ifdef CPPHTTPLIB_SSL_ENABLED
  22548. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  22549. // Direct origin replying 407 must not trigger the digest retry; otherwise
  22550. // proxy creds would be sent to the (possibly hostile) origin.
  22551. std::atomic<int> target_hits{0};
  22552. std::atomic<bool> target_saw_proxy_authz{false};
  22553. no_proxy_test::ScopedServer target;
  22554. target.svr().Get(".*", [&](const Request &req, Response &res) {
  22555. target_hits++;
  22556. if (req.has_header("Proxy-Authorization")) {
  22557. target_saw_proxy_authz = true;
  22558. }
  22559. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22560. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  22561. "nonce=\"abc\", algorithm=MD5");
  22562. });
  22563. target.listen();
  22564. // The proxy address is set to the target's port: the bypass MUST kick in;
  22565. // if it doesn't, the test still routes "via proxy" to the same server and
  22566. // the Proxy-Authorization assertion below catches the leak.
  22567. Client cli("evil.example", target.port());
  22568. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  22569. cli.set_proxy("127.0.0.1", target.port());
  22570. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22571. cli.set_no_proxy({"evil.example"});
  22572. auto res = cli.Get("/x");
  22573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22574. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22575. EXPECT_EQ(1, target_hits.load());
  22576. EXPECT_FALSE(target_saw_proxy_authz.load());
  22577. }
  22578. #endif
  22579. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  22580. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  22581. std::atomic<int> proxy_hits{0};
  22582. std::atomic<int> bypass_hits{0};
  22583. std::atomic<bool> proxy_saw_c_url{false};
  22584. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  22585. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  22586. proxy_hits++;
  22587. if (req.path.find("/start") != std::string::npos) {
  22588. res.status = 302;
  22589. res.set_header("Location", "http://127.0.0.1:" +
  22590. std::to_string(bypass_server.port()) +
  22591. "/middle");
  22592. return;
  22593. }
  22594. if (req.path.find("/end") != std::string::npos) {
  22595. proxy_saw_c_url = true;
  22596. res.set_content("c-via-proxy", "text/plain");
  22597. return;
  22598. }
  22599. res.set_content("unexpected", "text/plain");
  22600. });
  22601. // public.example's "advertised" port is arbitrary (the request never lands
  22602. // there — it goes through the proxy), but use a dynamic value to stay
  22603. // friendly with sharded parallel runs.
  22604. int public_port = bypass_server.port();
  22605. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  22606. bypass_hits++;
  22607. res.status = 302;
  22608. res.set_header("Location", "http://public.example:" +
  22609. std::to_string(public_port) + "/end");
  22610. });
  22611. proxy_mock.listen();
  22612. bypass_server.listen();
  22613. Client cli("public.example", public_port);
  22614. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22615. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22616. cli.set_no_proxy({"127.0.0.1"});
  22617. cli.set_follow_location(true);
  22618. auto res = cli.Get("/start");
  22619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22620. EXPECT_EQ(StatusCode::OK_200, res->status);
  22621. EXPECT_EQ("c-via-proxy", res->body);
  22622. EXPECT_GE(proxy_hits.load(), 2);
  22623. EXPECT_GE(bypass_hits.load(), 1);
  22624. EXPECT_TRUE(proxy_saw_c_url.load());
  22625. }
  22626. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  22627. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  22628. // request reconnects to the correct endpoint.
  22629. std::atomic<int> proxy_hits{0};
  22630. std::atomic<int> target_hits{0};
  22631. no_proxy_test::ScopedServer proxy_mock, target;
  22632. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  22633. proxy_hits++;
  22634. res.set_content("via-proxy", "text/plain");
  22635. });
  22636. target.svr().Get(".*", [&](const Request &, Response &res) {
  22637. target_hits++;
  22638. res.set_content("direct", "text/plain");
  22639. });
  22640. proxy_mock.listen();
  22641. target.listen();
  22642. Client cli("public.example", target.port());
  22643. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22644. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22645. cli.set_keep_alive(true);
  22646. auto res1 = cli.Get("/a");
  22647. ASSERT_TRUE(res1);
  22648. EXPECT_EQ("via-proxy", res1->body);
  22649. EXPECT_EQ(1, proxy_hits.load());
  22650. EXPECT_EQ(0, target_hits.load());
  22651. cli.set_no_proxy({"public.example"});
  22652. auto res2 = cli.Get("/b");
  22653. ASSERT_TRUE(res2);
  22654. EXPECT_EQ("direct", res2->body);
  22655. EXPECT_EQ(1, proxy_hits.load());
  22656. EXPECT_EQ(1, target_hits.load());
  22657. }
  22658. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  22659. namespace proxy_tunnel_test {
  22660. // SSLServer counterpart to no_proxy_test::ScopedServer.
  22661. class ScopedSSLServer {
  22662. public:
  22663. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  22664. port_ = svr_.bind_to_any_port("127.0.0.1");
  22665. }
  22666. ~ScopedSSLServer() {
  22667. svr_.stop();
  22668. if (th_.joinable()) { th_.join(); }
  22669. }
  22670. SSLServer &svr() { return svr_; }
  22671. int port() const { return port_; }
  22672. void listen() {
  22673. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22674. svr_.wait_until_ready();
  22675. }
  22676. private:
  22677. SSLServer svr_;
  22678. std::thread th_;
  22679. int port_ = 0;
  22680. };
  22681. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  22682. class ScopedConnectProxy {
  22683. public:
  22684. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  22685. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  22686. if (listen_fd_ < 0) { return; }
  22687. int yes = 1;
  22688. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  22689. sockaddr_in a{};
  22690. a.sin_family = AF_INET;
  22691. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  22692. a.sin_port = 0;
  22693. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  22694. return;
  22695. }
  22696. socklen_t alen = sizeof(a);
  22697. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  22698. 0) {
  22699. return;
  22700. }
  22701. port_ = ntohs(a.sin_port);
  22702. if (::listen(listen_fd_, 1) != 0) { return; }
  22703. th_ = std::thread([this] { run(); });
  22704. }
  22705. ~ScopedConnectProxy() {
  22706. stop_ = true;
  22707. if (listen_fd_ >= 0) {
  22708. ::shutdown(listen_fd_, SHUT_RDWR);
  22709. ::close(listen_fd_);
  22710. }
  22711. if (th_.joinable()) { th_.join(); }
  22712. }
  22713. int port() const { return port_; }
  22714. int connect_hits() const { return connect_hits_.load(); }
  22715. // Head of the last CONNECT request, as the proxy saw it on the wire.
  22716. std::string connect_request() const {
  22717. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  22718. return connect_request_;
  22719. }
  22720. private:
  22721. void run() {
  22722. while (!stop_.load()) {
  22723. fd_set rfds;
  22724. FD_ZERO(&rfds);
  22725. FD_SET(listen_fd_, &rfds);
  22726. timeval tv{0, 100 * 1000};
  22727. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  22728. if (sel <= 0) { continue; }
  22729. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  22730. if (client_fd < 0) { continue; }
  22731. std::string req;
  22732. char buf[2048];
  22733. while (req.find("\r\n\r\n") == std::string::npos) {
  22734. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  22735. if (n <= 0) { break; }
  22736. req.append(buf, static_cast<size_t>(n));
  22737. }
  22738. if (req.compare(0, 7, "CONNECT") != 0) {
  22739. ::close(client_fd);
  22740. continue;
  22741. }
  22742. connect_hits_++;
  22743. {
  22744. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  22745. connect_request_ = req;
  22746. }
  22747. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  22748. ::send(client_fd, ok, std::strlen(ok), 0);
  22749. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  22750. sockaddr_in o{};
  22751. o.sin_family = AF_INET;
  22752. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  22753. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  22754. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  22755. 0) {
  22756. ::close(client_fd);
  22757. ::close(origin_fd);
  22758. continue;
  22759. }
  22760. auto forward = [](int from, int to) {
  22761. char b[8192];
  22762. for (;;) {
  22763. ssize_t n = ::recv(from, b, sizeof(b), 0);
  22764. if (n <= 0) { break; }
  22765. ssize_t off = 0;
  22766. while (off < n) {
  22767. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  22768. if (s <= 0) {
  22769. off = n;
  22770. break;
  22771. }
  22772. off += s;
  22773. }
  22774. }
  22775. ::shutdown(to, SHUT_WR);
  22776. };
  22777. std::thread t1([&] { forward(client_fd, origin_fd); });
  22778. std::thread t2([&] { forward(origin_fd, client_fd); });
  22779. t1.join();
  22780. t2.join();
  22781. ::close(client_fd);
  22782. ::close(origin_fd);
  22783. }
  22784. }
  22785. int forward_port_ = -1;
  22786. int listen_fd_ = -1;
  22787. int port_ = 0;
  22788. std::thread th_;
  22789. std::atomic<bool> stop_{false};
  22790. std::atomic<int> connect_hits_{0};
  22791. mutable std::mutex connect_request_mutex_;
  22792. std::string connect_request_;
  22793. };
  22794. // Sends one request through the CONNECT proxy to the TLS origin with a
  22795. // credential configured for each hop, and checks that each credential reaches
  22796. // only the hop it was configured for: the proxy's on the CONNECT request, the
  22797. // origin's (every header in origin_headers) on the tunnelled request.
  22798. void CredentialsStayWithTheirHop(
  22799. const std::function<void(SSLClient &)> &set_credentials,
  22800. const std::string &scheme,
  22801. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  22802. std::atomic<int> origin_hits{0};
  22803. std::atomic<bool> origin_saw_proxy_authz{false};
  22804. std::atomic<bool> origin_saw_headers{false};
  22805. ScopedSSLServer origin;
  22806. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22807. origin_hits++;
  22808. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  22809. origin_saw_headers =
  22810. std::all_of(origin_headers.begin(), origin_headers.end(),
  22811. [&](const std::string &h) { return req.has_header(h); });
  22812. res.set_content("ok", "text/plain");
  22813. });
  22814. origin.listen();
  22815. ScopedConnectProxy proxy(origin.port());
  22816. ASSERT_NE(0, proxy.port());
  22817. // Pinned to 127.0.0.1 for the same reason as the test below.
  22818. SSLClient cli("127.0.0.1", origin.port());
  22819. cli.enable_server_certificate_verification(false);
  22820. cli.set_proxy("127.0.0.1", proxy.port());
  22821. set_credentials(cli);
  22822. auto res = cli.Get("/x");
  22823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22824. EXPECT_EQ(StatusCode::OK_200, res->status);
  22825. EXPECT_EQ(1, origin_hits.load());
  22826. EXPECT_EQ(1, proxy.connect_hits());
  22827. EXPECT_TRUE(origin_saw_headers.load());
  22828. EXPECT_FALSE(origin_saw_proxy_authz.load())
  22829. << "Proxy-Authorization must not be sent inside the tunnel";
  22830. auto connect_req = proxy.connect_request();
  22831. EXPECT_NE(std::string::npos,
  22832. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  22833. for (const auto &h : origin_headers) {
  22834. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  22835. << h << " must not be sent to the proxy on CONNECT";
  22836. }
  22837. }
  22838. } // namespace proxy_tunnel_test
  22839. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  22840. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22841. [](SSLClient &cli) {
  22842. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22843. cli.set_basic_auth("origin-user", "origin-pass");
  22844. },
  22845. "Basic");
  22846. }
  22847. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  22848. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22849. [](SSLClient &cli) {
  22850. cli.set_proxy_bearer_token_auth("proxy-token");
  22851. cli.set_bearer_token_auth("origin-token");
  22852. },
  22853. "Bearer");
  22854. }
  22855. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  22856. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22857. [](SSLClient &cli) {
  22858. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22859. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  22860. {"Cookie", "sid=origin-session"},
  22861. {"X-Api-Key", "origin-key"}});
  22862. },
  22863. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  22864. }
  22865. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  22866. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  22867. // retry; otherwise proxy creds would be sent to the origin.
  22868. std::atomic<int> origin_hits{0};
  22869. std::atomic<bool> origin_saw_proxy_authz{false};
  22870. proxy_tunnel_test::ScopedSSLServer origin;
  22871. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22872. origin_hits++;
  22873. if (req.has_header("Proxy-Authorization")) {
  22874. origin_saw_proxy_authz = true;
  22875. }
  22876. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22877. res.set_header("Proxy-Authenticate",
  22878. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  22879. "algorithm=MD5");
  22880. });
  22881. origin.listen();
  22882. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  22883. ASSERT_NE(0, proxy.port());
  22884. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  22885. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  22886. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  22887. // and answer with its own status, making this test flaky.
  22888. SSLClient cli("127.0.0.1", origin.port());
  22889. cli.enable_server_certificate_verification(false);
  22890. cli.set_proxy("127.0.0.1", proxy.port());
  22891. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22892. auto res = cli.Get("/x");
  22893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22894. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22895. EXPECT_EQ(1, origin_hits.load());
  22896. EXPECT_FALSE(origin_saw_proxy_authz.load());
  22897. EXPECT_EQ(1, proxy.connect_hits());
  22898. }
  22899. #endif