test.cc 869 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  42. #define CA_CERT_FILE "./ca-bundle.crt"
  43. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  44. #define CLIENT_CA_CERT_DIR "."
  45. #define CLIENT_CERT_FILE "./client.cert.pem"
  46. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  47. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  48. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  49. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  50. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  51. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  52. #else
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  54. #endif
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  56. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  57. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  58. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  59. #ifdef CPPHTTPLIB_SSL_ENABLED
  60. namespace httplib {
  61. namespace tls {
  62. // Declared here for the split build, where the TLS abstraction declarations
  63. // live below the split border; the definition is linked from httplib.cc.
  64. ca_store_t create_ca_store(const char *pem, size_t len);
  65. } // namespace tls
  66. } // namespace httplib
  67. #endif
  68. using namespace std;
  69. using namespace httplib;
  70. const char *HOST = "localhost";
  71. static int get_base_port() {
  72. const char *shard = getenv("GTEST_SHARD_INDEX");
  73. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  74. }
  75. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  76. // New standalone tests MUST use svr.bind_to_any_port() instead.
  77. const int PORT = get_base_port();
  78. const string LONG_QUERY_VALUE = string(25000, '@');
  79. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  80. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  81. const string TOO_LONG_QUERY_URL =
  82. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  83. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  84. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  85. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  86. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  87. return file.name == key;
  88. });
  89. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  90. return *it;
  91. #else
  92. if (it != items.end()) { return *it; }
  93. throw std::runtime_error("invalid multipart form data name error");
  94. #endif
  95. }
  96. static void read_file(const std::string &path, std::string &out) {
  97. std::ifstream fs(path, std::ios_base::binary);
  98. if (!fs) {
  99. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  100. return;
  101. #else
  102. throw std::runtime_error("File not found: " + path);
  103. #endif
  104. }
  105. fs.seekg(0, std::ios_base::end);
  106. auto size = fs.tellg();
  107. fs.seekg(0);
  108. out.resize(static_cast<size_t>(size));
  109. fs.read(&out[0], static_cast<std::streamsize>(size));
  110. }
  111. class UnixSocketTest : public ::testing::Test {
  112. protected:
  113. void TearDown() override { std::remove(pathname_.c_str()); }
  114. void client_GET(const std::string &addr) {
  115. httplib::Client cli{addr};
  116. cli.set_address_family(AF_UNIX);
  117. ASSERT_TRUE(cli.is_valid());
  118. const auto &result = cli.Get(pattern_);
  119. ASSERT_TRUE(result) << "error: " << result.error();
  120. const auto &resp = result.value();
  121. EXPECT_EQ(resp.status, StatusCode::OK_200);
  122. EXPECT_EQ(resp.body, content_);
  123. }
  124. static std::string make_sock_path() {
  125. const char *shard = getenv("GTEST_SHARD_INDEX");
  126. return shard ? std::string("./httplib-server-") + shard + ".sock"
  127. : "./httplib-server.sock";
  128. }
  129. const std::string pathname_{make_sock_path()};
  130. const std::string pattern_{"/hi"};
  131. const std::string content_{"Hello World!"};
  132. };
  133. TEST_F(UnixSocketTest, pathname) {
  134. httplib::Server svr;
  135. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  136. res.set_content(content_, "text/plain");
  137. });
  138. std::thread t{[&] {
  139. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  140. }};
  141. auto se = detail::scope_exit([&] {
  142. svr.stop();
  143. t.join();
  144. ASSERT_FALSE(svr.is_running());
  145. });
  146. svr.wait_until_ready();
  147. ASSERT_TRUE(svr.is_running());
  148. client_GET(pathname_);
  149. }
  150. #if defined(__linux__) || \
  151. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  152. TEST_F(UnixSocketTest, PeerPid) {
  153. httplib::Server svr;
  154. std::string remote_port_val;
  155. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  156. res.set_content(content_, "text/plain");
  157. remote_port_val = std::to_string(req.remote_port);
  158. });
  159. std::thread t{[&] {
  160. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  161. }};
  162. auto se = detail::scope_exit([&] {
  163. svr.stop();
  164. t.join();
  165. ASSERT_FALSE(svr.is_running());
  166. });
  167. svr.wait_until_ready();
  168. ASSERT_TRUE(svr.is_running());
  169. client_GET(pathname_);
  170. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  171. }
  172. #endif
  173. #ifdef __linux__
  174. TEST_F(UnixSocketTest, abstract) {
  175. constexpr char svr_path[]{"\x00httplib-server.sock"};
  176. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  177. httplib::Server svr;
  178. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  179. res.set_content(content_, "text/plain");
  180. });
  181. std::thread t{[&] {
  182. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  183. }};
  184. auto se = detail::scope_exit([&] {
  185. svr.stop();
  186. t.join();
  187. ASSERT_FALSE(svr.is_running());
  188. });
  189. svr.wait_until_ready();
  190. ASSERT_TRUE(svr.is_running());
  191. client_GET(abstract_addr);
  192. }
  193. #endif
  194. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  195. httplib::Server svr;
  196. std::string received_host_header;
  197. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  198. // Capture the Host header sent by the client
  199. auto host_iter = req.headers.find("Host");
  200. if (host_iter != req.headers.end()) {
  201. received_host_header = host_iter->second;
  202. }
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  207. }};
  208. auto se = detail::scope_exit([&] {
  209. svr.stop();
  210. t.join();
  211. ASSERT_FALSE(svr.is_running());
  212. });
  213. svr.wait_until_ready();
  214. ASSERT_TRUE(svr.is_running());
  215. // Test that Host header is automatically set to "localhost" for Unix socket
  216. // connections
  217. httplib::Client cli{pathname_};
  218. cli.set_address_family(AF_UNIX);
  219. ASSERT_TRUE(cli.is_valid());
  220. const auto &result = cli.Get(pattern_);
  221. ASSERT_TRUE(result) << "error: " << result.error();
  222. const auto &resp = result.value();
  223. EXPECT_EQ(resp.status, StatusCode::OK_200);
  224. EXPECT_EQ(resp.body, content_);
  225. // Verify that Host header was automatically set to "localhost"
  226. EXPECT_EQ(received_host_header, "localhost");
  227. }
  228. #ifndef _WIN32
  229. TEST(SocketStream, wait_writable_UNIX) {
  230. int fds[2];
  231. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  232. const auto asSocketStream = [&](socket_t fd,
  233. std::function<bool(Stream &)> func) {
  234. return detail::process_client_socket(
  235. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  236. };
  237. asSocketStream(fds[0], [&](Stream &s0) {
  238. EXPECT_EQ(s0.socket(), fds[0]);
  239. EXPECT_TRUE(s0.wait_writable());
  240. EXPECT_TRUE(s0.is_peer_alive());
  241. EXPECT_EQ(0, close(fds[1]));
  242. EXPECT_FALSE(s0.is_peer_alive());
  243. return true;
  244. });
  245. EXPECT_EQ(0, close(fds[0]));
  246. }
  247. TEST(SocketStream, wait_writable_INET) {
  248. sockaddr_in addr;
  249. memset(&addr, 0, sizeof(addr));
  250. addr.sin_family = AF_INET;
  251. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  252. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  253. int disconnected_svr_sock = -1;
  254. std::thread svr{[&] {
  255. const int s = socket(AF_INET, SOCK_STREAM, 0);
  256. ASSERT_LE(0, s);
  257. // PORT + 1 is shared with the SSL redirect tests and with
  258. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  259. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  260. // because that happens on a worker thread the ASSERT does not stop the
  261. // test: it runs on and fails at the disconnected_svr_sock check instead.
  262. default_socket_options(s);
  263. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  264. ASSERT_EQ(0, listen(s, 1));
  265. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  266. ASSERT_EQ(0, close(s));
  267. }};
  268. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  269. std::thread cli{[&] {
  270. const int s = socket(AF_INET, SOCK_STREAM, 0);
  271. ASSERT_LE(0, s);
  272. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  273. ASSERT_EQ(0, close(s));
  274. }};
  275. cli.join();
  276. svr.join();
  277. ASSERT_NE(disconnected_svr_sock, -1);
  278. const auto asSocketStream = [&](socket_t fd,
  279. std::function<bool(Stream &)> func) {
  280. return detail::process_client_socket(
  281. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  282. };
  283. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  284. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  285. // wait_writable() returns true because select_write() only checks if the
  286. // send buffer has space. Peer disconnection is detected later by send().
  287. EXPECT_TRUE(ss.wait_writable());
  288. return true;
  289. });
  290. ASSERT_EQ(0, close(disconnected_svr_sock));
  291. }
  292. #endif // #ifndef _WIN32
  293. TEST(SetSocketOptTest, TcpNoDelay) {
  294. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  295. ASSERT_NE(sock, INVALID_SOCKET);
  296. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  297. int val = 0;
  298. socklen_t len = sizeof(val);
  299. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  300. reinterpret_cast<char *>(&val), &len));
  301. EXPECT_NE(val, 0);
  302. detail::close_socket(sock);
  303. }
  304. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  305. // accept() reports failures through WSAGetLastError() on Windows and through
  306. // errno everywhere else. Asking the wrong one is what made the accept loop
  307. // treat every recoverable failure as fatal on Windows.
  308. struct Classification {
  309. bool resource;
  310. bool transient;
  311. };
  312. auto classify = [](int err) {
  313. #ifdef _WIN32
  314. WSASetLastError(err);
  315. #else
  316. errno = err;
  317. #endif
  318. // Read both before asserting: an assertion may clobber the error slot.
  319. Classification c;
  320. c.resource = detail::is_accept_resource_error();
  321. c.transient = detail::is_accept_transient_error();
  322. return c;
  323. };
  324. #ifdef _WIN32
  325. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  326. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  327. WSAECONNRESET, WSAECONNABORTED};
  328. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  329. #else
  330. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  331. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  332. ECONNABORTED};
  333. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  334. #endif
  335. for (auto err : resource_errors) {
  336. const auto c = classify(err);
  337. EXPECT_TRUE(c.resource) << "error " << err;
  338. EXPECT_FALSE(c.transient) << "error " << err;
  339. }
  340. for (auto err : transient_errors) {
  341. const auto c = classify(err);
  342. EXPECT_TRUE(c.transient) << "error " << err;
  343. EXPECT_FALSE(c.resource) << "error " << err;
  344. }
  345. for (auto err : fatal_errors) {
  346. const auto c = classify(err);
  347. EXPECT_FALSE(c.resource) << "error " << err;
  348. EXPECT_FALSE(c.transient) << "error " << err;
  349. }
  350. #ifdef _WIN32
  351. WSASetLastError(0);
  352. #else
  353. errno = 0;
  354. #endif
  355. }
  356. TEST(ClientTest, MoveConstructible) {
  357. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  358. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  359. }
  360. TEST(ClientTest, MoveAssignable) {
  361. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  362. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  363. }
  364. #ifdef _WIN32
  365. TEST(StartupTest, WSAStartup) {
  366. WSADATA wsaData;
  367. int ret = WSAStartup(0x0002, &wsaData);
  368. ASSERT_EQ(0, ret);
  369. }
  370. #endif
  371. TEST(DecodePathTest, PercentCharacter) {
  372. EXPECT_EQ(
  373. decode_path_component(
  374. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  375. U8("descrip=Gastos áéíóúñÑ 6"));
  376. }
  377. TEST(DecodePathTest, PercentCharacterNUL) {
  378. string expected;
  379. expected.push_back('x');
  380. expected.push_back('\0');
  381. expected.push_back('x');
  382. EXPECT_EQ(decode_path_component("x%00x"), expected);
  383. }
  384. TEST(DecodePathTest, UnicodeEncoding) {
  385. // %u0041 = 'A' (1-byte UTF-8)
  386. EXPECT_EQ("A", decode_path_component("%u0041"));
  387. // %u00E9 = 'é' (2-byte UTF-8)
  388. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  389. // %u3042 = 'あ' (3-byte UTF-8)
  390. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  391. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  392. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  393. // %uD800 = surrogate (invalid, silently dropped)
  394. EXPECT_EQ("", decode_path_component("%uD800"));
  395. }
  396. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  397. // A sign or whitespace inside the two-character escape window must not be
  398. // accepted as a valid percent-encoding; the sequence is passed through
  399. // literally, matching decode_uri_component / decode_path_component.
  400. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  401. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  402. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  403. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  404. // Well-formed escapes still decode.
  405. EXPECT_EQ("-", decode_query_component("%2D", false));
  406. EXPECT_EQ("A", decode_query_component("%41", false));
  407. }
  408. TEST(SanitizeFilenameTest, VariousPatterns) {
  409. // Path traversal
  410. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  411. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  412. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  413. // Normal and edge cases
  414. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  415. EXPECT_EQ("filename.txt",
  416. httplib::sanitize_filename("/path/to/filename.txt"));
  417. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  418. EXPECT_EQ("", httplib::sanitize_filename(".."));
  419. EXPECT_EQ("", httplib::sanitize_filename(""));
  420. // Null bytes stripped
  421. EXPECT_EQ("safe.txt",
  422. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  423. // Whitespace-only rejected
  424. EXPECT_EQ("", httplib::sanitize_filename(" "));
  425. }
  426. // Forward declaration (see the base64_encode note below): split builds move the
  427. // definition into httplib.cc, so re-declaring it here lets the test link.
  428. namespace httplib {
  429. namespace detail {
  430. bool is_chunked_transfer_encoding(const Headers &headers);
  431. } // namespace detail
  432. } // namespace httplib
  433. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  434. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  435. auto make = [](std::initializer_list<const char *> lines) {
  436. Headers h;
  437. for (auto te : lines) {
  438. if (te) { h.emplace("Transfer-Encoding", te); }
  439. }
  440. return h;
  441. };
  442. // Sole coding, matched case-insensitively.
  443. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  444. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  446. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  450. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  451. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  452. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  455. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  456. // were received, into one list. Headers preserves that order, so the answer
  457. // is decided by the last coding of the last line and the order the lines
  458. // arrived in is significant.
  459. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  462. // The split can fall anywhere in the list.
  463. EXPECT_TRUE(
  464. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  465. EXPECT_FALSE(
  466. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  467. // A trailing line naming no coding leaves the list ending in nothing, so it
  468. // must not inherit the chunked from the line before it.
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  470. }
  471. // Forward declaration: in split builds split.py strips `inline` and moves the
  472. // definition into httplib.cc, so detail::base64_encode is not visible from the
  473. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  474. // in both header-only and split builds.
  475. namespace httplib {
  476. namespace detail {
  477. std::string base64_encode(const std::string &in);
  478. } // namespace detail
  479. } // namespace httplib
  480. TEST(Base64EncodeTest, KnownAnswers) {
  481. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  482. // where the accumulator's top bit is already set before the next shift.
  483. EXPECT_EQ("", detail::base64_encode(""));
  484. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  485. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  486. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  487. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  488. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  489. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  490. // High bytes keep the top bit set across several rounds.
  491. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  492. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  493. }
  494. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  495. string unescapedCharacters = "-_.!~*'()";
  496. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  497. }
  498. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  499. string reservedCharacters = ";,/?:@&=+$";
  500. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  501. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  502. }
  503. TEST(ClientQueryOrder, PreserveOrder) {
  504. // This test reproduces Issue #2259: client may reorder query parameters
  505. // when sending a GET request. The expected behavior is that the client
  506. // preserves the original query string order when the caller supplied it
  507. // as part of the path.
  508. Server svr;
  509. svr.Get("/", [&](const Request &req, Response &res) {
  510. // Echo back the raw target so the test can assert ordering
  511. res.set_content(req.target, "text/plain");
  512. });
  513. std::thread t{[&] { svr.listen(HOST, PORT); }};
  514. auto se = detail::scope_exit([&] {
  515. svr.stop();
  516. t.join();
  517. ASSERT_FALSE(svr.is_running());
  518. });
  519. svr.wait_until_ready();
  520. Client cli(HOST, PORT);
  521. ASSERT_TRUE(cli.is_valid());
  522. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  523. auto res = cli.Get(original);
  524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  525. // Expect the echoed target to exactly match the original path (order
  526. // preserved)
  527. EXPECT_EQ(res->body, original);
  528. }
  529. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  530. string chineseCharacters = U8("中国語");
  531. string russianCharacters = U8("дом");
  532. string brazilianCharacters = U8("óculos");
  533. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  534. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  535. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  536. "%D0%B4%D0%BE%D0%BC");
  537. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  538. }
  539. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  540. string unescapedCharacters = "-_.!~*'()";
  541. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  542. }
  543. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  544. string reservedCharacters = ";,/?:@&=+$";
  545. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  546. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  547. }
  548. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  549. string chineseCharacters = U8("中国語");
  550. string russianCharacters = U8("дом");
  551. string brazilianCharacters = U8("óculos");
  552. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  553. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  554. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  555. "%D0%B4%D0%BE%D0%BC");
  556. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  557. }
  558. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  559. // Issue #2082 use case: encoding path component with ampersand
  560. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  561. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  562. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  563. }
  564. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  565. string unescapedCharacters = "-_.!~*'()";
  566. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  567. }
  568. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  569. string reservedCharacters = ";,/?:@&=+$#";
  570. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  571. }
  572. TEST(EncodeUriTest, TestUTF8Characters) {
  573. string chineseCharacters = U8("中国語");
  574. string russianCharacters = U8("дом");
  575. string brazilianCharacters = U8("óculos");
  576. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  577. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  578. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  579. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  580. }
  581. TEST(EncodeUriTest, TestCompleteUri) {
  582. string uri =
  583. "https://example.com/path/to/resource?query=value&param=test#fragment";
  584. EXPECT_EQ(
  585. httplib::encode_uri(uri),
  586. "https://example.com/path/to/resource?query=value&param=test#fragment");
  587. }
  588. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  589. string uri =
  590. "https://example.com/path with spaces/file name.html?q=hello world";
  591. EXPECT_EQ(httplib::encode_uri(uri),
  592. "https://example.com/path%20with%20spaces/"
  593. "file%20name.html?q=hello%20world");
  594. }
  595. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  596. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  597. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  598. }
  599. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  600. string unescapedCharacters = "-_.!~*'()";
  601. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  602. }
  603. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  604. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  605. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  606. string encodedBrazilian = "%C3%B3culos";
  607. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  608. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  609. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  610. }
  611. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  612. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  613. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  614. "Piri Tommy Villiers - on & on");
  615. }
  616. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  617. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  618. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  619. }
  620. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  621. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  622. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  623. }
  624. TEST(DecodeUriTest, TestUTF8Characters) {
  625. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  626. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  627. string encodedBrazilian = "%C3%B3culos";
  628. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  629. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  630. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  631. }
  632. TEST(DecodeUriTest, TestCompleteUri) {
  633. string encodedUri = "https://example.com/path%20with%20spaces/"
  634. "file%20name.html?q=hello%20world";
  635. EXPECT_EQ(
  636. httplib::decode_uri(encodedUri),
  637. "https://example.com/path with spaces/file name.html?q=hello world");
  638. }
  639. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  640. string original =
  641. "https://example.com/path with spaces/file name.html?q=hello world";
  642. string encoded = httplib::encode_uri(original);
  643. string decoded = httplib::decode_uri(encoded);
  644. EXPECT_EQ(decoded, original);
  645. }
  646. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  647. // decode_uri is the inverse of encode_uri: an escaped reserved character
  648. // stays encoded so it is not promoted into a real delimiter, while
  649. // non-reserved escapes still decode (like JS decodeURI).
  650. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  651. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  652. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  653. "%3F%3A%40%26%3D%2B%24%2C%3B");
  654. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  655. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  656. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  657. "http://example.com/a%2Fb");
  658. // decode_uri_component still decodes the reserved character.
  659. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  660. }
  661. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  662. string original = "Piri Tommy Villiers - on & on";
  663. string encoded = httplib::encode_uri_component(original);
  664. string decoded = httplib::decode_uri_component(encoded);
  665. EXPECT_EQ(decoded, original);
  666. }
  667. TEST(TrimTests, TrimStringTests) {
  668. EXPECT_EQ("abc", detail::trim_copy("abc"));
  669. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  670. EXPECT_TRUE(detail::trim_copy("").empty());
  671. }
  672. TEST(AsciiTest, LocaleIndependentClassification) {
  673. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  674. // which consult the global C locale: std::isalnum(0xC5) can return true
  675. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  676. // helpers must classify every byte by the ASCII grammar alone.
  677. for (int i = 0; i < 256; i++) {
  678. auto c = static_cast<char>(i);
  679. auto is_digit = i >= '0' && i <= '9';
  680. auto is_upper = i >= 'A' && i <= 'Z';
  681. auto is_lower = i >= 'a' && i <= 'z';
  682. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  683. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  684. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  685. << "byte " << i;
  686. }
  687. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  688. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  689. // Non-ASCII bytes must be percent-encoded, never passed through as
  690. // alphanumeric.
  691. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  692. }
  693. TEST(FromCharsTest, Double) {
  694. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  695. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  696. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  697. auto parse = [](const std::string &s, double &v) {
  698. return detail::from_chars(s.data(), s.data() + s.size(), v);
  699. };
  700. double v = -1.0;
  701. // Representative quality values.
  702. EXPECT_EQ(parse("0", v).ec, std::errc{});
  703. EXPECT_DOUBLE_EQ(v, 0.0);
  704. EXPECT_EQ(parse("1", v).ec, std::errc{});
  705. EXPECT_DOUBLE_EQ(v, 1.0);
  706. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  707. EXPECT_DOUBLE_EQ(v, 0.8);
  708. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  709. EXPECT_DOUBLE_EQ(v, 0.001);
  710. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  711. EXPECT_DOUBLE_EQ(v, 1.0);
  712. // A missing integer or fractional part is tolerated.
  713. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  714. EXPECT_DOUBLE_EQ(v, 0.5);
  715. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  716. EXPECT_DOUBLE_EQ(v, 5.0);
  717. // Values outside [0, 1] still parse; the caller range-checks them.
  718. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  719. EXPECT_DOUBLE_EQ(v, 123.456);
  720. // Stops at the first byte that is not part of the number and reports where.
  721. std::string trailing = "0.9, text/html";
  722. auto r = parse(trailing, v);
  723. EXPECT_EQ(r.ec, std::errc{});
  724. EXPECT_DOUBLE_EQ(v, 0.9);
  725. EXPECT_EQ(*r.ptr, ',');
  726. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  727. // outright, and an 'e'/'E' simply ends the number.
  728. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  729. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  730. std::string exp_input = "1.5e3";
  731. r = parse(exp_input, v);
  732. EXPECT_EQ(r.ec, std::errc{});
  733. EXPECT_DOUBLE_EQ(v, 1.5);
  734. EXPECT_EQ(*r.ptr, 'e');
  735. // Invalid inputs.
  736. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  737. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  738. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  739. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  740. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  741. // Pathological but well-formed inputs must stay bounded (no overflow, no
  742. // out-of-bounds table access) and stay within [0, 1] for the caller.
  743. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  744. std::errc{});
  745. EXPECT_DOUBLE_EQ(v, 0.0);
  746. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  747. std::errc{});
  748. EXPECT_GE(v, 0.0);
  749. EXPECT_LE(v, 1.0);
  750. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  751. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  752. }
  753. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  754. // Simple case without quality values
  755. std::vector<std::string> result1;
  756. EXPECT_TRUE(detail::parse_accept_header(
  757. "text/html,application/json,text/plain", result1));
  758. EXPECT_EQ(result1.size(), 3U);
  759. EXPECT_EQ(result1[0], "text/html");
  760. EXPECT_EQ(result1[1], "application/json");
  761. EXPECT_EQ(result1[2], "text/plain");
  762. // With quality values
  763. std::vector<std::string> result2;
  764. EXPECT_TRUE(detail::parse_accept_header(
  765. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  766. EXPECT_EQ(result2.size(), 3U);
  767. EXPECT_EQ(result2[0], "application/json"); // highest q value
  768. EXPECT_EQ(result2[1], "text/html");
  769. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  770. }
  771. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  772. // Mixed with and without quality values
  773. std::vector<std::string> result;
  774. EXPECT_TRUE(detail::parse_accept_header(
  775. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  776. EXPECT_EQ(result.size(), 3U);
  777. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  778. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  779. EXPECT_EQ(result[2], "application/json"); // q=0.5
  780. }
  781. TEST(ParseAcceptHeaderTest, EdgeCases) {
  782. // Empty header
  783. std::vector<std::string> empty_result;
  784. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  785. EXPECT_TRUE(empty_result.empty());
  786. // Single type
  787. std::vector<std::string> single_result;
  788. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  789. EXPECT_EQ(single_result.size(), 1U);
  790. EXPECT_EQ(single_result[0], "application/json");
  791. // Wildcard types
  792. std::vector<std::string> wildcard_result;
  793. EXPECT_TRUE(detail::parse_accept_header(
  794. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  795. EXPECT_EQ(wildcard_result.size(), 3U);
  796. EXPECT_EQ(wildcard_result[0], "application/json");
  797. EXPECT_EQ(wildcard_result[1], "text/*");
  798. EXPECT_EQ(wildcard_result[2], "*/*");
  799. }
  800. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  801. // Common browser Accept header
  802. std::vector<std::string> browser_result;
  803. EXPECT_TRUE(
  804. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  805. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  806. browser_result));
  807. EXPECT_EQ(browser_result.size(), 6U);
  808. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  809. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  810. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  811. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  812. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  813. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  814. // API client header
  815. std::vector<std::string> api_result;
  816. EXPECT_TRUE(detail::parse_accept_header(
  817. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  818. api_result));
  819. EXPECT_EQ(api_result.size(), 3U);
  820. EXPECT_EQ(api_result[0], "application/json");
  821. EXPECT_EQ(api_result[1], "application/xml");
  822. EXPECT_EQ(api_result[2], "text/plain");
  823. }
  824. TEST(ParseAcceptHeaderTest, SpecialCases) {
  825. // Quality value with 3 decimal places
  826. std::vector<std::string> decimal_result;
  827. EXPECT_TRUE(detail::parse_accept_header(
  828. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  829. EXPECT_EQ(decimal_result.size(), 2U);
  830. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  831. EXPECT_EQ(decimal_result[1], "text/html");
  832. // Zero quality (should still be included but with lowest priority)
  833. std::vector<std::string> zero_q_result;
  834. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  835. zero_q_result));
  836. EXPECT_EQ(zero_q_result.size(), 2U);
  837. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  838. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  839. // No spaces around commas
  840. std::vector<std::string> no_space_result;
  841. EXPECT_TRUE(detail::parse_accept_header(
  842. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  843. no_space_result));
  844. EXPECT_EQ(no_space_result.size(), 3U);
  845. EXPECT_EQ(no_space_result[0], "text/html");
  846. EXPECT_EQ(no_space_result[1], "application/json");
  847. EXPECT_EQ(no_space_result[2], "text/plain");
  848. }
  849. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  850. // Quality values always use '.' as the decimal separator, so parsing must
  851. // not depend on the process locale. An embedding application may have
  852. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  853. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  854. std::string saved = cur ? cur : "C";
  855. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  856. "fr_FR.UTF-8"};
  857. bool switched = false;
  858. for (const auto loc : comma_locales) {
  859. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  860. std::localeconv()->decimal_point[0] == ',') {
  861. switched = true;
  862. break;
  863. }
  864. }
  865. if (!switched) {
  866. std::setlocale(LC_NUMERIC, saved.c_str());
  867. GTEST_SKIP() << "no comma-decimal locale available on this host";
  868. }
  869. // The higher-weighted type appears later in the list, so a correct parse
  870. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  871. // sensitive parse reads both weights as 0 and leaves the original order.
  872. std::vector<std::string> result;
  873. EXPECT_TRUE(detail::parse_accept_header(
  874. "application/json;q=0.1,text/html;q=0.9", result));
  875. ASSERT_EQ(result.size(), 2U);
  876. EXPECT_EQ(result[0], "text/html");
  877. EXPECT_EQ(result[1], "application/json");
  878. std::setlocale(LC_NUMERIC, saved.c_str());
  879. }
  880. TEST(ParseAcceptHeaderTest, InvalidCases) {
  881. std::vector<std::string> result;
  882. // Invalid quality value (> 1.0)
  883. EXPECT_FALSE(
  884. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  885. // Invalid quality value (< 0.0)
  886. EXPECT_FALSE(
  887. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  888. // Invalid quality value (not a number)
  889. EXPECT_FALSE(detail::parse_accept_header(
  890. "text/html;q=invalid,application/json", result));
  891. // A valid numeric prefix does not make the entire quality value valid.
  892. EXPECT_FALSE(detail::parse_accept_header(
  893. "text/html;q=0.5junk,application/json", result));
  894. // Empty quality value
  895. EXPECT_FALSE(
  896. detail::parse_accept_header("text/html;q=,application/json", result));
  897. // Invalid media type format (no slash and not wildcard)
  898. EXPECT_FALSE(
  899. detail::parse_accept_header("invalidtype,application/json", result));
  900. // Valid cases should still work
  901. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  902. EXPECT_EQ(result.size(), 1U);
  903. EXPECT_EQ(result[0], "*/*");
  904. EXPECT_TRUE(detail::parse_accept_header("*", result));
  905. EXPECT_EQ(result.size(), 1U);
  906. EXPECT_EQ(result[0], "*");
  907. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  908. EXPECT_EQ(result.size(), 1U);
  909. EXPECT_EQ(result[0], "text/*");
  910. }
  911. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  912. // elements, so a leading, trailing or doubled comma is a legal Accept value
  913. // and must not be answered with 400 Bad Request.
  914. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  915. struct {
  916. const char *value;
  917. std::vector<std::string> expected;
  918. } cases[] = {
  919. {",application/json", {"application/json"}},
  920. {"text/html,", {"text/html"}},
  921. {"text/html,,*/*", {"text/html", "*/*"}},
  922. // An empty element may be spelled with whitespace in it
  923. {"text/html, , application/json", {"text/html", "application/json"}},
  924. // Nothing but empty elements is an empty list, which means the same
  925. // thing as no Accept header at all
  926. {",,,", {}},
  927. // Quality values still apply across ignored empty elements
  928. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  929. };
  930. for (const auto &c : cases) {
  931. std::vector<std::string> result;
  932. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  933. << "value: " << c.value;
  934. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  935. }
  936. // An invalid entry is still rejected when empty elements surround it
  937. std::vector<std::string> result;
  938. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  939. }
  940. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  941. Server svr;
  942. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  943. EXPECT_EQ(req.accept_content_types.size(), 3U);
  944. EXPECT_EQ(req.accept_content_types[0], "application/json");
  945. EXPECT_EQ(req.accept_content_types[1], "text/html");
  946. EXPECT_EQ(req.accept_content_types[2], "*/*");
  947. res.set_content("ok", "text/plain");
  948. });
  949. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  950. EXPECT_TRUE(false);
  951. res.set_content("bad request", "text/plain");
  952. });
  953. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  954. auto se = detail::scope_exit([&] {
  955. svr.stop();
  956. listen_thread.join();
  957. ASSERT_FALSE(svr.is_running());
  958. });
  959. svr.wait_until_ready();
  960. Client cli("localhost", PORT);
  961. {
  962. auto res = cli.Get(
  963. "/accept_ok",
  964. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  966. EXPECT_EQ(StatusCode::OK_200, res->status);
  967. }
  968. {
  969. auto res = cli.Get("/accept_bad_request",
  970. Headers{{"Accept", "text/html;q=abc,application/json"}});
  971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  972. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  973. }
  974. }
  975. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  976. Server svr;
  977. svr.Get("/", [](const Request & /*req*/, Response &res) {
  978. res.set_content("ok", "text/plain");
  979. });
  980. std::atomic<int> start_count{0};
  981. std::atomic<bool> running_when_called{false};
  982. svr.set_start_handler([&]() {
  983. running_when_called = svr.is_running();
  984. start_count++;
  985. });
  986. auto port = svr.bind_to_any_port(HOST);
  987. std::thread t([&]() { svr.listen_after_bind(); });
  988. auto se = detail::scope_exit([&] {
  989. svr.stop();
  990. t.join();
  991. ASSERT_FALSE(svr.is_running());
  992. });
  993. svr.wait_until_ready();
  994. // A successful request proves the accept loop is running, which the start
  995. // handler precedes; so by now the handler must have run exactly once.
  996. Client cli(HOST, port);
  997. cli.set_connection_timeout(std::chrono::seconds(5));
  998. auto res = cli.Get("/");
  999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1000. EXPECT_EQ(StatusCode::OK_200, res->status);
  1001. EXPECT_EQ(1, start_count.load());
  1002. EXPECT_TRUE(running_when_called.load());
  1003. }
  1004. TEST(DivideTest, DivideStringTests) {
  1005. auto divide = [](const std::string &str, char d) {
  1006. std::string lhs;
  1007. std::string rhs;
  1008. detail::divide(str, d,
  1009. [&](const char *lhs_data, std::size_t lhs_size,
  1010. const char *rhs_data, std::size_t rhs_size) {
  1011. lhs.assign(lhs_data, lhs_size);
  1012. rhs.assign(rhs_data, rhs_size);
  1013. });
  1014. return std::make_pair(std::move(lhs), std::move(rhs));
  1015. };
  1016. {
  1017. const auto res = divide("", '=');
  1018. EXPECT_EQ(res.first, "");
  1019. EXPECT_EQ(res.second, "");
  1020. }
  1021. {
  1022. const auto res = divide("=", '=');
  1023. EXPECT_EQ(res.first, "");
  1024. EXPECT_EQ(res.second, "");
  1025. }
  1026. {
  1027. const auto res = divide(" ", '=');
  1028. EXPECT_EQ(res.first, " ");
  1029. EXPECT_EQ(res.second, "");
  1030. }
  1031. {
  1032. const auto res = divide("a", '=');
  1033. EXPECT_EQ(res.first, "a");
  1034. EXPECT_EQ(res.second, "");
  1035. }
  1036. {
  1037. const auto res = divide("a=", '=');
  1038. EXPECT_EQ(res.first, "a");
  1039. EXPECT_EQ(res.second, "");
  1040. }
  1041. {
  1042. const auto res = divide("=b", '=');
  1043. EXPECT_EQ(res.first, "");
  1044. EXPECT_EQ(res.second, "b");
  1045. }
  1046. {
  1047. const auto res = divide("a=b", '=');
  1048. EXPECT_EQ(res.first, "a");
  1049. EXPECT_EQ(res.second, "b");
  1050. }
  1051. {
  1052. const auto res = divide("a=b=", '=');
  1053. EXPECT_EQ(res.first, "a");
  1054. EXPECT_EQ(res.second, "b=");
  1055. }
  1056. {
  1057. const auto res = divide("a=b=c", '=');
  1058. EXPECT_EQ(res.first, "a");
  1059. EXPECT_EQ(res.second, "b=c");
  1060. }
  1061. }
  1062. TEST(SplitTest, ParseQueryString) {
  1063. string s = "key1=val1&key2=val2&key3=val3";
  1064. Params dic;
  1065. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1066. [&](const char *b, const char *e) {
  1067. string key, val;
  1068. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1069. if (key.empty()) {
  1070. key.assign(b2, e2);
  1071. } else {
  1072. val.assign(b2, e2);
  1073. }
  1074. });
  1075. dic.emplace(key, val);
  1076. });
  1077. EXPECT_EQ("val1", dic.find("key1")->second);
  1078. EXPECT_EQ("val2", dic.find("key2")->second);
  1079. EXPECT_EQ("val3", dic.find("key3")->second);
  1080. }
  1081. TEST(SplitTest, ParseInvalidQueryTests) {
  1082. {
  1083. string s = " ";
  1084. Params dict;
  1085. detail::parse_query_text(s, dict);
  1086. EXPECT_TRUE(dict.empty());
  1087. }
  1088. {
  1089. string s = " = =";
  1090. Params dict;
  1091. detail::parse_query_text(s, dict);
  1092. EXPECT_TRUE(dict.empty());
  1093. }
  1094. }
  1095. TEST(ParseQueryTest, ParseQueryString) {
  1096. {
  1097. std::string s = "key1=val1&key2=val2&key3=val3";
  1098. Params dic;
  1099. detail::parse_query_text(s, dic);
  1100. EXPECT_EQ("val1", dic.find("key1")->second);
  1101. EXPECT_EQ("val2", dic.find("key2")->second);
  1102. EXPECT_EQ("val3", dic.find("key3")->second);
  1103. }
  1104. {
  1105. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1106. Params dic;
  1107. detail::parse_query_text(s, dic);
  1108. EXPECT_EQ("", dic.find("key1")->second);
  1109. EXPECT_EQ("val1", dic.find("key2")->second);
  1110. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1111. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1112. }
  1113. }
  1114. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1115. Params dic;
  1116. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1117. dic.emplace("key1", "val1");
  1118. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1119. dic.emplace("key2", "val2");
  1120. dic.emplace("key3", "val3");
  1121. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1122. }
  1123. // Joins every entry of a Headers or Params into "key=value " so a whole
  1124. // traversal can be compared in one assertion. Both are instantiations of the
  1125. // same insertion-ordered container, so one helper serves both.
  1126. template <typename Map> static std::string entries_to_string(const Map &m) {
  1127. std::string s;
  1128. for (const auto &entry : m) {
  1129. s += entry.first + "=" + entry.second + " ";
  1130. }
  1131. return s;
  1132. }
  1133. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1134. // Params used to be a std::multimap, which sorted by name and handed the
  1135. // caller's query back alphabetised. A client signing its query string could
  1136. // not reproduce the order it asked for.
  1137. Params dic;
  1138. dic.emplace("zulu", "1");
  1139. dic.emplace("alpha", "2");
  1140. dic.emplace("mike", "3");
  1141. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1142. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1143. }
  1144. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1145. Params dic;
  1146. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1147. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1148. }
  1149. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1150. Request req;
  1151. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1152. req.params);
  1153. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1154. EXPECT_EQ("first", req.get_param_value("tag"));
  1155. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1156. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1157. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1158. EXPECT_EQ("", req.get_param_value("tag", 3));
  1159. }
  1160. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1161. // Params shares its container with Headers, which matches field names
  1162. // case-insensitively. Parameter names must not pick that up.
  1163. Params dic;
  1164. dic.emplace("Key", "upper");
  1165. dic.emplace("key", "lower");
  1166. EXPECT_EQ(2U, dic.size());
  1167. EXPECT_EQ(1U, dic.count("Key"));
  1168. EXPECT_EQ(1U, dic.count("key"));
  1169. EXPECT_EQ("upper", dic.find("Key")->second);
  1170. EXPECT_EQ("lower", dic.find("key")->second);
  1171. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1172. }
  1173. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1174. Server svr;
  1175. std::string order;
  1176. svr.Get("/order", [&](const Request &req, Response &res) {
  1177. order = entries_to_string(req.params);
  1178. res.set_content("ok", "text/plain");
  1179. });
  1180. auto port = svr.bind_to_any_port(HOST);
  1181. thread t = thread([&] { svr.listen_after_bind(); });
  1182. auto se = detail::scope_exit([&] {
  1183. svr.stop();
  1184. t.join();
  1185. ASSERT_FALSE(svr.is_running());
  1186. });
  1187. svr.wait_until_ready();
  1188. Client cli(HOST, port);
  1189. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1190. ASSERT_TRUE(res);
  1191. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1192. }
  1193. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1194. Server svr;
  1195. std::string field_order, file_order;
  1196. svr.Post("/order", [&](const Request &req, Response &res) {
  1197. for (const auto &field : req.form.fields) {
  1198. field_order += field.first + "=" + field.second.content + " ";
  1199. }
  1200. for (const auto &file : req.form.files) {
  1201. file_order += file.first + "=" + file.second.filename + " ";
  1202. }
  1203. res.set_content("ok", "text/plain");
  1204. });
  1205. auto port = svr.bind_to_any_port(HOST);
  1206. thread t = thread([&] { svr.listen_after_bind(); });
  1207. auto se = detail::scope_exit([&] {
  1208. svr.stop();
  1209. t.join();
  1210. ASSERT_FALSE(svr.is_running());
  1211. });
  1212. svr.wait_until_ready();
  1213. UploadFormDataItems items = {
  1214. {"zulu", "1", "", ""},
  1215. {"alpha", "2", "", ""},
  1216. {"mike", "3", "", ""},
  1217. {"zebra", "z", "z.txt", "text/plain"},
  1218. {"apple", "a", "a.txt", "text/plain"},
  1219. };
  1220. Client cli(HOST, port);
  1221. auto res = cli.Post("/order", items);
  1222. ASSERT_TRUE(res);
  1223. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1224. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1225. }
  1226. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1227. Server svr;
  1228. std::vector<std::string> values;
  1229. std::string first, second, out_of_range, order;
  1230. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1231. values = req.form.get_fields("tag");
  1232. first = req.form.get_field("tag", 0);
  1233. second = req.form.get_field("tag", 1);
  1234. out_of_range = req.form.get_field("tag", 2);
  1235. for (const auto &field : req.form.fields) {
  1236. order += field.first + "=" + field.second.content + " ";
  1237. }
  1238. res.set_content("ok", "text/plain");
  1239. });
  1240. auto port = svr.bind_to_any_port(HOST);
  1241. thread t = thread([&] { svr.listen_after_bind(); });
  1242. auto se = detail::scope_exit([&] {
  1243. svr.stop();
  1244. t.join();
  1245. ASSERT_FALSE(svr.is_running());
  1246. });
  1247. svr.wait_until_ready();
  1248. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1249. // not adjacent in the container.
  1250. UploadFormDataItems items = {
  1251. {"tag", "first", "", ""},
  1252. {"other", "x", "", ""},
  1253. {"tag", "second", "", ""},
  1254. };
  1255. Client cli(HOST, port);
  1256. auto res = cli.Post("/repeated", items);
  1257. ASSERT_TRUE(res);
  1258. ASSERT_EQ(2U, values.size());
  1259. EXPECT_EQ("first", values[0]);
  1260. EXPECT_EQ("second", values[1]);
  1261. EXPECT_EQ("first", first);
  1262. EXPECT_EQ("second", second);
  1263. // std::multimap already kept entries sharing a name in insertion order, so
  1264. // everything above passes without this change too. The whole traversal is
  1265. // what tells the two apart: sorting by name would hoist "other" to the front
  1266. // and the two "tag" parts would end up adjacent.
  1267. EXPECT_EQ("tag=first other=x tag=second ", order);
  1268. // Advancing past the last entry of a name used to run off the container;
  1269. // the container's saturating increment makes it return the default instead.
  1270. EXPECT_EQ("", out_of_range);
  1271. }
  1272. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1273. // Server::read_content() keeps a FormFields::iterator alive across the
  1274. // content callbacks that fill the part it points at. The container is
  1275. // vector-backed, so a later emplace can reallocate and invalidate an older
  1276. // iterator; 64 parts grow the vector through seven reallocations, which
  1277. // checks that every part's content still lands in its own entry.
  1278. const size_t part_count = 64;
  1279. // One formula for both the parts sent and the values expected back, so the
  1280. // two cannot drift apart.
  1281. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1282. auto content_of = [](size_t i) {
  1283. return std::string(64, static_cast<char>('a' + (i % 26)));
  1284. };
  1285. Server svr;
  1286. std::vector<std::pair<std::string, std::string>> received;
  1287. svr.Post("/many", [&](const Request &req, Response &res) {
  1288. for (const auto &field : req.form.fields) {
  1289. received.emplace_back(field.first, field.second.content);
  1290. }
  1291. res.set_content("ok", "text/plain");
  1292. });
  1293. auto port = svr.bind_to_any_port(HOST);
  1294. thread t = thread([&] { svr.listen_after_bind(); });
  1295. auto se = detail::scope_exit([&] {
  1296. svr.stop();
  1297. t.join();
  1298. ASSERT_FALSE(svr.is_running());
  1299. });
  1300. svr.wait_until_ready();
  1301. UploadFormDataItems items;
  1302. for (size_t i = 0; i < part_count; i++) {
  1303. items.push_back({name_of(i), content_of(i), "", ""});
  1304. }
  1305. Client cli(HOST, port);
  1306. auto res = cli.Post("/many", items);
  1307. ASSERT_TRUE(res);
  1308. ASSERT_EQ(part_count, received.size());
  1309. for (size_t i = 0; i < part_count; i++) {
  1310. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1311. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1312. }
  1313. }
  1314. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1315. string content_type = "multipart/form-data; boundary=something";
  1316. string boundary;
  1317. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1318. EXPECT_TRUE(ret);
  1319. EXPECT_EQ(boundary, "something");
  1320. }
  1321. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1322. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1323. string boundary;
  1324. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1325. EXPECT_TRUE(ret);
  1326. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1327. }
  1328. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1329. string content_type =
  1330. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1331. string boundary;
  1332. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1333. EXPECT_TRUE(ret);
  1334. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1335. }
  1336. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1337. string content_type =
  1338. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1339. string boundary;
  1340. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1341. EXPECT_TRUE(ret);
  1342. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1343. }
  1344. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1345. const string boundary(70, 'a');
  1346. string content_type = "multipart/form-data; boundary=" + boundary;
  1347. string parsed;
  1348. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1349. EXPECT_TRUE(ret);
  1350. EXPECT_EQ(parsed, boundary);
  1351. }
  1352. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1353. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1354. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1355. string parsed;
  1356. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1357. EXPECT_FALSE(ret);
  1358. }
  1359. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1360. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1361. // is 72 characters on the wire and still valid.
  1362. const string boundary(70, 'a');
  1363. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1364. string parsed;
  1365. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1366. EXPECT_EQ(parsed, boundary);
  1367. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1368. parsed.clear();
  1369. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1370. }
  1371. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1372. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1373. // The parameter parser must not treat that '=' as the key/value separator.
  1374. string content_type =
  1375. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1376. "charset=UTF-8";
  1377. string parsed;
  1378. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1379. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1380. }
  1381. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1382. // A ';' inside the quoted-string is part of the value, not a parameter
  1383. // separator, so it must not truncate the boundary.
  1384. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1385. string parsed;
  1386. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1387. EXPECT_EQ(parsed, "a;b");
  1388. }
  1389. TEST(ParseDispositionParamsTest, QuotedValues) {
  1390. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1391. // ';' and '=' are ordinary characters inside one.
  1392. struct {
  1393. const char *value;
  1394. std::vector<std::pair<const char *, const char *>> expected;
  1395. } cases[] = {
  1396. {"name=\"file1\"; filename=\"a.txt\"",
  1397. {{"name", "file1"}, {"filename", "a.txt"}}},
  1398. // Whitespace around '=' and ';' is still trimmed
  1399. {"name=\"file2\" ;filename = \"a.html\"",
  1400. {{"name", "file2"}, {"filename", "a.html"}}},
  1401. // '=' inside the value used to leave only the text after the last one
  1402. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1403. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1404. {"name=\"x=y\"", {{"name", "x=y"}}},
  1405. // ';' inside the value used to truncate the pair and leave a bogus one
  1406. {"name=\"file3\"; filename=\"a;b.txt\"",
  1407. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1408. // An unquoted value keeps working, and so does filename*
  1409. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1410. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1411. // A parameter with no key is dropped rather than turned into one whose
  1412. // key is the value
  1413. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1414. };
  1415. for (const auto &c : cases) {
  1416. Params params;
  1417. detail::parse_disposition_params(c.value, params);
  1418. for (const auto &kv : c.expected) {
  1419. auto it = params.find(kv.first);
  1420. ASSERT_NE(it, params.end())
  1421. << "value: " << c.value << ", key: " << kv.first;
  1422. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1423. }
  1424. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1425. }
  1426. }
  1427. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1428. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1429. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1430. Server svr;
  1431. std::string field_value, file_name, file_filename;
  1432. bool has_field = false, has_file = false;
  1433. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1434. has_field = req.form.has_field("x=y");
  1435. field_value = req.form.get_field("x=y");
  1436. has_file = req.form.has_file("file1");
  1437. const auto &file = req.form.get_file("file1");
  1438. file_name = file.name;
  1439. file_filename = file.filename;
  1440. res.set_content("ok", "text/plain");
  1441. });
  1442. auto port = svr.bind_to_any_port(HOST);
  1443. thread t = thread([&] { svr.listen_after_bind(); });
  1444. auto se = detail::scope_exit([&] {
  1445. svr.stop();
  1446. t.join();
  1447. ASSERT_FALSE(svr.is_running());
  1448. });
  1449. svr.wait_until_ready();
  1450. UploadFormDataItems items = {
  1451. {"x=y", "field-value", "", ""},
  1452. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1453. };
  1454. Client cli(HOST, port);
  1455. auto res = cli.Post("/quoted", items);
  1456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1457. ASSERT_EQ(StatusCode::OK_200, res->status);
  1458. EXPECT_TRUE(has_field);
  1459. EXPECT_EQ("field-value", field_value);
  1460. EXPECT_TRUE(has_file);
  1461. EXPECT_EQ("file1", file_name);
  1462. EXPECT_EQ("a;b=report.pdf", file_filename);
  1463. }
  1464. TEST(GetHeaderValueTest, DefaultValue) {
  1465. Headers headers = {{"Dummy", "Dummy"}};
  1466. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1467. EXPECT_STREQ("text/plain", val);
  1468. }
  1469. TEST(GetHeaderValueTest, DefaultValueInt) {
  1470. Headers headers = {{"Dummy", "Dummy"}};
  1471. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1472. EXPECT_EQ(100ull, val);
  1473. }
  1474. TEST(GetHeaderValueTest, RegularValue) {
  1475. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1476. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1477. EXPECT_STREQ("text/html", val);
  1478. }
  1479. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1480. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1481. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1482. EXPECT_STREQ("text/html", val);
  1483. }
  1484. TEST(GetHeaderValueTest, SetContent) {
  1485. Response res;
  1486. res.set_content("html", "text/html");
  1487. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1488. res.set_content("text", "text/plain");
  1489. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1490. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1491. }
  1492. TEST(GetHeaderValueTest, RegularValueInt) {
  1493. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1494. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1495. EXPECT_EQ(100ull, val);
  1496. }
  1497. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1498. Headers headers = {{"Content-Length", "x"}};
  1499. auto is_invalid_value = false;
  1500. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1501. is_invalid_value);
  1502. EXPECT_EQ(0ull, val);
  1503. EXPECT_TRUE(is_invalid_value);
  1504. }
  1505. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1506. // An all-digit value that overflows size_t must be reported as invalid, not
  1507. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1508. // a large length to a small one on 32-bit builds, leaving the framing length
  1509. // wrong while is_invalid_value stayed false.
  1510. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1511. auto is_invalid_value = false;
  1512. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1513. is_invalid_value);
  1514. EXPECT_TRUE(is_invalid_value);
  1515. // A well-formed length is unaffected.
  1516. Headers ok = {{"Content-Length", "1234"}};
  1517. is_invalid_value = false;
  1518. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1519. is_invalid_value);
  1520. EXPECT_EQ(1234ull, val);
  1521. EXPECT_FALSE(is_invalid_value);
  1522. }
  1523. TEST(GetHeaderValueTest, Range) {
  1524. {
  1525. Headers headers = {make_range_header({{1, -1}})};
  1526. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1527. EXPECT_STREQ("bytes=1-", val);
  1528. }
  1529. {
  1530. Headers headers = {make_range_header({{-1, 1}})};
  1531. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1532. EXPECT_STREQ("bytes=-1", val);
  1533. }
  1534. {
  1535. Headers headers = {make_range_header({{1, 10}})};
  1536. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1537. EXPECT_STREQ("bytes=1-10", val);
  1538. }
  1539. {
  1540. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1541. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1542. EXPECT_STREQ("bytes=1-10, 100-", val);
  1543. }
  1544. {
  1545. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1546. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1547. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1548. }
  1549. {
  1550. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1551. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1552. EXPECT_STREQ("bytes=0-0, -1", val);
  1553. }
  1554. }
  1555. TEST(BearerTokenAuthTest, SchemeValidation) {
  1556. // A value shorter than "Bearer " must not throw from the fixed-length
  1557. // substr, and a non-Bearer scheme must not be reported as a token.
  1558. struct {
  1559. const char *value;
  1560. const char *expected;
  1561. } cases[] = {
  1562. {"x", ""},
  1563. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1564. {"Bearer abc123", "abc123"},
  1565. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1566. };
  1567. for (const auto &c : cases) {
  1568. Request req;
  1569. req.set_header("Authorization", c.value);
  1570. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1571. }
  1572. }
  1573. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1574. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1575. // to depend on the standard library (libstdc++ handed back duplicates in
  1576. // reverse insertion order, libc++ in insertion order).
  1577. Request req;
  1578. req.set_header("Accept-Encoding", "gzip");
  1579. req.set_header("Accept-Encoding", "deflate");
  1580. req.set_header("Accept-Encoding", "br");
  1581. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1582. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1583. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1584. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1585. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1586. }
  1587. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1588. Request req;
  1589. req.set_header("X-Test", "only");
  1590. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1591. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1592. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1593. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1594. }
  1595. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1596. Headers headers;
  1597. headers.emplace("Host", "example.com");
  1598. headers.emplace("Accept-Encoding", "gzip");
  1599. headers.emplace("User-Agent", "test");
  1600. headers.emplace("Accept-Encoding", "deflate");
  1601. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1602. "Accept-Encoding=deflate ",
  1603. entries_to_string(headers));
  1604. }
  1605. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1606. Headers headers = {{"Content-Type", "text/html"},
  1607. {"CONTENT-TYPE", "text/xml"}};
  1608. EXPECT_EQ(2U, headers.count("content-type"));
  1609. auto it = headers.find("content-type");
  1610. ASSERT_TRUE(it != headers.end());
  1611. EXPECT_EQ("text/html", it->second);
  1612. }
  1613. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1614. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1615. // drop only those fields and leave everything positioned between them.
  1616. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1617. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1618. auto rng = headers.equal_range("a");
  1619. headers.erase(rng.first, rng.second);
  1620. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1621. }
  1622. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1623. Headers headers = {
  1624. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1625. EXPECT_EQ(3U, headers.erase("A"));
  1626. EXPECT_EQ(0U, headers.count("A"));
  1627. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1628. }
  1629. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1630. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1631. headers.emplace_front("Host", "example.com");
  1632. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1633. entries_to_string(headers));
  1634. }
  1635. TEST(ParseHeaderValueTest, Range) {
  1636. {
  1637. Ranges ranges;
  1638. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1639. EXPECT_TRUE(ret);
  1640. EXPECT_EQ(1u, ranges.size());
  1641. EXPECT_EQ(1u, ranges[0].first);
  1642. EXPECT_EQ(-1, ranges[0].second);
  1643. }
  1644. {
  1645. Ranges ranges;
  1646. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1647. EXPECT_TRUE(ret);
  1648. EXPECT_EQ(1u, ranges.size());
  1649. EXPECT_EQ(-1, ranges[0].first);
  1650. EXPECT_EQ(1u, ranges[0].second);
  1651. }
  1652. {
  1653. Ranges ranges;
  1654. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1655. EXPECT_TRUE(ret);
  1656. EXPECT_EQ(1u, ranges.size());
  1657. EXPECT_EQ(1u, ranges[0].first);
  1658. EXPECT_EQ(10u, ranges[0].second);
  1659. }
  1660. {
  1661. Ranges ranges;
  1662. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1663. EXPECT_FALSE(ret);
  1664. }
  1665. {
  1666. Ranges ranges;
  1667. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1668. EXPECT_TRUE(ret);
  1669. EXPECT_EQ(2u, ranges.size());
  1670. EXPECT_EQ(1u, ranges[0].first);
  1671. EXPECT_EQ(10u, ranges[0].second);
  1672. EXPECT_EQ(100u, ranges[1].first);
  1673. EXPECT_EQ(-1, ranges[1].second);
  1674. }
  1675. {
  1676. Ranges ranges;
  1677. auto ret =
  1678. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1679. EXPECT_TRUE(ret);
  1680. EXPECT_EQ(3u, ranges.size());
  1681. EXPECT_EQ(1u, ranges[0].first);
  1682. EXPECT_EQ(10u, ranges[0].second);
  1683. EXPECT_EQ(100u, ranges[1].first);
  1684. EXPECT_EQ(200u, ranges[1].second);
  1685. EXPECT_EQ(300u, ranges[2].first);
  1686. EXPECT_EQ(400u, ranges[2].second);
  1687. }
  1688. {
  1689. Ranges ranges;
  1690. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1691. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1692. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1693. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1694. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1695. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1696. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1697. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1698. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1699. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1700. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1701. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1702. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1703. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1704. EXPECT_FALSE(
  1705. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1706. EXPECT_TRUE(ranges.empty());
  1707. }
  1708. {
  1709. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1710. // remainder of the representation, so it stays accepted.
  1711. Ranges ranges;
  1712. auto ret =
  1713. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1714. EXPECT_TRUE(ret);
  1715. ASSERT_EQ(1u, ranges.size());
  1716. EXPECT_EQ(0, ranges[0].first);
  1717. EXPECT_EQ(-1, ranges[0].second);
  1718. }
  1719. }
  1720. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1721. Request req;
  1722. req.set_header("Accept-Encoding", "gzip");
  1723. Response res;
  1724. res.set_header("Content-Type", "text/plain");
  1725. auto ret = detail::encoding_type(req, res);
  1726. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1727. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1728. #else
  1729. EXPECT_TRUE(ret == detail::EncodingType::None);
  1730. #endif
  1731. }
  1732. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1733. Request req;
  1734. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1735. Response res;
  1736. res.set_header("Content-Type", "text/plain");
  1737. auto ret = detail::encoding_type(req, res);
  1738. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1739. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1740. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1741. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1742. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1743. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1744. #else
  1745. EXPECT_TRUE(ret == detail::EncodingType::None);
  1746. #endif
  1747. }
  1748. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1749. Request req;
  1750. req.set_header("Accept-Encoding",
  1751. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1752. Response res;
  1753. res.set_header("Content-Type", "text/plain");
  1754. auto ret = detail::encoding_type(req, res);
  1755. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1756. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1757. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1758. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1759. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1760. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1761. #else
  1762. EXPECT_TRUE(ret == detail::EncodingType::None);
  1763. #endif
  1764. }
  1765. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1766. // All supported encodings rejected with q=0 should return None
  1767. Request req;
  1768. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1769. Response res;
  1770. res.set_header("Content-Type", "text/plain");
  1771. auto ret = detail::encoding_type(req, res);
  1772. EXPECT_TRUE(ret == detail::EncodingType::None);
  1773. }
  1774. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1775. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1776. Request req;
  1777. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1778. Response res;
  1779. res.set_header("Content-Type", "text/plain");
  1780. auto ret = detail::encoding_type(req, res);
  1781. EXPECT_TRUE(ret == detail::EncodingType::None);
  1782. }
  1783. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  1784. Request req;
  1785. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  1786. Response res;
  1787. res.set_header("Content-Type", "text/plain");
  1788. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  1789. }
  1790. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1791. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1792. Request req;
  1793. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1794. Response res;
  1795. res.set_header("Content-Type", "text/plain");
  1796. auto ret = detail::encoding_type(req, res);
  1797. EXPECT_TRUE(ret == detail::EncodingType::None);
  1798. }
  1799. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1800. // RFC 7231: Accept-Encoding values are case-insensitive
  1801. Request req;
  1802. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1803. Response res;
  1804. res.set_header("Content-Type", "text/plain");
  1805. auto ret = detail::encoding_type(req, res);
  1806. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1807. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1808. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1809. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1810. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1811. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1812. #else
  1813. EXPECT_TRUE(ret == detail::EncodingType::None);
  1814. #endif
  1815. }
  1816. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1817. // q value should determine priority, not hardcoded order
  1818. Request req;
  1819. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1820. Response res;
  1821. res.set_header("Content-Type", "text/plain");
  1822. auto ret = detail::encoding_type(req, res);
  1823. // gzip has highest q=1.0, so it should be selected even though
  1824. // br and zstd are also supported
  1825. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1826. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1827. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1828. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1829. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1830. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1831. #else
  1832. EXPECT_TRUE(ret == detail::EncodingType::None);
  1833. #endif
  1834. }
  1835. TEST(BufferStreamTest, read) {
  1836. detail::BufferStream strm1;
  1837. Stream &strm = strm1;
  1838. EXPECT_EQ(5, strm.write("hello"));
  1839. char buf[512];
  1840. EXPECT_EQ(2, strm.read(buf, 2));
  1841. EXPECT_EQ('h', buf[0]);
  1842. EXPECT_EQ('e', buf[1]);
  1843. EXPECT_EQ(2, strm.read(buf, 2));
  1844. EXPECT_EQ('l', buf[0]);
  1845. EXPECT_EQ('l', buf[1]);
  1846. EXPECT_EQ(1, strm.read(buf, 1));
  1847. EXPECT_EQ('o', buf[0]);
  1848. EXPECT_EQ(0, strm.read(buf, 1));
  1849. }
  1850. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1851. auto host = "www.httpwatch.com";
  1852. auto ip = hosted_at(host);
  1853. EXPECT_EQ("23.96.13.243", ip);
  1854. std::vector<std::string> addrs;
  1855. hosted_at(host, addrs);
  1856. EXPECT_EQ(1u, addrs.size());
  1857. }
  1858. #if 0 // It depends on each test environment...
  1859. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1860. auto host = "www.youtube.com";
  1861. std::vector<std::string> addrs;
  1862. hosted_at(host, addrs);
  1863. EXPECT_EQ(20u, addrs.size());
  1864. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1865. EXPECT_TRUE(it != addrs.end());
  1866. }
  1867. #endif
  1868. class ChunkedEncodingTest : public ::testing::Test {
  1869. protected:
  1870. ChunkedEncodingTest()
  1871. : cli_(HOST, PORT)
  1872. #ifdef CPPHTTPLIB_SSL_ENABLED
  1873. ,
  1874. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1875. #endif
  1876. {
  1877. cli_.set_connection_timeout(2);
  1878. #ifdef CPPHTTPLIB_SSL_ENABLED
  1879. cli_.enable_server_certificate_verification(false);
  1880. #endif
  1881. }
  1882. virtual void SetUp() {
  1883. read_file("./image.jpg", image_data_);
  1884. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1885. res.set_content("Hello World!", "text/plain");
  1886. });
  1887. svr_.Get(
  1888. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1889. res.set_chunked_content_provider(
  1890. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1891. size_t remaining = image_data_.size() - offset;
  1892. if (remaining == 0) {
  1893. sink.done();
  1894. } else {
  1895. constexpr size_t CHUNK_SIZE = 1024;
  1896. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1897. sink.write(&image_data_[offset], send_size);
  1898. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1899. }
  1900. return true;
  1901. });
  1902. });
  1903. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1904. svr_.wait_until_ready();
  1905. }
  1906. virtual void TearDown() {
  1907. svr_.stop();
  1908. if (!request_threads_.empty()) {
  1909. std::this_thread::sleep_for(std::chrono::seconds(1));
  1910. for (auto &t : request_threads_) {
  1911. t.join();
  1912. }
  1913. }
  1914. t_.join();
  1915. }
  1916. #ifdef CPPHTTPLIB_SSL_ENABLED
  1917. SSLClient cli_;
  1918. SSLServer svr_;
  1919. #else
  1920. Client cli_;
  1921. Server svr_;
  1922. #endif
  1923. thread t_;
  1924. std::vector<thread> request_threads_;
  1925. std::string image_data_;
  1926. };
  1927. TEST_F(ChunkedEncodingTest, NormalGet) {
  1928. auto res = cli_.Get("/chunked");
  1929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1930. std::string out;
  1931. read_file("./image.jpg", out);
  1932. EXPECT_EQ(StatusCode::OK_200, res->status);
  1933. EXPECT_EQ(out, res->body);
  1934. }
  1935. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1936. std::string body;
  1937. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1938. body.append(data, data_length);
  1939. return true;
  1940. });
  1941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1942. std::string out;
  1943. read_file("./image.jpg", out);
  1944. EXPECT_EQ(StatusCode::OK_200, res->status);
  1945. EXPECT_EQ(out, body);
  1946. }
  1947. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1948. std::string body;
  1949. auto res = cli_.Get(
  1950. "/chunked",
  1951. [&](const Response &response) {
  1952. EXPECT_EQ(StatusCode::OK_200, response.status);
  1953. return true;
  1954. },
  1955. [&](const char *data, size_t data_length) {
  1956. body.append(data, data_length);
  1957. return true;
  1958. });
  1959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1960. std::string out;
  1961. read_file("./image.jpg", out);
  1962. EXPECT_EQ(StatusCode::OK_200, res->status);
  1963. EXPECT_EQ(out, body);
  1964. }
  1965. TEST(RangeTest, FromHTTPBin_Online) {
  1966. auto host = "httpbingo.org";
  1967. auto path = std::string{"/range/32"};
  1968. #ifdef CPPHTTPLIB_SSL_ENABLED
  1969. auto port = 443;
  1970. SSLClient cli(host, port);
  1971. #else
  1972. auto port = 80;
  1973. Client cli(host, port);
  1974. #endif
  1975. cli.set_connection_timeout(5);
  1976. {
  1977. auto res = cli.Get(path);
  1978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1979. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1980. EXPECT_EQ(StatusCode::OK_200, res->status);
  1981. }
  1982. {
  1983. Headers headers = {make_range_header({{1, -1}})};
  1984. auto res = cli.Get(path, headers);
  1985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1986. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1987. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1988. }
  1989. {
  1990. Headers headers = {make_range_header({{1, 10}})};
  1991. auto res = cli.Get(path, headers);
  1992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1993. EXPECT_EQ("bcdefghijk", res->body);
  1994. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1995. }
  1996. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1997. // entire resource, while the original httpbin returned 200. Both are
  1998. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1999. {
  2000. Headers headers = {make_range_header({{0, 31}})};
  2001. auto res = cli.Get(path, headers);
  2002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2003. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2004. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2005. res->status == StatusCode::PartialContent_206);
  2006. }
  2007. {
  2008. Headers headers = {make_range_header({{0, -1}})};
  2009. auto res = cli.Get(path, headers);
  2010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2011. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2012. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2013. res->status == StatusCode::PartialContent_206);
  2014. }
  2015. // go-httpbin returns 206 with clamped range for over-range requests,
  2016. // while the original httpbin returned 416. Both behaviors are observed
  2017. // in real servers, so we only verify the request succeeds.
  2018. {
  2019. Headers headers = {make_range_header({{0, 32}})};
  2020. auto res = cli.Get(path, headers);
  2021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2022. }
  2023. }
  2024. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2025. auto host = "unresolvableaddress.local";
  2026. auto path = std::string{"/"};
  2027. #ifdef CPPHTTPLIB_SSL_ENABLED
  2028. auto port = 443;
  2029. SSLClient cli(host, port);
  2030. #else
  2031. auto port = 80;
  2032. Client cli(host, port);
  2033. #endif
  2034. cli.set_connection_timeout(1);
  2035. {
  2036. auto res = cli.Get(path);
  2037. ASSERT_FALSE(res);
  2038. }
  2039. std::this_thread::sleep_for(std::chrono::seconds(8));
  2040. }
  2041. #if defined(__linux__) && defined(__GLIBC__) && \
  2042. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2043. // Forward declaration: in split builds split.py strips `inline` and moves the
  2044. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2045. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2046. // against the symbol in both header-only and split builds.
  2047. namespace httplib {
  2048. namespace detail {
  2049. int getaddrinfo_with_timeout(const char *node, const char *service,
  2050. const struct addrinfo *hints,
  2051. struct addrinfo **res, time_t timeout_sec);
  2052. } // namespace detail
  2053. } // namespace httplib
  2054. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2055. //
  2056. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2057. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2058. // gai_suspend() call hits the connection timeout the function calls
  2059. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2060. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2061. // still alive and still references the now-destroyed stack frame.
  2062. //
  2063. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2064. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2065. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2066. // and runs them in a container.
  2067. namespace {
  2068. bool should_run_issue_2431_tests() {
  2069. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2070. return v && *v && std::string(v) != "0";
  2071. }
  2072. std::string unique_unresolvable_host(int n) {
  2073. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2074. // glibc still asks the configured nameserver — which is exactly the path
  2075. // we want to exercise. A unique label per call avoids the resolver cache.
  2076. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2077. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2078. std::to_string(n) + ".invalid";
  2079. }
  2080. } // namespace
  2081. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2082. if (!should_run_issue_2431_tests()) {
  2083. GTEST_SKIP()
  2084. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2085. }
  2086. for (int i = 0; i < 8; ++i) {
  2087. struct addrinfo hints;
  2088. memset(&hints, 0, sizeof(hints));
  2089. hints.ai_family = AF_UNSPEC;
  2090. hints.ai_socktype = SOCK_STREAM;
  2091. auto host = unique_unresolvable_host(i);
  2092. struct addrinfo *result = nullptr;
  2093. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2094. &result, /*timeout_sec=*/1);
  2095. if (rc == 0 && result) { freeaddrinfo(result); }
  2096. }
  2097. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2098. // stack region they still believe holds their gaicb.
  2099. std::this_thread::sleep_for(std::chrono::seconds(3));
  2100. }
  2101. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2102. if (!should_run_issue_2431_tests()) {
  2103. GTEST_SKIP()
  2104. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2105. }
  2106. std::atomic<bool> stop{false};
  2107. std::vector<std::thread> threads;
  2108. for (int t = 0; t < 8; ++t) {
  2109. threads.emplace_back([t, &stop] {
  2110. int i = 0;
  2111. while (!stop.load(std::memory_order_relaxed)) {
  2112. struct addrinfo hints;
  2113. memset(&hints, 0, sizeof(hints));
  2114. hints.ai_family = AF_UNSPEC;
  2115. hints.ai_socktype = SOCK_STREAM;
  2116. auto host = unique_unresolvable_host(t * 100000 + i++);
  2117. struct addrinfo *result = nullptr;
  2118. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2119. &result, /*timeout_sec=*/1);
  2120. if (rc == 0 && result) { freeaddrinfo(result); }
  2121. }
  2122. });
  2123. }
  2124. std::this_thread::sleep_for(std::chrono::seconds(8));
  2125. stop.store(true, std::memory_order_relaxed);
  2126. for (auto &th : threads) {
  2127. th.join();
  2128. }
  2129. std::this_thread::sleep_for(std::chrono::seconds(3));
  2130. }
  2131. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2132. if (!should_run_issue_2431_tests()) {
  2133. GTEST_SKIP()
  2134. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2135. }
  2136. std::atomic<bool> stop{false};
  2137. std::vector<std::thread> threads;
  2138. for (int t = 0; t < 8; ++t) {
  2139. threads.emplace_back([t, &stop] {
  2140. int i = 0;
  2141. while (!stop.load(std::memory_order_relaxed)) {
  2142. auto host = unique_unresolvable_host(t * 100000 + i++);
  2143. Client cli(host, 80);
  2144. cli.set_connection_timeout(1, 0);
  2145. cli.set_read_timeout(1, 0);
  2146. cli.set_write_timeout(1, 0);
  2147. (void)cli.Get("/");
  2148. }
  2149. });
  2150. }
  2151. std::this_thread::sleep_for(std::chrono::seconds(8));
  2152. stop.store(true, std::memory_order_relaxed);
  2153. for (auto &th : threads) {
  2154. th.join();
  2155. }
  2156. std::this_thread::sleep_for(std::chrono::seconds(3));
  2157. }
  2158. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2159. TEST(ConnectionErrorTest, InvalidHost) {
  2160. auto host = "-abcde.com";
  2161. #ifdef CPPHTTPLIB_SSL_ENABLED
  2162. auto port = 443;
  2163. SSLClient cli(host, port);
  2164. #else
  2165. auto port = 80;
  2166. Client cli(host, port);
  2167. #endif
  2168. cli.set_connection_timeout(std::chrono::seconds(2));
  2169. auto res = cli.Get("/");
  2170. ASSERT_TRUE(!res);
  2171. EXPECT_EQ(Error::Connection, res.error());
  2172. }
  2173. TEST(ConnectionErrorTest, InvalidHost2) {
  2174. auto host = "httpcan.org/";
  2175. #ifdef CPPHTTPLIB_SSL_ENABLED
  2176. SSLClient cli(host);
  2177. #else
  2178. Client cli(host);
  2179. #endif
  2180. cli.set_connection_timeout(std::chrono::seconds(2));
  2181. auto res = cli.Get("/");
  2182. ASSERT_TRUE(!res);
  2183. EXPECT_EQ(Error::Connection, res.error());
  2184. }
  2185. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2186. auto host = "httpcan.org/";
  2187. #ifdef CPPHTTPLIB_SSL_ENABLED
  2188. SSLClient cli(host);
  2189. #else
  2190. Client cli(host);
  2191. #endif
  2192. cli.set_connection_timeout(std::chrono::seconds(2));
  2193. auto res = cli.Get("/");
  2194. ASSERT_TRUE(!res);
  2195. stringstream s;
  2196. s << "error code: " << res.error();
  2197. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2198. }
  2199. TEST(ConnectionErrorTest, InvalidPort) {
  2200. auto host = "localhost";
  2201. auto port = 44380;
  2202. #ifdef CPPHTTPLIB_SSL_ENABLED
  2203. SSLClient cli(host, port);
  2204. #else
  2205. Client cli(host, port);
  2206. #endif
  2207. cli.set_connection_timeout(std::chrono::seconds(2));
  2208. auto res = cli.Get("/");
  2209. ASSERT_TRUE(!res);
  2210. EXPECT_TRUE(Error::Connection == res.error() ||
  2211. Error::ConnectionTimeout == res.error());
  2212. }
  2213. TEST(ConnectionErrorTest, Timeout_Online) {
  2214. auto host = "google.com";
  2215. #ifdef CPPHTTPLIB_SSL_ENABLED
  2216. auto port = 44380;
  2217. SSLClient cli(host, port);
  2218. #else
  2219. auto port = 8080;
  2220. Client cli(host, port);
  2221. #endif
  2222. cli.set_connection_timeout(std::chrono::seconds(2));
  2223. // only probe one address type so that the error reason
  2224. // correlates to the timed-out IPv4, not the unsupported
  2225. // IPv6 connection attempt
  2226. cli.set_address_family(AF_INET);
  2227. auto res = cli.Get("/");
  2228. ASSERT_TRUE(!res);
  2229. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2230. }
  2231. TEST(CancelTest, NoCancel_Online) {
  2232. auto host = "httpbingo.org";
  2233. auto path = std::string{"/range/32"};
  2234. #ifdef CPPHTTPLIB_SSL_ENABLED
  2235. auto port = 443;
  2236. SSLClient cli(host, port);
  2237. #else
  2238. auto port = 80;
  2239. Client cli(host, port);
  2240. #endif
  2241. cli.set_connection_timeout(std::chrono::seconds(5));
  2242. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2244. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2245. EXPECT_EQ(StatusCode::OK_200, res->status);
  2246. }
  2247. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2248. // Use /bytes with a large payload so that the DownloadProgress callback
  2249. // (which only fires for Content-Length responses) is invoked before the
  2250. // entire body is received, giving cancellation a chance to fire.
  2251. auto host = "httpbingo.org";
  2252. auto path = std::string{"/bytes/524288"};
  2253. #ifdef CPPHTTPLIB_SSL_ENABLED
  2254. auto port = 443;
  2255. SSLClient cli(host, port);
  2256. #else
  2257. auto port = 80;
  2258. Client cli(host, port);
  2259. #endif
  2260. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2261. cli.set_connection_timeout(std::chrono::seconds(5));
  2262. ASSERT_TRUE(!res);
  2263. EXPECT_EQ(Error::Canceled, res.error());
  2264. }
  2265. TEST(CancelTest, WithCancelLargePayload_Online) {
  2266. auto host = "httpbingo.org";
  2267. auto path = std::string{"/bytes/524288"};
  2268. #ifdef CPPHTTPLIB_SSL_ENABLED
  2269. auto port = 443;
  2270. SSLClient cli(host, port);
  2271. #else
  2272. auto port = 80;
  2273. Client cli(host, port);
  2274. #endif
  2275. cli.set_connection_timeout(std::chrono::seconds(5));
  2276. uint32_t count = 0;
  2277. auto res =
  2278. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2279. ASSERT_TRUE(!res);
  2280. EXPECT_EQ(Error::Canceled, res.error());
  2281. }
  2282. TEST(CancelTest, NoCancelPost) {
  2283. Server svr;
  2284. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2285. res.set_content("Hello World!", "text/plain");
  2286. });
  2287. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2288. auto se = detail::scope_exit([&] {
  2289. svr.stop();
  2290. thread.join();
  2291. ASSERT_FALSE(svr.is_running());
  2292. });
  2293. svr.wait_until_ready();
  2294. Client cli(HOST, PORT);
  2295. cli.set_connection_timeout(std::chrono::seconds(5));
  2296. auto res =
  2297. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2298. "application/json", [](uint64_t, uint64_t) { return true; });
  2299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2300. EXPECT_EQ("Hello World!", res->body);
  2301. EXPECT_EQ(StatusCode::OK_200, res->status);
  2302. }
  2303. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2304. Server svr;
  2305. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2306. res.set_content("Hello World!", "text/plain");
  2307. });
  2308. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2309. auto se = detail::scope_exit([&] {
  2310. svr.stop();
  2311. thread.join();
  2312. ASSERT_FALSE(svr.is_running());
  2313. });
  2314. svr.wait_until_ready();
  2315. Client cli(HOST, PORT);
  2316. cli.set_connection_timeout(std::chrono::seconds(5));
  2317. auto res =
  2318. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2319. "application/json", [](uint64_t, uint64_t) { return false; });
  2320. ASSERT_TRUE(!res);
  2321. EXPECT_EQ(Error::Canceled, res.error());
  2322. }
  2323. TEST(CancelTest, WithCancelLargePayloadPost) {
  2324. Server svr;
  2325. svr.set_payload_max_length(200 * 1024 * 1024);
  2326. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2327. res.set_content(LARGE_DATA, "text/plain");
  2328. });
  2329. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2330. auto se = detail::scope_exit([&] {
  2331. svr.stop();
  2332. thread.join();
  2333. ASSERT_FALSE(svr.is_running());
  2334. });
  2335. svr.wait_until_ready();
  2336. Client cli(HOST, PORT);
  2337. cli.set_payload_max_length(200 * 1024 * 1024);
  2338. cli.set_connection_timeout(std::chrono::seconds(5));
  2339. auto res =
  2340. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2341. "application/json", [](uint64_t, uint64_t) { return false; });
  2342. ASSERT_TRUE(!res);
  2343. EXPECT_EQ(Error::Canceled, res.error());
  2344. }
  2345. TEST(CancelTest, NoCancelPut) {
  2346. Server svr;
  2347. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2348. res.set_content("Hello World!", "text/plain");
  2349. });
  2350. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2351. auto se = detail::scope_exit([&] {
  2352. svr.stop();
  2353. thread.join();
  2354. ASSERT_FALSE(svr.is_running());
  2355. });
  2356. svr.wait_until_ready();
  2357. Client cli(HOST, PORT);
  2358. cli.set_connection_timeout(std::chrono::seconds(5));
  2359. auto res =
  2360. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2361. "application/json", [](uint64_t, uint64_t) { return true; });
  2362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2363. EXPECT_EQ("Hello World!", res->body);
  2364. EXPECT_EQ(StatusCode::OK_200, res->status);
  2365. }
  2366. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2367. Server svr;
  2368. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2369. res.set_content("Hello World!", "text/plain");
  2370. });
  2371. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2372. auto se = detail::scope_exit([&] {
  2373. svr.stop();
  2374. thread.join();
  2375. ASSERT_FALSE(svr.is_running());
  2376. });
  2377. svr.wait_until_ready();
  2378. Client cli(HOST, PORT);
  2379. cli.set_connection_timeout(std::chrono::seconds(5));
  2380. auto res =
  2381. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2382. "application/json", [](uint64_t, uint64_t) { return false; });
  2383. ASSERT_TRUE(!res);
  2384. EXPECT_EQ(Error::Canceled, res.error());
  2385. }
  2386. TEST(CancelTest, WithCancelLargePayloadPut) {
  2387. Server svr;
  2388. svr.set_payload_max_length(200 * 1024 * 1024);
  2389. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2390. res.set_content(LARGE_DATA, "text/plain");
  2391. });
  2392. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2393. auto se = detail::scope_exit([&] {
  2394. svr.stop();
  2395. thread.join();
  2396. ASSERT_FALSE(svr.is_running());
  2397. });
  2398. svr.wait_until_ready();
  2399. Client cli(HOST, PORT);
  2400. cli.set_payload_max_length(200 * 1024 * 1024);
  2401. cli.set_connection_timeout(std::chrono::seconds(5));
  2402. auto res =
  2403. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2404. "application/json", [](uint64_t, uint64_t) { return false; });
  2405. ASSERT_TRUE(!res);
  2406. EXPECT_EQ(Error::Canceled, res.error());
  2407. }
  2408. TEST(CancelTest, NoCancelPatch) {
  2409. Server svr;
  2410. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2411. res.set_content("Hello World!", "text/plain");
  2412. });
  2413. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2414. auto se = detail::scope_exit([&] {
  2415. svr.stop();
  2416. thread.join();
  2417. ASSERT_FALSE(svr.is_running());
  2418. });
  2419. svr.wait_until_ready();
  2420. Client cli(HOST, PORT);
  2421. cli.set_connection_timeout(std::chrono::seconds(5));
  2422. auto res =
  2423. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2424. "application/json", [](uint64_t, uint64_t) { return true; });
  2425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2426. EXPECT_EQ("Hello World!", res->body);
  2427. EXPECT_EQ(StatusCode::OK_200, res->status);
  2428. }
  2429. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2430. Server svr;
  2431. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2432. res.set_content("Hello World!", "text/plain");
  2433. });
  2434. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2435. auto se = detail::scope_exit([&] {
  2436. svr.stop();
  2437. thread.join();
  2438. ASSERT_FALSE(svr.is_running());
  2439. });
  2440. svr.wait_until_ready();
  2441. Client cli(HOST, PORT);
  2442. cli.set_connection_timeout(std::chrono::seconds(5));
  2443. auto res =
  2444. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2445. "application/json", [](uint64_t, uint64_t) { return false; });
  2446. ASSERT_TRUE(!res);
  2447. EXPECT_EQ(Error::Canceled, res.error());
  2448. }
  2449. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2450. Server svr;
  2451. svr.set_payload_max_length(200 * 1024 * 1024);
  2452. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2453. res.set_content(LARGE_DATA, "text/plain");
  2454. });
  2455. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2456. auto se = detail::scope_exit([&] {
  2457. svr.stop();
  2458. thread.join();
  2459. ASSERT_FALSE(svr.is_running());
  2460. });
  2461. svr.wait_until_ready();
  2462. Client cli(HOST, PORT);
  2463. cli.set_payload_max_length(200 * 1024 * 1024);
  2464. cli.set_connection_timeout(std::chrono::seconds(5));
  2465. auto res =
  2466. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2467. "application/json", [](uint64_t, uint64_t) { return false; });
  2468. ASSERT_TRUE(!res);
  2469. EXPECT_EQ(Error::Canceled, res.error());
  2470. }
  2471. TEST(CancelTest, NoCancelDelete) {
  2472. Server svr;
  2473. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2474. res.set_content("Hello World!", "text/plain");
  2475. });
  2476. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2477. auto se = detail::scope_exit([&] {
  2478. svr.stop();
  2479. thread.join();
  2480. ASSERT_FALSE(svr.is_running());
  2481. });
  2482. svr.wait_until_ready();
  2483. Client cli(HOST, PORT);
  2484. cli.set_connection_timeout(std::chrono::seconds(5));
  2485. auto res =
  2486. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2487. "application/json", [](uint64_t, uint64_t) { return true; });
  2488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2489. EXPECT_EQ("Hello World!", res->body);
  2490. EXPECT_EQ(StatusCode::OK_200, res->status);
  2491. }
  2492. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2493. Server svr;
  2494. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2495. res.set_content("Hello World!", "text/plain");
  2496. });
  2497. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2498. auto se = detail::scope_exit([&] {
  2499. svr.stop();
  2500. thread.join();
  2501. ASSERT_FALSE(svr.is_running());
  2502. });
  2503. svr.wait_until_ready();
  2504. Client cli(HOST, PORT);
  2505. cli.set_connection_timeout(std::chrono::seconds(5));
  2506. auto res =
  2507. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2508. "application/json", [](uint64_t, uint64_t) { return false; });
  2509. ASSERT_TRUE(!res);
  2510. EXPECT_EQ(Error::Canceled, res.error());
  2511. }
  2512. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2513. Server svr;
  2514. svr.set_payload_max_length(200 * 1024 * 1024);
  2515. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2516. res.set_content(LARGE_DATA, "text/plain");
  2517. });
  2518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2519. auto se = detail::scope_exit([&] {
  2520. svr.stop();
  2521. thread.join();
  2522. ASSERT_FALSE(svr.is_running());
  2523. });
  2524. svr.wait_until_ready();
  2525. Client cli(HOST, PORT);
  2526. cli.set_payload_max_length(200 * 1024 * 1024);
  2527. cli.set_connection_timeout(std::chrono::seconds(5));
  2528. auto res =
  2529. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2530. "application/json", [](uint64_t, uint64_t) { return false; });
  2531. ASSERT_TRUE(!res);
  2532. EXPECT_EQ(Error::Canceled, res.error());
  2533. }
  2534. static std::string remove_whitespace(const std::string &input) {
  2535. std::string output;
  2536. output.reserve(input.size());
  2537. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2538. [](unsigned char c) { return !std::isspace(c); });
  2539. return output;
  2540. }
  2541. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2542. auto host = "httpbingo.org";
  2543. auto path = std::string{"/basic-auth/hello/world"};
  2544. #ifdef CPPHTTPLIB_SSL_ENABLED
  2545. auto port = 443;
  2546. SSLClient cli(host, port);
  2547. #else
  2548. auto port = 80;
  2549. Client cli(host, port);
  2550. #endif
  2551. {
  2552. auto res = cli.Get(path);
  2553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2554. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2555. }
  2556. {
  2557. auto res = cli.Get(
  2558. path, Headers{make_basic_authentication_header("hello", "world")});
  2559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2560. auto body = remove_whitespace(res->body);
  2561. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2562. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2563. EXPECT_EQ(StatusCode::OK_200, res->status);
  2564. }
  2565. {
  2566. cli.set_basic_auth("hello", "world");
  2567. auto res = cli.Get(path);
  2568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2569. auto body = remove_whitespace(res->body);
  2570. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2571. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2572. EXPECT_EQ(StatusCode::OK_200, res->status);
  2573. }
  2574. {
  2575. cli.set_basic_auth("hello", "bad");
  2576. auto res = cli.Get(path);
  2577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2578. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2579. }
  2580. {
  2581. cli.set_basic_auth("bad", "world");
  2582. auto res = cli.Get(path);
  2583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2584. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2585. }
  2586. }
  2587. #ifdef CPPHTTPLIB_SSL_ENABLED
  2588. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2589. auto host = "httpbingo.org";
  2590. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2591. auto paths = std::vector<std::string>{
  2592. "/digest-auth/auth/hello/world/MD5",
  2593. "/digest-auth/auth/hello/world/SHA-256",
  2594. };
  2595. auto port = 443;
  2596. SSLClient cli(host, port);
  2597. {
  2598. auto res = cli.Get(unauth_path);
  2599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2600. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2601. }
  2602. {
  2603. cli.set_digest_auth("hello", "world");
  2604. for (const auto &path : paths) {
  2605. auto res = cli.Get(path.c_str());
  2606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2607. auto body = remove_whitespace(res->body);
  2608. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2609. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2610. EXPECT_EQ(StatusCode::OK_200, res->status);
  2611. }
  2612. cli.set_digest_auth("hello", "bad");
  2613. for (const auto &path : paths) {
  2614. auto res = cli.Get(path.c_str());
  2615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2616. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2617. }
  2618. }
  2619. }
  2620. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2621. // comma-separated list of challenges, and each challenge may itself carry a
  2622. // comma-separated auth-param list, so a server can legally offer Basic
  2623. // before Digest, either as two field lines or packed into one. Runs one 401
  2624. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2625. // value() joins them in receipt order) and checks that the retry carries a
  2626. // well-formed Digest Authorization header naming expected_realm.
  2627. static void
  2628. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2629. const std::string &expected_realm) {
  2630. std::atomic<int> hits{0};
  2631. Server svr;
  2632. svr.Get("/x", [&](const Request &req, Response &res) {
  2633. if (++hits == 1) {
  2634. res.status = StatusCode::Unauthorized_401;
  2635. for (const auto &challenge : challenges) {
  2636. res.set_header("WWW-Authenticate", challenge);
  2637. }
  2638. } else {
  2639. auto authorization = req.get_header_value("Authorization");
  2640. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2641. EXPECT_NE(std::string::npos,
  2642. authorization.find("realm=\"" + expected_realm + "\""));
  2643. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2644. res.set_content("ok", "text/plain");
  2645. }
  2646. });
  2647. auto port = svr.bind_to_any_port(HOST);
  2648. std::thread t([&]() { svr.listen_after_bind(); });
  2649. auto se = detail::scope_exit([&] {
  2650. svr.stop();
  2651. t.join();
  2652. });
  2653. svr.wait_until_ready();
  2654. Client cli(HOST, port);
  2655. cli.set_digest_auth("hello", "world");
  2656. auto res = cli.Get("/x");
  2657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2658. EXPECT_EQ(2, hits.load());
  2659. }
  2660. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2661. static const char *kDigestChallenge =
  2662. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2663. "algorithm=MD5";
  2664. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2665. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2666. "testrealm");
  2667. }
  2668. // Same challenge list with the schemes in the opposite order, to make sure
  2669. // the fix above didn't just special-case "Basic first".
  2670. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2671. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2672. "testrealm");
  2673. }
  2674. // A comma inside a quoted auth-param value must not be mistaken for the
  2675. // separator between two challenges (or two auth-params).
  2676. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2677. run_digest_challenge_list_test(
  2678. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2679. "algorithm=MD5"},
  2680. "test,realm");
  2681. }
  2682. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2683. // make_digest_authentication_header() dereferences both unconditionally, so
  2684. // a server sending a challenge missing either one must not be treated as
  2685. // usable -- doing so used to crash the client with std::out_of_range.
  2686. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2687. Server svr;
  2688. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2689. res.status = StatusCode::Unauthorized_401;
  2690. res.set_header("WWW-Authenticate", challenge);
  2691. });
  2692. auto port = svr.bind_to_any_port(HOST);
  2693. std::thread t([&]() { svr.listen_after_bind(); });
  2694. auto se = detail::scope_exit([&] {
  2695. svr.stop();
  2696. t.join();
  2697. });
  2698. svr.wait_until_ready();
  2699. Client cli(HOST, port);
  2700. cli.set_digest_auth("hello", "world");
  2701. auto res = cli.Get("/x");
  2702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2703. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2704. }
  2705. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2706. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2707. }
  2708. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2709. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2710. }
  2711. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2712. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2713. }
  2714. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2715. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2716. // when storing the values, so the header builder has to re-escape them (and
  2717. // keep algorithm a bare token); otherwise the value breaks out of its
  2718. // quoted-string and injects extra auth-params into the client's Authorization.
  2719. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2720. std::atomic<int> hits{0};
  2721. std::string authorization;
  2722. Server svr;
  2723. svr.Get("/x", [&](const Request &req, Response &res) {
  2724. if (++hits == 1) {
  2725. res.status = StatusCode::Unauthorized_401;
  2726. // On the wire the quotes embedded in the values are backslash-escaped.
  2727. res.set_header("WWW-Authenticate",
  2728. "Digest realm=\"testrealm\", "
  2729. "nonce=\"n\\\"; injected=\\\"x\", "
  2730. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2731. } else {
  2732. authorization = req.get_header_value("Authorization");
  2733. res.set_content("ok", "text/plain");
  2734. }
  2735. });
  2736. auto port = svr.bind_to_any_port(HOST);
  2737. std::thread t([&]() { svr.listen_after_bind(); });
  2738. auto se = detail::scope_exit([&] {
  2739. svr.stop();
  2740. t.join();
  2741. });
  2742. svr.wait_until_ready();
  2743. Client cli(HOST, port);
  2744. cli.set_digest_auth("hello", "world");
  2745. auto res = cli.Get("/x");
  2746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2747. EXPECT_EQ(2, hits.load());
  2748. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2749. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  2750. // inside its quoted-string rather than starting an "injected" auth-param.
  2751. EXPECT_NE(std::string::npos,
  2752. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  2753. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  2754. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  2755. }
  2756. #endif
  2757. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2758. auto host = "google.com";
  2759. auto another_host = "example.com";
  2760. auto wrong_ip = "0.0.0.0";
  2761. #ifdef CPPHTTPLIB_SSL_ENABLED
  2762. SSLClient cli(host);
  2763. #else
  2764. Client cli(host);
  2765. #endif
  2766. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2767. auto res = cli.Get("/");
  2768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2769. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2770. }
  2771. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2772. auto host = "google.com";
  2773. auto wrong_ip = "0.0.0.0";
  2774. #ifdef CPPHTTPLIB_SSL_ENABLED
  2775. SSLClient cli(host);
  2776. #else
  2777. Client cli(host);
  2778. #endif
  2779. cli.set_hostname_addr_map({{host, wrong_ip}});
  2780. auto res = cli.Get("/");
  2781. ASSERT_TRUE(!res);
  2782. EXPECT_EQ(Error::Connection, res.error());
  2783. }
  2784. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2785. // A mapped value that is not an IP literal must be resolved. "localhost"
  2786. // resolves from the hosts file, so this test needs no external DNS.
  2787. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2788. auto host = "target.invalid";
  2789. Server svr;
  2790. std::string received_host;
  2791. svr.Get("/hi", [&](const Request &req, Response &res) {
  2792. received_host = req.get_header_value("Host");
  2793. res.set_content("Hello World!", "text/plain");
  2794. });
  2795. auto port = svr.bind_to_any_port(HOST);
  2796. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2797. auto se = detail::scope_exit([&] {
  2798. svr.stop();
  2799. thread.join();
  2800. ASSERT_FALSE(svr.is_running());
  2801. });
  2802. svr.wait_until_ready();
  2803. Client cli(host, port);
  2804. cli.set_hostname_addr_map({{host, HOST}});
  2805. auto res = cli.Get("/hi");
  2806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2807. EXPECT_EQ(StatusCode::OK_200, res->status);
  2808. // The mapping only redirects the connection; the identity stays host_.
  2809. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2810. }
  2811. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2812. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2813. auto host = "target.invalid";
  2814. Server svr;
  2815. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2816. res.set_content("Hello World!", "text/plain");
  2817. });
  2818. auto port = svr.bind_to_any_port("127.0.0.1");
  2819. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2820. auto se = detail::scope_exit([&] {
  2821. svr.stop();
  2822. thread.join();
  2823. ASSERT_FALSE(svr.is_running());
  2824. });
  2825. svr.wait_until_ready();
  2826. Client cli(host, port);
  2827. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2828. auto res = cli.Get("/hi");
  2829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2830. EXPECT_EQ(StatusCode::OK_200, res->status);
  2831. }
  2832. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2833. // An empty mapped value must leave host_ as the connection target. Without
  2834. // that guard the empty value would become the host argument, getaddrinfo
  2835. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2836. // loopback - silently connecting somewhere the caller never asked for.
  2837. // The server listens on loopback, so such a fallback would succeed and is
  2838. // therefore observable as a failure of this test.
  2839. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2840. Server svr;
  2841. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2842. res.set_content("Hello World!", "text/plain");
  2843. });
  2844. auto port = svr.bind_to_any_port(HOST);
  2845. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2846. auto se = detail::scope_exit([&] {
  2847. svr.stop();
  2848. thread.join();
  2849. ASSERT_FALSE(svr.is_running());
  2850. });
  2851. svr.wait_until_ready();
  2852. Client cli(blackhole, port);
  2853. cli.set_hostname_addr_map({{blackhole, ""}});
  2854. cli.set_connection_timeout(1);
  2855. auto res = cli.Get("/hi");
  2856. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2857. }
  2858. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2859. auto host = "httpbingo.org";
  2860. auto path = std::string{"/absolute-redirect/3"};
  2861. #ifdef CPPHTTPLIB_SSL_ENABLED
  2862. SSLClient cli(host);
  2863. #else
  2864. Client cli(host);
  2865. #endif
  2866. cli.set_follow_location(true);
  2867. auto res = cli.Get(path);
  2868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2869. EXPECT_EQ(StatusCode::OK_200, res->status);
  2870. }
  2871. TEST(RedirectTest, Redirect_Online) {
  2872. auto host = "httpbingo.org";
  2873. auto path = std::string{"/redirect/3"};
  2874. #ifdef CPPHTTPLIB_SSL_ENABLED
  2875. SSLClient cli(host);
  2876. #else
  2877. Client cli(host);
  2878. #endif
  2879. cli.set_follow_location(true);
  2880. auto res = cli.Get(path);
  2881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2882. EXPECT_EQ(StatusCode::OK_200, res->status);
  2883. }
  2884. TEST(RelativeRedirectTest, Redirect_Online) {
  2885. auto host = "httpbingo.org";
  2886. auto path = std::string{"/relative-redirect/3"};
  2887. #ifdef CPPHTTPLIB_SSL_ENABLED
  2888. SSLClient cli(host);
  2889. #else
  2890. Client cli(host);
  2891. #endif
  2892. cli.set_follow_location(true);
  2893. auto res = cli.Get(path);
  2894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2895. EXPECT_EQ(StatusCode::OK_200, res->status);
  2896. }
  2897. TEST(TooManyRedirectTest, Redirect_Online) {
  2898. auto host = "httpbingo.org";
  2899. auto path = std::string{"/redirect/21"};
  2900. #ifdef CPPHTTPLIB_SSL_ENABLED
  2901. SSLClient cli(host);
  2902. #else
  2903. Client cli(host);
  2904. #endif
  2905. cli.set_follow_location(true);
  2906. auto res = cli.Get(path);
  2907. ASSERT_TRUE(!res);
  2908. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2909. }
  2910. #ifdef CPPHTTPLIB_SSL_ENABLED
  2911. TEST(YahooRedirectTest, Redirect_Online) {
  2912. Client cli("yahoo.com");
  2913. auto res = cli.Get("/");
  2914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2915. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2916. cli.set_follow_location(true);
  2917. res = cli.Get("/");
  2918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2919. EXPECT_EQ(StatusCode::OK_200, res->status);
  2920. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2921. }
  2922. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2923. #define REDIR_HOST "httpbingo.org"
  2924. #define REDIR_PATH "/redirect-to"
  2925. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2926. SSLClient cli(REDIR_HOST);
  2927. cli.set_follow_location(true);
  2928. auto res =
  2929. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2931. EXPECT_EQ(StatusCode::OK_200, res->status);
  2932. }
  2933. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2934. SSLClient cli(REDIR_HOST);
  2935. cli.set_follow_location(true);
  2936. Params params;
  2937. params.emplace("url", "http://example.com");
  2938. params.emplace("status_code", "302");
  2939. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2941. EXPECT_EQ(StatusCode::OK_200, res->status);
  2942. }
  2943. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2944. SSLClient cli(REDIR_HOST);
  2945. cli.set_follow_location(true);
  2946. Params params;
  2947. params.emplace("url", "http://example.com");
  2948. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2950. EXPECT_EQ(StatusCode::OK_200, res->status);
  2951. }
  2952. TEST(UrlWithSpace, Redirect_Online) {
  2953. SSLClient cli("edge.forgecdn.net");
  2954. cli.set_follow_location(true);
  2955. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2957. EXPECT_EQ(StatusCode::OK_200, res->status);
  2958. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2959. }
  2960. #endif
  2961. #if !defined(_WIN32) && !defined(_WIN64)
  2962. TEST(ReceiveSignals, Signal) {
  2963. auto setupSignalHandlers = []() {
  2964. struct sigaction act;
  2965. sigemptyset(&act.sa_mask);
  2966. act.sa_flags = SA_SIGINFO;
  2967. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2968. switch (sig) {
  2969. case SIGINT:
  2970. default: break;
  2971. }
  2972. };
  2973. ::sigaction(SIGINT, &act, nullptr);
  2974. };
  2975. Server svr;
  2976. int port = 0;
  2977. auto thread = std::thread([&]() {
  2978. setupSignalHandlers();
  2979. port = svr.bind_to_any_port(HOST);
  2980. svr.listen_after_bind();
  2981. });
  2982. auto se = detail::scope_exit([&] {
  2983. svr.stop();
  2984. thread.join();
  2985. ASSERT_FALSE(svr.is_running());
  2986. });
  2987. svr.wait_until_ready();
  2988. ASSERT_TRUE(svr.is_running());
  2989. pthread_kill(thread.native_handle(), SIGINT);
  2990. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2991. ASSERT_TRUE(svr.is_running());
  2992. }
  2993. #endif
  2994. TEST(RedirectToDifferentPort, Redirect) {
  2995. Server svr1;
  2996. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2997. res.set_content("Hello World!", "text/plain");
  2998. });
  2999. int svr1_port = 0;
  3000. auto thread1 = std::thread([&]() {
  3001. svr1_port = svr1.bind_to_any_port(HOST);
  3002. svr1.listen_after_bind();
  3003. });
  3004. Server svr2;
  3005. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3006. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3007. });
  3008. int svr2_port = 0;
  3009. auto thread2 = std::thread([&]() {
  3010. svr2_port = svr2.bind_to_any_port(HOST);
  3011. svr2.listen_after_bind();
  3012. });
  3013. auto se = detail::scope_exit([&] {
  3014. svr2.stop();
  3015. thread2.join();
  3016. svr1.stop();
  3017. thread1.join();
  3018. ASSERT_FALSE(svr2.is_running());
  3019. ASSERT_FALSE(svr1.is_running());
  3020. });
  3021. svr1.wait_until_ready();
  3022. svr2.wait_until_ready();
  3023. Client cli("localhost", svr2_port);
  3024. cli.set_follow_location(true);
  3025. auto res = cli.Get("/2");
  3026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3027. EXPECT_EQ(StatusCode::OK_200, res->status);
  3028. EXPECT_EQ("Hello World!", res->body);
  3029. }
  3030. static void
  3031. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3032. Server svr1;
  3033. std::string captured_authorization;
  3034. svr1.Get("/target", [&](const Request &req, Response &res) {
  3035. captured_authorization = req.get_header_value("Authorization");
  3036. res.set_content("OK", "text/plain");
  3037. });
  3038. int svr1_port = 0;
  3039. auto thread1 = std::thread([&]() {
  3040. svr1_port = svr1.bind_to_any_port(HOST);
  3041. svr1.listen_after_bind();
  3042. });
  3043. Server svr2;
  3044. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3045. res.set_redirect(
  3046. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3047. });
  3048. int svr2_port = 0;
  3049. auto thread2 = std::thread([&]() {
  3050. svr2_port = svr2.bind_to_any_port(HOST);
  3051. svr2.listen_after_bind();
  3052. });
  3053. auto se = detail::scope_exit([&] {
  3054. svr2.stop();
  3055. thread2.join();
  3056. svr1.stop();
  3057. thread1.join();
  3058. ASSERT_FALSE(svr2.is_running());
  3059. ASSERT_FALSE(svr1.is_running());
  3060. });
  3061. svr1.wait_until_ready();
  3062. svr2.wait_until_ready();
  3063. Client cli("localhost", svr2_port);
  3064. cli.set_follow_location(true);
  3065. set_auth(cli);
  3066. auto res = cli.Get("/redir");
  3067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3068. EXPECT_EQ(StatusCode::OK_200, res->status);
  3069. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3070. EXPECT_TRUE(captured_authorization.empty());
  3071. }
  3072. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3073. TestDoNotForwardCredentialsOnRedirect(
  3074. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3075. }
  3076. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3077. TestDoNotForwardCredentialsOnRedirect(
  3078. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3079. }
  3080. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3081. Server svr1;
  3082. std::string captured_cookie;
  3083. bool target_hit = false;
  3084. svr1.Get("/target", [&](const Request &req, Response &res) {
  3085. captured_cookie = req.get_header_value("Cookie");
  3086. target_hit = true;
  3087. res.set_content("OK", "text/plain");
  3088. });
  3089. int svr1_port = 0;
  3090. auto thread1 = std::thread([&]() {
  3091. svr1_port = svr1.bind_to_any_port(HOST);
  3092. svr1.listen_after_bind();
  3093. });
  3094. Server svr2;
  3095. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3096. res.set_redirect(
  3097. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3098. });
  3099. int svr2_port = 0;
  3100. auto thread2 = std::thread([&]() {
  3101. svr2_port = svr2.bind_to_any_port(HOST);
  3102. svr2.listen_after_bind();
  3103. });
  3104. auto se = detail::scope_exit([&] {
  3105. svr2.stop();
  3106. thread2.join();
  3107. svr1.stop();
  3108. thread1.join();
  3109. ASSERT_FALSE(svr2.is_running());
  3110. ASSERT_FALSE(svr1.is_running());
  3111. });
  3112. svr1.wait_until_ready();
  3113. svr2.wait_until_ready();
  3114. Client cli("localhost", svr2_port);
  3115. cli.set_follow_location(true);
  3116. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  3117. auto res = cli.Get("/redir", headers);
  3118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3119. EXPECT_EQ(StatusCode::OK_200, res->status);
  3120. EXPECT_TRUE(target_hit);
  3121. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3122. EXPECT_TRUE(captured_cookie.empty());
  3123. }
  3124. TEST(RedirectToSamePort, ForwardCookie) {
  3125. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3126. // header so that ordinary session flows keep working.
  3127. Server svr;
  3128. std::string captured_cookie;
  3129. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3130. res.set_redirect("/target", 302);
  3131. });
  3132. svr.Get("/target", [&](const Request &req, Response &res) {
  3133. captured_cookie = req.get_header_value("Cookie");
  3134. res.set_content("OK", "text/plain");
  3135. });
  3136. auto port = svr.bind_to_any_port(HOST);
  3137. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3138. auto se = detail::scope_exit([&] {
  3139. svr.stop();
  3140. thread.join();
  3141. ASSERT_FALSE(svr.is_running());
  3142. });
  3143. svr.wait_until_ready();
  3144. Client cli(HOST, port);
  3145. cli.set_follow_location(true);
  3146. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3147. auto res = cli.Get("/redir", headers);
  3148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3149. EXPECT_EQ(StatusCode::OK_200, res->status);
  3150. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3151. }
  3152. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3153. Server svr;
  3154. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3155. // Port number that overflows int — should not crash
  3156. res.set_redirect("http://localhost:99999999999999999999/target");
  3157. });
  3158. auto port = svr.bind_to_any_port(HOST);
  3159. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3160. auto se = detail::scope_exit([&] {
  3161. svr.stop();
  3162. thread.join();
  3163. ASSERT_FALSE(svr.is_running());
  3164. });
  3165. svr.wait_until_ready();
  3166. Client cli(HOST, port);
  3167. cli.set_follow_location(true);
  3168. auto res = cli.Get("/redir");
  3169. // Should fail gracefully, not crash (no valid response due to bad port)
  3170. EXPECT_FALSE(res);
  3171. }
  3172. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3173. Server svr;
  3174. auto port = svr.bind_to_any_port(HOST);
  3175. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3176. // The server's own port followed by junk must not be followed
  3177. res.set_redirect("http://" + std::string(HOST) + ":" +
  3178. std::to_string(port) + "junk/target");
  3179. });
  3180. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3181. res.set_content("target", "text/plain");
  3182. });
  3183. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3184. auto se = detail::scope_exit([&] {
  3185. svr.stop();
  3186. thread.join();
  3187. ASSERT_FALSE(svr.is_running());
  3188. });
  3189. svr.wait_until_ready();
  3190. Client cli(HOST, port);
  3191. cli.set_follow_location(true);
  3192. auto res = cli.Get("/redir");
  3193. EXPECT_FALSE(res);
  3194. }
  3195. TEST(RedirectFromPageWithContent, Redirect) {
  3196. Server svr;
  3197. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3198. res.set_content("___", "text/plain");
  3199. res.set_redirect("/2");
  3200. });
  3201. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3202. res.set_content("Hello World!", "text/plain");
  3203. });
  3204. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3205. auto se = detail::scope_exit([&] {
  3206. svr.stop();
  3207. th.join();
  3208. ASSERT_FALSE(svr.is_running());
  3209. });
  3210. svr.wait_until_ready();
  3211. {
  3212. Client cli("localhost", PORT);
  3213. cli.set_follow_location(true);
  3214. std::string body;
  3215. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3216. body.append(data, data_length);
  3217. return true;
  3218. });
  3219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3220. EXPECT_EQ(StatusCode::OK_200, res->status);
  3221. EXPECT_EQ("Hello World!", body);
  3222. }
  3223. {
  3224. Client cli("localhost", PORT);
  3225. std::string body;
  3226. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3227. body.append(data, data_length);
  3228. return true;
  3229. });
  3230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3231. EXPECT_EQ(StatusCode::Found_302, res->status);
  3232. EXPECT_EQ("___", body);
  3233. }
  3234. }
  3235. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3236. Server svr;
  3237. auto port_str = std::to_string(PORT);
  3238. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3239. auto expected_host = "[::1]:" + port_str;
  3240. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3241. res.set_content("___", "text/plain");
  3242. // res.set_redirect("/2");
  3243. res.set_redirect(redirect_url);
  3244. });
  3245. svr.Get("/2", [&](const Request &req, Response &res) {
  3246. auto host_header = req.headers.find("Host");
  3247. ASSERT_TRUE(host_header != req.headers.end());
  3248. EXPECT_EQ(expected_host, host_header->second);
  3249. res.set_content("Hello World!", "text/plain");
  3250. });
  3251. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3252. auto se = detail::scope_exit([&] {
  3253. svr.stop();
  3254. th.join();
  3255. ASSERT_FALSE(svr.is_running());
  3256. });
  3257. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3258. // actually starts anything, so the condition !svr.is_running() will
  3259. // always remain true, and the loop never stops.
  3260. // This basically counts how many milliseconds have passed since the
  3261. // call to svr.listen(), and if after 5 seconds nothing started yet
  3262. // aborts the test.
  3263. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3264. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3265. ASSERT_LT(milliseconds, 5000U);
  3266. }
  3267. {
  3268. Client cli("::1", PORT);
  3269. cli.set_follow_location(true);
  3270. std::string body;
  3271. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3272. body.append(data, data_length);
  3273. return true;
  3274. });
  3275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3276. EXPECT_EQ(StatusCode::OK_200, res->status);
  3277. EXPECT_EQ("Hello World!", body);
  3278. }
  3279. {
  3280. Client cli("::1", PORT);
  3281. std::string body;
  3282. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3283. body.append(data, data_length);
  3284. return true;
  3285. });
  3286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3287. EXPECT_EQ(StatusCode::Found_302, res->status);
  3288. EXPECT_EQ("___", body);
  3289. }
  3290. }
  3291. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3292. Server svr;
  3293. svr.Get("/foo", [](const Request &req, Response &res) {
  3294. auto a = req.params.find("a");
  3295. if (a != req.params.end()) {
  3296. res.set_content((*a).second, "text/plain");
  3297. res.status = StatusCode::OK_200;
  3298. } else {
  3299. res.status = StatusCode::BadRequest_400;
  3300. }
  3301. });
  3302. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3303. auto se = detail::scope_exit([&] {
  3304. svr.stop();
  3305. thread.join();
  3306. ASSERT_FALSE(svr.is_running());
  3307. });
  3308. svr.wait_until_ready();
  3309. {
  3310. Client cli(HOST, PORT);
  3311. cli.set_path_encode(false);
  3312. auto res = cli.Get("/foo?a=explicitly+encoded");
  3313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3314. EXPECT_EQ(StatusCode::OK_200, res->status);
  3315. // This expects it back with a space, as the `+` won't have been
  3316. // url-encoded, and server-side the params get decoded turning `+`
  3317. // into spaces.
  3318. EXPECT_EQ("explicitly encoded", res->body);
  3319. }
  3320. }
  3321. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3322. // When path encoding is disabled the client must transmit the supplied
  3323. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3324. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3325. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3326. // than a space (0x20). Assert on the raw wire target to catch this.
  3327. Server svr;
  3328. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3329. svr.Get("/foo", [&](const Request &req, Response &res) {
  3330. EXPECT_EQ(expected_target, req.target);
  3331. res.status = StatusCode::OK_200;
  3332. });
  3333. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3334. auto se = detail::scope_exit([&] {
  3335. svr.stop();
  3336. thread.join();
  3337. ASSERT_FALSE(svr.is_running());
  3338. });
  3339. svr.wait_until_ready();
  3340. {
  3341. Client cli(HOST, PORT);
  3342. cli.set_path_encode(false);
  3343. auto res = cli.Get(expected_target.c_str());
  3344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3345. EXPECT_EQ(StatusCode::OK_200, res->status);
  3346. }
  3347. }
  3348. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3349. // `open_stream()` used to skip the path encoding that the buffered send
  3350. // path applies, so the same `path` produced different bytes in the request
  3351. // line depending on which API was used. Assert the two agree.
  3352. Server svr;
  3353. std::string target;
  3354. svr.Get(".*", [&](const Request &req, Response &res) {
  3355. target = req.target;
  3356. res.status = StatusCode::OK_200;
  3357. });
  3358. auto port = svr.bind_to_any_port(HOST);
  3359. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3360. auto se = detail::scope_exit([&] {
  3361. svr.stop();
  3362. thread.join();
  3363. ASSERT_FALSE(svr.is_running());
  3364. });
  3365. svr.wait_until_ready();
  3366. struct {
  3367. const char *path;
  3368. const char *expected;
  3369. } cases[] = {
  3370. {"/a b?x=1", "/a%20b?x=1"},
  3371. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3372. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3373. };
  3374. for (const auto &c : cases) {
  3375. Client cli(HOST, port);
  3376. target.clear();
  3377. auto res = cli.Get(c.path);
  3378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3379. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3380. auto buffered_target = target;
  3381. target.clear();
  3382. auto handle = cli.open_stream("GET", c.path);
  3383. EXPECT_TRUE(handle.is_valid())
  3384. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3385. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3386. }
  3387. }
  3388. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3389. // The `set_path_encode(false)` contract — transmit the supplied target
  3390. // verbatim — must hold for the streaming API too.
  3391. Server svr;
  3392. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3393. std::string target;
  3394. svr.Get("/foo", [&](const Request &req, Response &res) {
  3395. target = req.target;
  3396. res.status = StatusCode::OK_200;
  3397. });
  3398. auto port = svr.bind_to_any_port(HOST);
  3399. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3400. auto se = detail::scope_exit([&] {
  3401. svr.stop();
  3402. thread.join();
  3403. ASSERT_FALSE(svr.is_running());
  3404. });
  3405. svr.wait_until_ready();
  3406. {
  3407. Client cli(HOST, port);
  3408. cli.set_path_encode(false);
  3409. auto handle = cli.open_stream("GET", expected_target);
  3410. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3411. EXPECT_EQ(expected_target, target);
  3412. }
  3413. }
  3414. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3415. // With path encoding enabled a CR/LF in the target is percent-encoded
  3416. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3417. // write_request_line still backstops `set_path_encode(false)`, which is
  3418. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3419. Server svr;
  3420. // Captured before routing: the decoded path contains a newline, which a
  3421. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3422. std::string target;
  3423. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3424. target = req.target;
  3425. res.status = StatusCode::OK_200;
  3426. return Server::HandlerResponse::Handled;
  3427. });
  3428. auto port = svr.bind_to_any_port(HOST);
  3429. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3430. auto se = detail::scope_exit([&] {
  3431. svr.stop();
  3432. thread.join();
  3433. ASSERT_FALSE(svr.is_running());
  3434. });
  3435. svr.wait_until_ready();
  3436. {
  3437. Client cli(HOST, port);
  3438. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3439. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3440. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3441. }
  3442. }
  3443. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3444. // Every control character is percent-encoded, not just CR/LF, so the target
  3445. // passes the request-target check in write_request_line.
  3446. Server svr;
  3447. std::string target;
  3448. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3449. target = req.target;
  3450. res.status = StatusCode::OK_200;
  3451. return Server::HandlerResponse::Handled;
  3452. });
  3453. auto port = svr.bind_to_any_port(HOST);
  3454. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3455. auto se = detail::scope_exit([&] {
  3456. svr.stop();
  3457. thread.join();
  3458. ASSERT_FALSE(svr.is_running());
  3459. });
  3460. svr.wait_until_ready();
  3461. {
  3462. Client cli(HOST, port);
  3463. auto res = cli.Get("/a\tb\x1b\x7f");
  3464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3465. EXPECT_EQ("/a%09b%1B%7F", target);
  3466. }
  3467. }
  3468. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3469. // Nothing may reach the wire: a raw CR/LF target would split the request
  3470. // line and inject headers.
  3471. Server svr;
  3472. // Pre-routing so that "not called" means nothing reached the server at all,
  3473. // rather than merely failing to match a handler pattern.
  3474. auto handler_called = false;
  3475. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3476. handler_called = true;
  3477. res.status = StatusCode::OK_200;
  3478. return Server::HandlerResponse::Handled;
  3479. });
  3480. auto port = svr.bind_to_any_port(HOST);
  3481. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3482. auto se = detail::scope_exit([&] {
  3483. svr.stop();
  3484. thread.join();
  3485. ASSERT_FALSE(svr.is_running());
  3486. });
  3487. svr.wait_until_ready();
  3488. {
  3489. Client cli(HOST, port);
  3490. cli.set_path_encode(false);
  3491. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3492. EXPECT_FALSE(handle.is_valid());
  3493. EXPECT_EQ(Error::Write, handle.error);
  3494. EXPECT_FALSE(handler_called);
  3495. }
  3496. }
  3497. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3498. // Which of the two branches runs is decided by whether the query component
  3499. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3500. // an empty query and must still fall back to building one from
  3501. // `req.params`, while a non-empty query must win over `req.params`.
  3502. Server svr;
  3503. std::string target;
  3504. svr.Get("/foo", [&](const Request &req, Response &res) {
  3505. target = req.target;
  3506. res.status = StatusCode::OK_200;
  3507. });
  3508. auto port = svr.bind_to_any_port(HOST);
  3509. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3510. auto se = detail::scope_exit([&] {
  3511. svr.stop();
  3512. thread.join();
  3513. ASSERT_FALSE(svr.is_running());
  3514. });
  3515. svr.wait_until_ready();
  3516. {
  3517. // Trailing `?` -> empty query component -> `req.params` is used.
  3518. Client cli(HOST, port);
  3519. Request req;
  3520. req.method = "GET";
  3521. req.path = "/foo?";
  3522. req.params.emplace("a", "1");
  3523. target.clear();
  3524. auto res = cli.send(req);
  3525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3526. EXPECT_EQ("/foo?a=1", target);
  3527. }
  3528. {
  3529. // Non-empty query in `req.path` -> `req.params` is not appended.
  3530. Client cli(HOST, port);
  3531. Request req;
  3532. req.method = "GET";
  3533. req.path = "/foo?b=2";
  3534. req.params.emplace("a", "1");
  3535. target.clear();
  3536. auto res = cli.send(req);
  3537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3538. EXPECT_EQ("/foo?b=2", target);
  3539. }
  3540. }
  3541. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3542. Server svr;
  3543. svr.Get("/", [](const Request &req, Response &) {
  3544. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3545. });
  3546. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3547. auto se = detail::scope_exit([&] {
  3548. svr.stop();
  3549. thread.join();
  3550. ASSERT_FALSE(svr.is_running());
  3551. });
  3552. svr.wait_until_ready();
  3553. {
  3554. Client cli(HOST, PORT);
  3555. cli.set_path_encode(false);
  3556. auto res = cli.Get("/?something=%0A");
  3557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3558. EXPECT_EQ(StatusCode::OK_200, res->status);
  3559. }
  3560. }
  3561. TEST(BindServerTest, BindDualStack) {
  3562. Server svr;
  3563. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3564. res.set_content("Hello World!", "text/plain");
  3565. });
  3566. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3567. auto se = detail::scope_exit([&] {
  3568. svr.stop();
  3569. thread.join();
  3570. ASSERT_FALSE(svr.is_running());
  3571. });
  3572. svr.wait_until_ready();
  3573. {
  3574. Client cli("127.0.0.1", PORT);
  3575. auto res = cli.Get("/1");
  3576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3577. EXPECT_EQ(StatusCode::OK_200, res->status);
  3578. EXPECT_EQ("Hello World!", res->body);
  3579. }
  3580. {
  3581. Client cli("::1", PORT);
  3582. auto res = cli.Get("/1");
  3583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3584. EXPECT_EQ(StatusCode::OK_200, res->status);
  3585. EXPECT_EQ("Hello World!", res->body);
  3586. }
  3587. }
  3588. TEST(BindServerTest, BindAndListenSeparately) {
  3589. Server svr;
  3590. int port = svr.bind_to_any_port("0.0.0.0");
  3591. ASSERT_TRUE(svr.is_valid());
  3592. ASSERT_TRUE(port > 0);
  3593. svr.stop();
  3594. }
  3595. // Reports whether anything is still listening on a loopback port. A plain
  3596. // connect() is used instead of a Client request because a socket left bound by
  3597. // mistake accepts the connection into its backlog and never answers, which
  3598. // would hang the test instead of failing it.
  3599. static bool is_loopback_port_accepting(int port) {
  3600. sockaddr_in addr{};
  3601. addr.sin_family = AF_INET;
  3602. addr.sin_port = htons(static_cast<uint16_t>(port));
  3603. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3604. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3605. EXPECT_NE(sock, INVALID_SOCKET);
  3606. if (sock == INVALID_SOCKET) { return false; }
  3607. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3608. static_cast<socklen_t>(sizeof(addr)));
  3609. detail::close_socket(sock);
  3610. return ret == 0;
  3611. }
  3612. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3613. Server svr;
  3614. auto port = svr.bind_to_any_port("127.0.0.1");
  3615. ASSERT_TRUE(port > 0);
  3616. svr.stop();
  3617. // bind_to_any_port() already called listen(2), so until stop() closed the
  3618. // descriptor the port kept accepting connections into the backlog. ASSERT
  3619. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3620. // below blocks forever in the accept loop.
  3621. ASSERT_FALSE(is_loopback_port_accepting(port));
  3622. // Nothing is left to accept on, so listen_after_bind() must report failure
  3623. // instead of returning success without ever serving.
  3624. EXPECT_FALSE(svr.listen_after_bind());
  3625. // The failed listen marks the server decommissioned, so a waiter returns
  3626. // instead of spinning forever.
  3627. svr.wait_until_ready();
  3628. }
  3629. #ifdef CPPHTTPLIB_SSL_ENABLED
  3630. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3631. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3632. CLIENT_CA_CERT_DIR);
  3633. int port = svr.bind_to_any_port("0.0.0.0");
  3634. ASSERT_TRUE(svr.is_valid());
  3635. ASSERT_TRUE(port > 0);
  3636. svr.stop();
  3637. }
  3638. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3639. // or a rejected CustomRoute() registration would not stop the server binding.
  3640. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3641. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3642. CLIENT_CA_CERT_DIR);
  3643. ASSERT_TRUE(svr.is_valid());
  3644. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3645. EXPECT_FALSE(svr.is_valid());
  3646. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3647. }
  3648. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3649. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3650. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3651. int port = svr.bind_to_any_port("0.0.0.0");
  3652. ASSERT_TRUE(svr.is_valid());
  3653. ASSERT_TRUE(port > 0);
  3654. svr.stop();
  3655. }
  3656. TEST(BindServerTest, UpdateCertsPem) {
  3657. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3658. int port = svr.bind_to_any_port("0.0.0.0");
  3659. ASSERT_TRUE(svr.is_valid());
  3660. ASSERT_TRUE(port > 0);
  3661. // Read PEM files
  3662. std::string cert_pem, key_pem, ca_pem;
  3663. read_file(SERVER_CERT_FILE, cert_pem);
  3664. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3665. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3666. // Update server certificates using PEM API
  3667. ASSERT_TRUE(
  3668. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3669. ASSERT_TRUE(svr.is_valid());
  3670. svr.stop();
  3671. }
  3672. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3673. // Start server with client CA (enables client auth)
  3674. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3675. ASSERT_TRUE(svr.is_valid());
  3676. bool handler_called = false;
  3677. svr.Get("/test", [&](const Request &req, Response &res) {
  3678. handler_called = true;
  3679. // Verify client certificate is present
  3680. auto cert = req.peer_cert();
  3681. EXPECT_TRUE(static_cast<bool>(cert));
  3682. res.set_content("ok", "text/plain");
  3683. });
  3684. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3685. auto se = detail::scope_exit([&] {
  3686. svr.stop();
  3687. t.join();
  3688. ASSERT_FALSE(svr.is_running());
  3689. });
  3690. svr.wait_until_ready();
  3691. // Read PEM files
  3692. std::string cert_pem, key_pem, ca_pem;
  3693. read_file(SERVER_CERT_FILE, cert_pem);
  3694. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3695. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3696. // Update server certificates and client CA using PEM API while server running
  3697. ASSERT_TRUE(
  3698. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3699. // Connect with client certificate
  3700. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3701. cli.enable_server_certificate_verification(false);
  3702. cli.set_connection_timeout(30);
  3703. auto res = cli.Get("/test");
  3704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3705. ASSERT_EQ(StatusCode::OK_200, res->status);
  3706. ASSERT_TRUE(handler_called);
  3707. EXPECT_EQ("ok", res->body);
  3708. }
  3709. #endif
  3710. TEST(ErrorHandlerTest, ContentLength) {
  3711. Server svr;
  3712. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3713. res.status = StatusCode::OK_200;
  3714. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3715. "text/html"); // <= Content-Length still 13
  3716. });
  3717. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3718. res.set_content("Hello World!\n", "text/plain");
  3719. res.status = 524;
  3720. });
  3721. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3722. auto se = detail::scope_exit([&] {
  3723. svr.stop();
  3724. thread.join();
  3725. ASSERT_FALSE(svr.is_running());
  3726. });
  3727. svr.wait_until_ready();
  3728. {
  3729. Client cli(HOST, PORT);
  3730. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3732. EXPECT_EQ(StatusCode::OK_200, res->status);
  3733. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3734. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3735. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3736. }
  3737. }
  3738. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3739. TEST(ExceptionTest, WithoutExceptionHandler) {
  3740. Server svr;
  3741. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3742. throw std::runtime_error("exception...");
  3743. });
  3744. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3745. throw std::runtime_error("exception\r\n...");
  3746. });
  3747. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3748. auto se = detail::scope_exit([&] {
  3749. svr.stop();
  3750. listen_thread.join();
  3751. ASSERT_FALSE(svr.is_running());
  3752. });
  3753. svr.wait_until_ready();
  3754. Client cli("localhost", PORT);
  3755. {
  3756. auto res = cli.Get("/exception");
  3757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3758. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3759. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3760. }
  3761. {
  3762. auto res = cli.Get("/unknown");
  3763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3764. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3765. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3766. }
  3767. }
  3768. TEST(ExceptionTest, WithExceptionHandler) {
  3769. Server svr;
  3770. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3771. std::exception_ptr ep) {
  3772. EXPECT_FALSE(ep == nullptr);
  3773. try {
  3774. std::rethrow_exception(ep);
  3775. } catch (std::exception &e) {
  3776. EXPECT_EQ("abc", std::string(e.what()));
  3777. } catch (...) {}
  3778. res.status = StatusCode::InternalServerError_500;
  3779. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3780. "text/html"); // <= Content-Length still 13 at this point
  3781. });
  3782. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3783. res.set_content("Hello World!\n", "text/plain");
  3784. throw std::runtime_error("abc");
  3785. });
  3786. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3787. auto se = detail::scope_exit([&] {
  3788. svr.stop();
  3789. thread.join();
  3790. ASSERT_FALSE(svr.is_running());
  3791. });
  3792. svr.wait_until_ready();
  3793. for (size_t i = 0; i < 10; i++) {
  3794. Client cli(HOST, PORT);
  3795. for (size_t j = 0; j < 100; j++) {
  3796. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3798. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3799. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3800. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3801. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3802. }
  3803. cli.set_keep_alive(true);
  3804. for (size_t j = 0; j < 100; j++) {
  3805. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3807. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3808. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3809. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3810. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3811. }
  3812. }
  3813. }
  3814. TEST(ExceptionTest, AndErrorHandler) {
  3815. Server svr;
  3816. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3817. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3818. });
  3819. svr.set_exception_handler(
  3820. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3821. EXPECT_FALSE(ep == nullptr);
  3822. try {
  3823. std::rethrow_exception(ep);
  3824. } catch (std::exception &e) {
  3825. res.set_content(e.what(), "text/html");
  3826. } catch (...) {}
  3827. res.status = StatusCode::InternalServerError_500;
  3828. });
  3829. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3830. throw std::runtime_error("EXCEPTION");
  3831. });
  3832. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3833. res.set_content("ERROR", "text/html");
  3834. res.status = StatusCode::InternalServerError_500;
  3835. });
  3836. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3837. auto se = detail::scope_exit([&] {
  3838. svr.stop();
  3839. thread.join();
  3840. ASSERT_FALSE(svr.is_running());
  3841. });
  3842. svr.wait_until_ready();
  3843. Client cli(HOST, PORT);
  3844. {
  3845. auto res = cli.Get("/exception");
  3846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3847. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3848. EXPECT_EQ("EXCEPTION", res->body);
  3849. }
  3850. {
  3851. auto res = cli.Get("/error");
  3852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3853. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3854. EXPECT_EQ("ERROR", res->body);
  3855. }
  3856. {
  3857. auto res = cli.Get("/invalid");
  3858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3859. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3860. EXPECT_EQ("NOT_FOUND", res->body);
  3861. }
  3862. }
  3863. #endif
  3864. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3865. // process_request() wraps only routing() in a try/catch, so an exception from
  3866. // any other user callback used to unwind into the task queue - which does not
  3867. // catch - and terminate the process. Each test below runs the server on a
  3868. // single worker thread: a guard that catches the exception but still loses the
  3869. // thread would otherwise be hidden by a spare worker serving the follow-up
  3870. // request. Note that a regression here aborts the whole test binary rather
  3871. // than failing one test.
  3872. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3873. Server svr;
  3874. svr.new_task_queue = [] { return new ThreadPool(1); };
  3875. std::atomic<int> reported{0};
  3876. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3877. if (err == Error::UserCallbackException) { reported++; }
  3878. });
  3879. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3880. res.set_content_provider(
  3881. 1024, "text/plain",
  3882. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3883. sink.write("hello", 5);
  3884. throw std::runtime_error("from the content provider");
  3885. });
  3886. });
  3887. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3888. res.set_content("ok", "text/plain");
  3889. });
  3890. auto port = svr.bind_to_any_port(HOST);
  3891. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3892. auto se = detail::scope_exit([&] {
  3893. svr.stop();
  3894. listen_thread.join();
  3895. ASSERT_FALSE(svr.is_running());
  3896. });
  3897. svr.wait_until_ready();
  3898. {
  3899. Client cli(HOST, port);
  3900. cli.set_read_timeout(5, 0);
  3901. EXPECT_FALSE(cli.Get("/throw"));
  3902. }
  3903. EXPECT_TRUE(svr.is_running());
  3904. EXPECT_EQ(1, reported.load());
  3905. // A request on a fresh connection is still served.
  3906. {
  3907. Client cli(HOST, port);
  3908. auto res = cli.Get("/ok");
  3909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3910. EXPECT_EQ(StatusCode::OK_200, res->status);
  3911. EXPECT_EQ("ok", res->body);
  3912. }
  3913. }
  3914. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3915. Server svr;
  3916. svr.new_task_queue = [] { return new ThreadPool(1); };
  3917. std::atomic<bool> should_throw{true};
  3918. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3919. res.set_content("hi", "text/plain");
  3920. });
  3921. svr.set_post_routing_handler(
  3922. [&](const Request & /*req*/, Response & /*res*/) {
  3923. if (should_throw) {
  3924. throw std::runtime_error("from the post-routing handler");
  3925. }
  3926. });
  3927. auto port = svr.bind_to_any_port(HOST);
  3928. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3929. auto se = detail::scope_exit([&] {
  3930. svr.stop();
  3931. listen_thread.join();
  3932. ASSERT_FALSE(svr.is_running());
  3933. });
  3934. svr.wait_until_ready();
  3935. {
  3936. Client cli(HOST, port);
  3937. cli.set_read_timeout(5, 0);
  3938. EXPECT_FALSE(cli.Get("/hi"));
  3939. }
  3940. EXPECT_TRUE(svr.is_running());
  3941. should_throw = false;
  3942. {
  3943. Client cli(HOST, port);
  3944. auto res = cli.Get("/hi");
  3945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3946. EXPECT_EQ(StatusCode::OK_200, res->status);
  3947. EXPECT_EQ("hi", res->body);
  3948. }
  3949. }
  3950. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  3951. // The guard reports the caught exception through the error logger, which is
  3952. // a user callback too. A logger that throws has to be contained as well, or
  3953. // the process would terminate from inside the catch.
  3954. Server svr;
  3955. svr.new_task_queue = [] { return new ThreadPool(1); };
  3956. std::atomic<int> reported{0};
  3957. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3958. if (err == Error::UserCallbackException) {
  3959. reported++;
  3960. throw std::runtime_error("from the error logger");
  3961. }
  3962. });
  3963. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3964. res.set_content_provider(
  3965. 1024, "text/plain",
  3966. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3967. sink.write("hello", 5);
  3968. throw std::runtime_error("from the content provider");
  3969. });
  3970. });
  3971. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3972. res.set_content("ok", "text/plain");
  3973. });
  3974. auto port = svr.bind_to_any_port(HOST);
  3975. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3976. auto se = detail::scope_exit([&] {
  3977. svr.stop();
  3978. listen_thread.join();
  3979. ASSERT_FALSE(svr.is_running());
  3980. });
  3981. svr.wait_until_ready();
  3982. {
  3983. Client cli(HOST, port);
  3984. cli.set_read_timeout(5, 0);
  3985. EXPECT_FALSE(cli.Get("/throw"));
  3986. }
  3987. EXPECT_TRUE(svr.is_running());
  3988. EXPECT_EQ(1, reported.load());
  3989. {
  3990. Client cli(HOST, port);
  3991. auto res = cli.Get("/ok");
  3992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3993. EXPECT_EQ(StatusCode::OK_200, res->status);
  3994. EXPECT_EQ("ok", res->body);
  3995. }
  3996. }
  3997. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  3998. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  3999. // so the exception unwinds through the ws::WebSocket object on its way to
  4000. // the guard. None of the HTTP cases above cross that.
  4001. Server svr;
  4002. svr.new_task_queue = [] { return new ThreadPool(1); };
  4003. std::atomic<int> reported{0};
  4004. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4005. if (err == Error::UserCallbackException) { reported++; }
  4006. });
  4007. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4008. throw std::runtime_error("from the WebSocket handler");
  4009. });
  4010. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4011. res.set_content("ok", "text/plain");
  4012. });
  4013. auto port = svr.bind_to_any_port(HOST);
  4014. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4015. auto se = detail::scope_exit([&] {
  4016. svr.stop();
  4017. listen_thread.join();
  4018. ASSERT_FALSE(svr.is_running());
  4019. });
  4020. svr.wait_until_ready();
  4021. {
  4022. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4023. "/ws");
  4024. auto res = client.connect();
  4025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4026. // The server dropped the connection instead of dying.
  4027. std::string msg;
  4028. EXPECT_FALSE(client.read(msg));
  4029. client.close();
  4030. }
  4031. EXPECT_TRUE(svr.is_running());
  4032. EXPECT_EQ(1, reported.load());
  4033. {
  4034. Client cli(HOST, port);
  4035. auto res = cli.Get("/ok");
  4036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4037. EXPECT_EQ(StatusCode::OK_200, res->status);
  4038. EXPECT_EQ("ok", res->body);
  4039. }
  4040. }
  4041. #ifdef CPPHTTPLIB_SSL_ENABLED
  4042. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4043. // SSLServer::process_and_close_socket() is a separate overload with its own
  4044. // guard, so it is exercised on its own.
  4045. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4046. ASSERT_TRUE(svr.is_valid());
  4047. svr.new_task_queue = [] { return new ThreadPool(1); };
  4048. std::atomic<int> reported{0};
  4049. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4050. if (err == Error::UserCallbackException) { reported++; }
  4051. });
  4052. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4053. res.set_content_provider(
  4054. 1024, "text/plain",
  4055. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4056. sink.write("hello", 5);
  4057. throw std::runtime_error("from the content provider");
  4058. });
  4059. });
  4060. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4061. res.set_content("ok", "text/plain");
  4062. });
  4063. auto port = svr.bind_to_any_port(HOST);
  4064. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4065. auto se = detail::scope_exit([&] {
  4066. svr.stop();
  4067. listen_thread.join();
  4068. ASSERT_FALSE(svr.is_running());
  4069. });
  4070. svr.wait_until_ready();
  4071. {
  4072. SSLClient cli(HOST, port);
  4073. cli.enable_server_certificate_verification(false);
  4074. cli.set_read_timeout(5, 0);
  4075. EXPECT_FALSE(cli.Get("/throw"));
  4076. }
  4077. EXPECT_TRUE(svr.is_running());
  4078. EXPECT_EQ(1, reported.load());
  4079. {
  4080. SSLClient cli(HOST, port);
  4081. cli.enable_server_certificate_verification(false);
  4082. auto res = cli.Get("/ok");
  4083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4084. EXPECT_EQ(StatusCode::OK_200, res->status);
  4085. EXPECT_EQ("ok", res->body);
  4086. }
  4087. }
  4088. #endif
  4089. #endif
  4090. TEST(NoContentTest, ContentLength) {
  4091. Server svr;
  4092. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4093. res.status = StatusCode::NoContent_204;
  4094. });
  4095. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4096. auto se = detail::scope_exit([&] {
  4097. svr.stop();
  4098. thread.join();
  4099. ASSERT_FALSE(svr.is_running());
  4100. });
  4101. svr.wait_until_ready();
  4102. {
  4103. Client cli(HOST, PORT);
  4104. auto res = cli.Get("/hi");
  4105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4106. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4107. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4108. }
  4109. }
  4110. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4111. #ifdef CPPHTTPLIB_SSL_ENABLED
  4112. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4113. ASSERT_TRUE(svr.is_valid());
  4114. #else
  4115. Server svr;
  4116. #endif
  4117. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4118. if (req.path == "/routing_handler") {
  4119. res.set_header("PRE_ROUTING", "on");
  4120. res.set_content("Routing Handler", "text/plain");
  4121. return httplib::Server::HandlerResponse::Handled;
  4122. }
  4123. return httplib::Server::HandlerResponse::Unhandled;
  4124. });
  4125. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4126. res.set_content("Error", "text/html");
  4127. });
  4128. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4129. if (req.path == "/routing_handler") {
  4130. res.set_header("POST_ROUTING", "on");
  4131. }
  4132. });
  4133. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4134. res.set_content("Hello World!\n", "text/plain");
  4135. });
  4136. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4137. auto se = detail::scope_exit([&] {
  4138. svr.stop();
  4139. thread.join();
  4140. ASSERT_FALSE(svr.is_running());
  4141. });
  4142. svr.wait_until_ready();
  4143. {
  4144. #ifdef CPPHTTPLIB_SSL_ENABLED
  4145. SSLClient cli(HOST, PORT);
  4146. cli.enable_server_certificate_verification(false);
  4147. #else
  4148. Client cli(HOST, PORT);
  4149. #endif
  4150. auto res = cli.Get("/routing_handler");
  4151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4152. EXPECT_EQ(StatusCode::OK_200, res->status);
  4153. EXPECT_EQ("Routing Handler", res->body);
  4154. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4155. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4156. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4157. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4158. }
  4159. {
  4160. #ifdef CPPHTTPLIB_SSL_ENABLED
  4161. SSLClient cli(HOST, PORT);
  4162. cli.enable_server_certificate_verification(false);
  4163. #else
  4164. Client cli(HOST, PORT);
  4165. #endif
  4166. auto res = cli.Get("/hi");
  4167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4168. EXPECT_EQ(StatusCode::OK_200, res->status);
  4169. EXPECT_EQ("Hello World!\n", res->body);
  4170. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4171. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4172. }
  4173. {
  4174. #ifdef CPPHTTPLIB_SSL_ENABLED
  4175. SSLClient cli(HOST, PORT);
  4176. cli.enable_server_certificate_verification(false);
  4177. #else
  4178. Client cli(HOST, PORT);
  4179. #endif
  4180. auto res = cli.Get("/aaa");
  4181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4182. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4183. EXPECT_EQ("Error", res->body);
  4184. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4185. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4186. }
  4187. }
  4188. TEST(RequestHandlerTest, PreRequestHandler) {
  4189. auto route_path = "/user/:user";
  4190. Server svr;
  4191. svr.Get("/hi", [](const Request &, Response &res) {
  4192. res.set_content("hi", "text/plain");
  4193. });
  4194. svr.Get(route_path, [](const Request &req, Response &res) {
  4195. res.set_content(req.path_params.at("user"), "text/plain");
  4196. });
  4197. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4198. if (req.matched_route == route_path) {
  4199. auto user = req.path_params.at("user");
  4200. if (user != "john") {
  4201. res.status = StatusCode::Forbidden_403;
  4202. res.set_content("error", "text/html");
  4203. return Server::HandlerResponse::Handled;
  4204. }
  4205. }
  4206. return Server::HandlerResponse::Unhandled;
  4207. });
  4208. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4209. auto se = detail::scope_exit([&] {
  4210. svr.stop();
  4211. thread.join();
  4212. ASSERT_FALSE(svr.is_running());
  4213. });
  4214. svr.wait_until_ready();
  4215. Client cli(HOST, PORT);
  4216. {
  4217. auto res = cli.Get("/hi");
  4218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4219. EXPECT_EQ(StatusCode::OK_200, res->status);
  4220. EXPECT_EQ("hi", res->body);
  4221. }
  4222. {
  4223. auto res = cli.Get("/user/john");
  4224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4225. EXPECT_EQ(StatusCode::OK_200, res->status);
  4226. EXPECT_EQ("john", res->body);
  4227. }
  4228. {
  4229. auto res = cli.Get("/user/invalid-user");
  4230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4231. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4232. EXPECT_EQ("error", res->body);
  4233. }
  4234. }
  4235. // The pre-request handler must run before the request body is read, so a
  4236. // rejected request never forces the server to buffer a (potentially large)
  4237. // body. Here the posted body is larger than the payload limit: if the body
  4238. // were read first the server would answer 413, but because the pre-request
  4239. // handler runs first it answers 403 and the body is never read.
  4240. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4241. Server svr;
  4242. svr.set_payload_max_length(8);
  4243. auto handler_ran = false;
  4244. svr.Post("/reject", [&](const Request &req, Response &res) {
  4245. handler_ran = true;
  4246. res.set_content(req.body, "text/plain");
  4247. });
  4248. svr.Post("/accept", [](const Request &req, Response &res) {
  4249. res.set_content(req.body, "text/plain");
  4250. });
  4251. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4252. if (req.matched_route == "/reject") {
  4253. res.status = StatusCode::Forbidden_403;
  4254. res.set_content("denied", "text/plain");
  4255. return Server::HandlerResponse::Handled;
  4256. }
  4257. return Server::HandlerResponse::Unhandled;
  4258. });
  4259. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4260. auto se = detail::scope_exit([&] {
  4261. svr.stop();
  4262. thread.join();
  4263. ASSERT_FALSE(svr.is_running());
  4264. });
  4265. svr.wait_until_ready();
  4266. Client cli(HOST, PORT);
  4267. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4268. // rejects with 403 before the body is read, so 413 is never reached.
  4269. {
  4270. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4272. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4273. EXPECT_EQ("denied", res->body);
  4274. EXPECT_FALSE(handler_ran);
  4275. }
  4276. // An approved route still reads the body and enforces the payload limit.
  4277. {
  4278. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4280. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4281. }
  4282. }
  4283. TEST(UserDataTest, BasicOperations) {
  4284. httplib::UserData ud;
  4285. // Initially empty
  4286. EXPECT_FALSE(ud.has("key"));
  4287. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4288. // set and get
  4289. ud.set("key", 42);
  4290. EXPECT_TRUE(ud.has("key"));
  4291. auto *p = ud.get<int>("key");
  4292. ASSERT_NE(nullptr, p);
  4293. EXPECT_EQ(42, *p);
  4294. // Type mismatch → nullptr
  4295. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4296. // Overwrite with different type
  4297. ud.set("key", std::string("hello"));
  4298. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4299. auto *s = ud.get<std::string>("key");
  4300. ASSERT_NE(nullptr, s);
  4301. EXPECT_EQ("hello", *s);
  4302. // erase
  4303. ud.erase("key");
  4304. EXPECT_FALSE(ud.has("key"));
  4305. // clear
  4306. ud.set("a", 1);
  4307. ud.set("b", 2);
  4308. ud.clear();
  4309. EXPECT_FALSE(ud.has("a"));
  4310. EXPECT_FALSE(ud.has("b"));
  4311. }
  4312. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4313. struct AuthCtx {
  4314. std::string user_id;
  4315. };
  4316. Server svr;
  4317. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4318. res.user_data.set("auth", AuthCtx{"alice"});
  4319. return Server::HandlerResponse::Unhandled;
  4320. });
  4321. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4322. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4323. ASSERT_NE(nullptr, ctx);
  4324. res.set_content("Hello " + ctx->user_id, "text/plain");
  4325. });
  4326. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4327. auto se = detail::scope_exit([&] {
  4328. svr.stop();
  4329. thread.join();
  4330. ASSERT_FALSE(svr.is_running());
  4331. });
  4332. svr.wait_until_ready();
  4333. Client cli(HOST, PORT);
  4334. auto res = cli.Get("/me");
  4335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4336. EXPECT_EQ(StatusCode::OK_200, res->status);
  4337. EXPECT_EQ("Hello alice", res->body);
  4338. }
  4339. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4340. struct RoleCtx {
  4341. std::string role;
  4342. };
  4343. Server svr;
  4344. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4345. res.user_data.set("role", RoleCtx{"admin"});
  4346. return Server::HandlerResponse::Unhandled;
  4347. });
  4348. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4349. auto *ctx = res.user_data.get<RoleCtx>("role");
  4350. ASSERT_NE(nullptr, ctx);
  4351. res.set_content(ctx->role, "text/plain");
  4352. });
  4353. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4354. auto se = detail::scope_exit([&] {
  4355. svr.stop();
  4356. thread.join();
  4357. ASSERT_FALSE(svr.is_running());
  4358. });
  4359. svr.wait_until_ready();
  4360. Client cli(HOST, PORT);
  4361. auto res = cli.Get("/role");
  4362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4363. EXPECT_EQ(StatusCode::OK_200, res->status);
  4364. EXPECT_EQ("admin", res->body);
  4365. }
  4366. TEST(InvalidFormatTest, StatusCode) {
  4367. Server svr;
  4368. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4369. res.set_content("Hello World!\n", "text/plain");
  4370. res.status = 9999; // Status should be a three-digit code...
  4371. });
  4372. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4373. auto se = detail::scope_exit([&] {
  4374. svr.stop();
  4375. thread.join();
  4376. ASSERT_FALSE(svr.is_running());
  4377. });
  4378. svr.wait_until_ready();
  4379. {
  4380. Client cli(HOST, PORT);
  4381. auto res = cli.Get("/hi");
  4382. ASSERT_FALSE(res);
  4383. }
  4384. }
  4385. TEST(URLFragmentTest, WithFragment) {
  4386. Server svr;
  4387. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4388. EXPECT_TRUE(req.target == "/hi");
  4389. });
  4390. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4391. auto se = detail::scope_exit([&] {
  4392. svr.stop();
  4393. thread.join();
  4394. ASSERT_FALSE(svr.is_running());
  4395. });
  4396. svr.wait_until_ready();
  4397. {
  4398. Client cli(HOST, PORT);
  4399. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4400. EXPECT_TRUE(res);
  4401. EXPECT_EQ(StatusCode::OK_200, res->status);
  4402. res = cli.Get("/hi%23key1=val1=key2=val2");
  4403. EXPECT_TRUE(res);
  4404. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4405. }
  4406. }
  4407. TEST(HeaderWriter, SetHeaderWriter) {
  4408. Server svr;
  4409. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4410. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4411. return detail::write_headers(strm, hdrs);
  4412. });
  4413. svr.Get("/hi", [](const Request &req, Response &res) {
  4414. auto it = req.headers.find("CustomClientHeader");
  4415. EXPECT_TRUE(it != req.headers.end());
  4416. EXPECT_EQ(it->second, "CustomClientValue");
  4417. res.set_content("Hello World!\n", "text/plain");
  4418. });
  4419. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4420. auto se = detail::scope_exit([&] {
  4421. svr.stop();
  4422. thread.join();
  4423. ASSERT_FALSE(svr.is_running());
  4424. });
  4425. svr.wait_until_ready();
  4426. {
  4427. Client cli(HOST, PORT);
  4428. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4429. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4430. return detail::write_headers(strm, hdrs);
  4431. });
  4432. auto res = cli.Get("/hi");
  4433. EXPECT_TRUE(res);
  4434. EXPECT_EQ(StatusCode::OK_200, res->status);
  4435. auto it = res->headers.find("CustomServerHeader");
  4436. EXPECT_TRUE(it != res->headers.end());
  4437. EXPECT_EQ(it->second, "CustomServerValue");
  4438. }
  4439. }
  4440. class ServerTest : public ::testing::Test {
  4441. protected:
  4442. ServerTest()
  4443. : cli_(HOST, PORT)
  4444. #ifdef CPPHTTPLIB_SSL_ENABLED
  4445. ,
  4446. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4447. #endif
  4448. {
  4449. #ifdef CPPHTTPLIB_SSL_ENABLED
  4450. cli_.enable_server_certificate_verification(false);
  4451. #endif
  4452. // Allow LARGE_DATA (100MB) responses
  4453. cli_.set_payload_max_length(200 * 1024 * 1024);
  4454. }
  4455. virtual void SetUp() {
  4456. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4457. svr_.set_payload_max_length(200 * 1024 * 1024);
  4458. svr_.set_mount_point("/", "./www");
  4459. svr_.set_mount_point("/mount", "./www2");
  4460. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4461. svr_.Get("/hi",
  4462. [&](const Request & /*req*/, Response &res) {
  4463. res.set_content("Hello World!", "text/plain");
  4464. })
  4465. .Get("/file_content",
  4466. [&](const Request & /*req*/, Response &res) {
  4467. res.set_file_content("./www/dir/test.html");
  4468. })
  4469. .Get("/file_content_with_content_type",
  4470. [&](const Request & /*req*/, Response &res) {
  4471. res.set_file_content("./www/file", "text/plain");
  4472. })
  4473. .Get("/invalid_file_content",
  4474. [&](const Request & /*req*/, Response &res) {
  4475. res.set_file_content("./www/dir/invalid_file_path");
  4476. })
  4477. .Get("/http_response_splitting",
  4478. [&](const Request & /*req*/, Response &res) {
  4479. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4480. EXPECT_EQ(0U, res.headers.size());
  4481. EXPECT_FALSE(res.has_header("a"));
  4482. res.set_header("a", "1\nSet-Cookie: a=1");
  4483. EXPECT_EQ(0U, res.headers.size());
  4484. EXPECT_FALSE(res.has_header("a"));
  4485. res.set_header("a", "1\rSet-Cookie: a=1");
  4486. EXPECT_EQ(0U, res.headers.size());
  4487. EXPECT_FALSE(res.has_header("a"));
  4488. res.set_header("a\r\nb", "0");
  4489. EXPECT_EQ(0U, res.headers.size());
  4490. EXPECT_FALSE(res.has_header("a"));
  4491. res.set_header("a\rb", "0");
  4492. EXPECT_EQ(0U, res.headers.size());
  4493. EXPECT_FALSE(res.has_header("a"));
  4494. res.set_header("a\nb", "0");
  4495. EXPECT_EQ(0U, res.headers.size());
  4496. EXPECT_FALSE(res.has_header("a"));
  4497. res.set_redirect("1\r\nSet-Cookie: a=1");
  4498. EXPECT_EQ(0U, res.headers.size());
  4499. EXPECT_FALSE(res.has_header("Location"));
  4500. })
  4501. .Get("/slow",
  4502. [&](const Request & /*req*/, Response &res) {
  4503. std::this_thread::sleep_for(std::chrono::seconds(4));
  4504. res.set_content("slow", "text/plain");
  4505. })
  4506. #if 0
  4507. .Post("/slowpost",
  4508. [&](const Request & /*req*/, Response &res) {
  4509. std::this_thread::sleep_for(std::chrono::seconds(2));
  4510. res.set_content("slow", "text/plain");
  4511. })
  4512. #endif
  4513. .Get("/remote_addr",
  4514. [&](const Request &req, Response &res) {
  4515. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4516. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4517. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4518. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4519. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4520. #endif
  4521. res.set_content(req.remote_addr, "text/plain");
  4522. })
  4523. .Get("/local_addr",
  4524. [&](const Request &req, Response &res) {
  4525. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4526. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4527. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4528. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4529. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4530. #endif
  4531. auto local_addr = req.local_addr;
  4532. auto local_port = std::to_string(req.local_port);
  4533. res.set_content(local_addr.append(":").append(local_port),
  4534. "text/plain");
  4535. })
  4536. .Get("/endwith%",
  4537. [&](const Request & /*req*/, Response &res) {
  4538. res.set_content("Hello World!", "text/plain");
  4539. })
  4540. .Get("/a\\+\\+b",
  4541. [&](const Request &req, Response &res) {
  4542. ASSERT_TRUE(req.has_param("a +b"));
  4543. auto val = req.get_param_value("a +b");
  4544. res.set_content(val, "text/plain");
  4545. })
  4546. .Get("/", [&](const Request & /*req*/,
  4547. Response &res) { res.set_redirect("/hi"); })
  4548. .Post("/1",
  4549. [](const Request & /*req*/, Response &res) {
  4550. res.set_redirect("/2", StatusCode::SeeOther_303);
  4551. })
  4552. .Get("/2",
  4553. [](const Request & /*req*/, Response &res) {
  4554. res.set_content("redirected.", "text/plain");
  4555. res.status = StatusCode::OK_200;
  4556. })
  4557. .Post("/person",
  4558. [&](const Request &req, Response &res) {
  4559. if (req.has_param("name") && req.has_param("note")) {
  4560. persons_[req.get_param_value("name")] =
  4561. req.get_param_value("note");
  4562. } else {
  4563. res.status = StatusCode::BadRequest_400;
  4564. }
  4565. })
  4566. .Put("/person",
  4567. [&](const Request &req, Response &res) {
  4568. if (req.has_param("name") && req.has_param("note")) {
  4569. persons_[req.get_param_value("name")] =
  4570. req.get_param_value("note");
  4571. } else {
  4572. res.status = StatusCode::BadRequest_400;
  4573. }
  4574. })
  4575. .Get("/person/(.*)",
  4576. [&](const Request &req, Response &res) {
  4577. string name = req.matches[1];
  4578. if (persons_.find(name) != persons_.end()) {
  4579. auto note = persons_[name];
  4580. res.set_content(note, "text/plain");
  4581. } else {
  4582. res.status = StatusCode::NotFound_404;
  4583. }
  4584. })
  4585. .Delete("/person",
  4586. [&](const Request &req, Response &res) {
  4587. if (req.has_param("name")) {
  4588. string name = req.get_param_value("name");
  4589. if (persons_.find(name) != persons_.end()) {
  4590. persons_.erase(name);
  4591. res.set_content("DELETED", "text/plain");
  4592. } else {
  4593. res.status = StatusCode::NotFound_404;
  4594. }
  4595. } else {
  4596. res.status = StatusCode::BadRequest_400;
  4597. }
  4598. })
  4599. .Post("/x-www-form-urlencoded-json",
  4600. [&](const Request &req, Response &res) {
  4601. auto json = req.get_param_value("json");
  4602. ASSERT_EQ(JSON_DATA, json);
  4603. res.set_content(json, "appliation/json");
  4604. res.status = StatusCode::OK_200;
  4605. })
  4606. .Get("/streamed-chunked",
  4607. [&](const Request & /*req*/, Response &res) {
  4608. res.set_chunked_content_provider(
  4609. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4610. sink.os << "123";
  4611. sink.os << "456";
  4612. sink.os << "789";
  4613. sink.done();
  4614. return true;
  4615. });
  4616. })
  4617. .Get("/streamed-chunked-with-prohibited-trailer",
  4618. [&](const Request & /*req*/, Response &res) {
  4619. auto i = new int(0);
  4620. // Declare both a prohibited trailer (Content-Length) and an
  4621. // allowed one
  4622. res.set_header("Trailer", "Content-Length, X-Allowed");
  4623. res.set_chunked_content_provider(
  4624. "text/plain",
  4625. [i](size_t /*offset*/, DataSink &sink) {
  4626. switch (*i) {
  4627. case 0: sink.os << "123"; break;
  4628. case 1: sink.os << "456"; break;
  4629. case 2: sink.os << "789"; break;
  4630. case 3: {
  4631. sink.done_with_trailer(
  4632. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4633. } break;
  4634. }
  4635. (*i)++;
  4636. return true;
  4637. },
  4638. [i](bool success) {
  4639. EXPECT_TRUE(success);
  4640. delete i;
  4641. });
  4642. })
  4643. .Get("/streamed-chunked2",
  4644. [&](const Request & /*req*/, Response &res) {
  4645. auto i = new int(0);
  4646. res.set_chunked_content_provider(
  4647. "text/plain",
  4648. [i](size_t /*offset*/, DataSink &sink) {
  4649. switch (*i) {
  4650. case 0: sink.os << "123"; break;
  4651. case 1: sink.os << "456"; break;
  4652. case 2: sink.os << "789"; break;
  4653. case 3: sink.done(); break;
  4654. }
  4655. (*i)++;
  4656. return true;
  4657. },
  4658. [i](bool success) {
  4659. EXPECT_TRUE(success);
  4660. delete i;
  4661. });
  4662. })
  4663. .Get("/streamed-chunked-with-trailer",
  4664. [&](const Request & /*req*/, Response &res) {
  4665. auto i = new int(0);
  4666. res.set_header("Trailer", "Dummy1, Dummy2");
  4667. res.set_chunked_content_provider(
  4668. "text/plain",
  4669. [i](size_t /*offset*/, DataSink &sink) {
  4670. switch (*i) {
  4671. case 0: sink.os << "123"; break;
  4672. case 1: sink.os << "456"; break;
  4673. case 2: sink.os << "789"; break;
  4674. case 3: {
  4675. sink.done_with_trailer(
  4676. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4677. } break;
  4678. }
  4679. (*i)++;
  4680. return true;
  4681. },
  4682. [i](bool success) {
  4683. EXPECT_TRUE(success);
  4684. delete i;
  4685. });
  4686. })
  4687. .Get("/streamed",
  4688. [&](const Request & /*req*/, Response &res) {
  4689. res.set_content_provider(
  4690. 6, "text/plain",
  4691. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4692. sink.os << (offset < 3 ? "a" : "b");
  4693. return true;
  4694. });
  4695. })
  4696. .Get("/streamed-without-length",
  4697. [&](const Request & /*req*/, Response &res) {
  4698. auto data = new std::string("abcdefg");
  4699. res.set_content_provider(
  4700. "text/plain",
  4701. [data](size_t offset, DataSink &sink) {
  4702. if (offset < data->size()) {
  4703. sink.os << data->substr(offset);
  4704. }
  4705. sink.done();
  4706. return true;
  4707. },
  4708. [data](bool success) {
  4709. EXPECT_TRUE(success);
  4710. delete data;
  4711. });
  4712. })
  4713. .Get("/streamed-with-range",
  4714. [&](const Request &req, Response &res) {
  4715. auto data = new std::string("abcdefg");
  4716. // An explicit status keeps the server from picking the 206 it
  4717. // would otherwise choose for a ranged request, so the response
  4718. // is not a partial representation.
  4719. auto status = req.get_param_value("status");
  4720. if (status == "200") {
  4721. res.status = StatusCode::OK_200;
  4722. } else if (status == "403") {
  4723. res.status = StatusCode::Forbidden_403;
  4724. }
  4725. res.set_content_provider(
  4726. data->size(), "text/plain",
  4727. [data](size_t offset, size_t length, DataSink &sink) {
  4728. size_t DATA_CHUNK_SIZE = 4;
  4729. const auto &d = *data;
  4730. auto out_len =
  4731. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4732. auto ret =
  4733. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4734. EXPECT_TRUE(ret);
  4735. return true;
  4736. },
  4737. [data, &req](bool success) {
  4738. EXPECT_EQ(success, !req.has_param("error"));
  4739. delete data;
  4740. });
  4741. })
  4742. .Get("/streamed-cancel",
  4743. [&](const Request & /*req*/, Response &res) {
  4744. res.set_content_provider(
  4745. size_t(-1), "text/plain",
  4746. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4747. sink.os << "data_chunk";
  4748. return true;
  4749. });
  4750. })
  4751. .Get("/regex-with-delimiter",
  4752. [&](const Request &req, Response & /*res*/) {
  4753. ASSERT_TRUE(req.has_param("key"));
  4754. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4755. })
  4756. .Get("/with-range",
  4757. [&](const Request & /*req*/, Response &res) {
  4758. res.set_content("abcdefg", "text/plain");
  4759. })
  4760. .Get("/test-start-time",
  4761. [&](const Request &req, Response & /*res*/) {
  4762. EXPECT_NE(req.start_time_,
  4763. std::chrono::steady_clock::time_point::min());
  4764. })
  4765. .Get("/with-range-customized-response",
  4766. [&](const Request & /*req*/, Response &res) {
  4767. res.status = StatusCode::BadRequest_400;
  4768. res.set_content(JSON_DATA, "application/json");
  4769. })
  4770. .Post("/chunked",
  4771. [&](const Request &req, Response & /*res*/) {
  4772. EXPECT_EQ(req.body, "dechunked post body");
  4773. })
  4774. .Post("/large-chunked",
  4775. [&](const Request &req, Response & /*res*/) {
  4776. std::string expected(6 * 30 * 1024u, 'a');
  4777. EXPECT_EQ(req.body, expected);
  4778. })
  4779. .Post("/multipart",
  4780. [&](const Request &req, Response & /*res*/) {
  4781. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4782. req.form.get_field_count("text2") +
  4783. req.form.get_field_count("file3") +
  4784. req.form.get_field_count("file4"));
  4785. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4786. req.form.get_file_count("file2"));
  4787. ASSERT_TRUE(!req.form.has_file("???"));
  4788. ASSERT_TRUE(!req.form.has_field("???"));
  4789. ASSERT_TRUE(req.body.empty());
  4790. {
  4791. const auto &text = req.form.get_field("text1");
  4792. EXPECT_EQ("text default", text);
  4793. }
  4794. {
  4795. const auto &text = req.form.get_field("text2");
  4796. EXPECT_EQ("aωb", text);
  4797. }
  4798. {
  4799. const auto &file = req.form.get_file("file1");
  4800. EXPECT_EQ("hello.txt", file.filename);
  4801. EXPECT_EQ("text/plain", file.content_type);
  4802. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4803. }
  4804. {
  4805. const auto &file = req.form.get_file("file2");
  4806. EXPECT_EQ("world.json", file.filename);
  4807. EXPECT_EQ("application/json", file.content_type);
  4808. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4809. }
  4810. {
  4811. const auto &text = req.form.get_field("file3");
  4812. EXPECT_EQ(0u, text.size());
  4813. }
  4814. {
  4815. const auto &text = req.form.get_field("file4");
  4816. EXPECT_EQ(0u, text.size());
  4817. }
  4818. })
  4819. .Post("/multipart/multi_file_values",
  4820. [&](const Request &req, Response & /*res*/) {
  4821. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4822. req.form.get_field_count("multi_text1"));
  4823. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4824. ASSERT_TRUE(!req.form.has_file("???"));
  4825. ASSERT_TRUE(!req.form.has_field("???"));
  4826. ASSERT_TRUE(req.body.empty());
  4827. {
  4828. const auto &text = req.form.get_field("text");
  4829. EXPECT_EQ("default text", text);
  4830. }
  4831. {
  4832. const auto &text1_values = req.form.get_fields("multi_text1");
  4833. EXPECT_EQ(2u, text1_values.size());
  4834. EXPECT_EQ("aaaaa", text1_values[0]);
  4835. EXPECT_EQ("bbbbb", text1_values[1]);
  4836. }
  4837. {
  4838. const auto &file1_values = req.form.get_files("multi_file1");
  4839. EXPECT_EQ(2u, file1_values.size());
  4840. auto file1 = file1_values[0];
  4841. EXPECT_EQ(file1.filename, "hello.txt");
  4842. EXPECT_EQ(file1.content_type, "text/plain");
  4843. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4844. auto file2 = file1_values[1];
  4845. EXPECT_EQ(file2.filename, "world.json");
  4846. EXPECT_EQ(file2.content_type, "application/json");
  4847. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4848. }
  4849. })
  4850. .Post("/empty",
  4851. [&](const Request &req, Response &res) {
  4852. EXPECT_EQ(req.body, "");
  4853. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4854. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4855. res.set_content("empty", "text/plain");
  4856. })
  4857. .Post("/empty-no-content-type",
  4858. [&](const Request &req, Response &res) {
  4859. EXPECT_EQ(req.body, "");
  4860. EXPECT_FALSE(req.has_header("Content-Type"));
  4861. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4862. res.set_content("empty-no-content-type", "text/plain");
  4863. })
  4864. .Post("/path-only",
  4865. [&](const Request &req, Response &res) {
  4866. EXPECT_EQ(req.body, "");
  4867. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4868. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4869. res.set_content("path-only", "text/plain");
  4870. })
  4871. .Post("/path-headers-only",
  4872. [&](const Request &req, Response &res) {
  4873. EXPECT_EQ(req.body, "");
  4874. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4875. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4876. EXPECT_EQ("world", req.get_header_value("hello"));
  4877. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4878. res.set_content("path-headers-only", "text/plain");
  4879. })
  4880. .Post("/post-large",
  4881. [&](const Request &req, Response &res) {
  4882. EXPECT_EQ(req.body, LARGE_DATA);
  4883. res.set_content(req.body, "text/plain");
  4884. })
  4885. .Post("/post-loopback",
  4886. [&](const Request &, Response &res,
  4887. ContentReader const &content_reader) {
  4888. std::string body;
  4889. content_reader([&](const char *data, size_t data_length) {
  4890. body.append(data, data_length);
  4891. return true;
  4892. });
  4893. res.set_content(body, "text/plain");
  4894. })
  4895. .Put("/put-loopback",
  4896. [&](const Request &, Response &res,
  4897. ContentReader const &content_reader) {
  4898. std::string body;
  4899. content_reader([&](const char *data, size_t data_length) {
  4900. body.append(data, data_length);
  4901. return true;
  4902. });
  4903. res.set_content(body, "text/plain");
  4904. })
  4905. .Patch("/patch-loopback",
  4906. [&](const Request &, Response &res,
  4907. ContentReader const &content_reader) {
  4908. std::string body;
  4909. content_reader([&](const char *data, size_t data_length) {
  4910. body.append(data, data_length);
  4911. return true;
  4912. });
  4913. res.set_content(body, "text/plain");
  4914. })
  4915. .Put("/empty-no-content-type",
  4916. [&](const Request &req, Response &res) {
  4917. EXPECT_EQ(req.body, "");
  4918. EXPECT_FALSE(req.has_header("Content-Type"));
  4919. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4920. res.set_content("empty-no-content-type", "text/plain");
  4921. })
  4922. .Put("/put",
  4923. [&](const Request &req, Response &res) {
  4924. EXPECT_EQ(req.body, "PUT");
  4925. res.set_content(req.body, "text/plain");
  4926. })
  4927. .Put("/put-large",
  4928. [&](const Request &req, Response &res) {
  4929. EXPECT_EQ(req.body, LARGE_DATA);
  4930. res.set_content(req.body, "text/plain");
  4931. })
  4932. .Patch("/patch",
  4933. [&](const Request &req, Response &res) {
  4934. EXPECT_EQ(req.body, "PATCH");
  4935. res.set_content(req.body, "text/plain");
  4936. })
  4937. .Delete("/delete",
  4938. [&](const Request & /*req*/, Response &res) {
  4939. res.set_content("DELETE", "text/plain");
  4940. })
  4941. .Delete("/delete-body",
  4942. [&](const Request &req, Response &res) {
  4943. EXPECT_EQ(req.body, "content");
  4944. res.set_content(req.body, "text/plain");
  4945. })
  4946. .Options(R"(\*)",
  4947. [&](const Request & /*req*/, Response &res) {
  4948. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4949. })
  4950. .CustomRoute("PROPFIND", "/dav/:id",
  4951. [&](const Request &req, Response &res) {
  4952. res.set_header("x-body-size",
  4953. std::to_string(req.body.size()));
  4954. res.set_header("x-matched-route", req.matched_route);
  4955. res.set_header("x-dav-id", req.path_params.at("id"));
  4956. res.status = StatusCode::MultiStatus_207;
  4957. res.set_content(req.body, "application/xml");
  4958. })
  4959. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4960. [&](const Request &req, Response &res) {
  4961. res.set_header("x-dav-match", req.matches[1]);
  4962. res.status = StatusCode::MultiStatus_207;
  4963. })
  4964. .CustomRoute("MKCOL", "/dav-mkcol",
  4965. [&](const Request &req, Response &res) {
  4966. EXPECT_TRUE(req.body.empty());
  4967. res.status = StatusCode::Created_201;
  4968. })
  4969. .CustomRoute(
  4970. "REPORT", "/dav-report",
  4971. [&](const Request & /*req*/, Response &res,
  4972. const ContentReader &content_reader) {
  4973. std::string body;
  4974. content_reader([&](const char *data, size_t data_length) {
  4975. body.append(data, data_length);
  4976. return true;
  4977. });
  4978. res.set_header("x-body-size", std::to_string(body.size()));
  4979. res.status = StatusCode::MultiStatus_207;
  4980. res.set_content(body, "application/xml");
  4981. })
  4982. .Get("/request-target",
  4983. [&](const Request &req, Response & /*res*/) {
  4984. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4985. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4986. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4987. })
  4988. .Get("/long-query-value",
  4989. [&](const Request &req, Response & /*res*/) {
  4990. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4991. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4992. })
  4993. .Get("/too-long-query-value",
  4994. [&](const Request &req, Response & /*res*/) {
  4995. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4996. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4997. })
  4998. .Get("/array-param",
  4999. [&](const Request &req, Response & /*res*/) {
  5000. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5001. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5002. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5003. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5004. })
  5005. .Get("/array-param-values",
  5006. [&](const Request &req, Response & /*res*/) {
  5007. auto values = req.get_param_values("array");
  5008. EXPECT_EQ(3u, values.size());
  5009. EXPECT_EQ("value1", values[0]);
  5010. EXPECT_EQ("value2", values[1]);
  5011. EXPECT_EQ("value3", values[2]);
  5012. auto empty = req.get_param_values("nonexistent");
  5013. EXPECT_TRUE(empty.empty());
  5014. })
  5015. .Post("/validate-no-multiple-headers",
  5016. [&](const Request &req, Response & /*res*/) {
  5017. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5018. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5019. })
  5020. .Post("/content_receiver",
  5021. [&](const Request &req, Response &res,
  5022. const ContentReader &content_reader) {
  5023. if (req.is_multipart_form_data()) {
  5024. std::vector<FormData> items;
  5025. content_reader(
  5026. [&](const FormData &file) {
  5027. items.push_back(file);
  5028. return true;
  5029. },
  5030. [&](const char *data, size_t data_length) {
  5031. items.back().content.append(data, data_length);
  5032. return true;
  5033. });
  5034. EXPECT_EQ(5u, items.size());
  5035. {
  5036. const auto &file = get_file_value(items, "text1");
  5037. EXPECT_TRUE(file.filename.empty());
  5038. EXPECT_EQ("text default", file.content);
  5039. }
  5040. {
  5041. const auto &file = get_file_value(items, "text2");
  5042. EXPECT_TRUE(file.filename.empty());
  5043. EXPECT_EQ("aωb", file.content);
  5044. }
  5045. {
  5046. const auto &file = get_file_value(items, "file1");
  5047. EXPECT_EQ("hello.txt", file.filename);
  5048. EXPECT_EQ("text/plain", file.content_type);
  5049. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5050. }
  5051. {
  5052. const auto &file = get_file_value(items, "file2");
  5053. EXPECT_EQ("world.json", file.filename);
  5054. EXPECT_EQ("application/json", file.content_type);
  5055. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5056. }
  5057. {
  5058. const auto &file = get_file_value(items, "file3");
  5059. EXPECT_TRUE(file.filename.empty());
  5060. EXPECT_EQ("application/octet-stream", file.content_type);
  5061. EXPECT_EQ(0u, file.content.size());
  5062. }
  5063. } else {
  5064. std::string body;
  5065. content_reader([&](const char *data, size_t data_length) {
  5066. EXPECT_EQ(7U, data_length);
  5067. body.append(data, data_length);
  5068. return true;
  5069. });
  5070. EXPECT_EQ(body, "content");
  5071. res.set_content(body, "text/plain");
  5072. }
  5073. })
  5074. .Put("/content_receiver",
  5075. [&](const Request & /*req*/, Response &res,
  5076. const ContentReader &content_reader) {
  5077. std::string body;
  5078. content_reader([&](const char *data, size_t data_length) {
  5079. body.append(data, data_length);
  5080. return true;
  5081. });
  5082. EXPECT_EQ(body, "content");
  5083. res.set_content(body, "text/plain");
  5084. })
  5085. .Patch("/content_receiver",
  5086. [&](const Request & /*req*/, Response &res,
  5087. const ContentReader &content_reader) {
  5088. std::string body;
  5089. content_reader([&](const char *data, size_t data_length) {
  5090. body.append(data, data_length);
  5091. return true;
  5092. });
  5093. EXPECT_EQ(body, "content");
  5094. res.set_content(body, "text/plain");
  5095. })
  5096. .Post("/query-string-and-body",
  5097. [&](const Request &req, Response & /*res*/) {
  5098. ASSERT_TRUE(req.has_param("key"));
  5099. EXPECT_EQ(req.get_param_value("key"), "value");
  5100. EXPECT_EQ(req.body, "content");
  5101. })
  5102. .Get("/last-request",
  5103. [&](const Request &req, Response & /*res*/) {
  5104. EXPECT_EQ("close", req.get_header_value("Connection"));
  5105. })
  5106. .Get(R"(/redirect/(\d+))",
  5107. [&](const Request &req, Response &res) {
  5108. auto num = std::stoi(req.matches[1]) + 1;
  5109. std::string url = "/redirect/" + std::to_string(num);
  5110. res.set_redirect(url);
  5111. })
  5112. .Post("/binary",
  5113. [&](const Request &req, Response &res) {
  5114. EXPECT_EQ(4U, req.body.size());
  5115. EXPECT_EQ("application/octet-stream",
  5116. req.get_header_value("Content-Type"));
  5117. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5118. res.set_content(req.body, "application/octet-stream");
  5119. })
  5120. .Put("/binary",
  5121. [&](const Request &req, Response &res) {
  5122. EXPECT_EQ(4U, req.body.size());
  5123. EXPECT_EQ("application/octet-stream",
  5124. req.get_header_value("Content-Type"));
  5125. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5126. res.set_content(req.body, "application/octet-stream");
  5127. })
  5128. .Patch("/binary",
  5129. [&](const Request &req, Response &res) {
  5130. EXPECT_EQ(4U, req.body.size());
  5131. EXPECT_EQ("application/octet-stream",
  5132. req.get_header_value("Content-Type"));
  5133. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5134. res.set_content(req.body, "application/octet-stream");
  5135. })
  5136. .Delete("/binary",
  5137. [&](const Request &req, Response &res) {
  5138. EXPECT_EQ(4U, req.body.size());
  5139. EXPECT_EQ("application/octet-stream",
  5140. req.get_header_value("Content-Type"));
  5141. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5142. res.set_content(req.body, "application/octet-stream");
  5143. })
  5144. .Get("/issue1772",
  5145. [&](const Request & /*req*/, Response &res) {
  5146. res.status = 401;
  5147. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5148. })
  5149. .Delete("/issue609",
  5150. [](const httplib::Request &, httplib::Response &res,
  5151. const httplib::ContentReader &) {
  5152. res.set_content("ok", "text/plain");
  5153. })
  5154. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5155. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5156. .Get("/compress",
  5157. [&](const Request & /*req*/, Response &res) {
  5158. res.set_content(
  5159. "12345678901234567890123456789012345678901234567890123456789"
  5160. "01234567890123456789012345678901234567890",
  5161. "text/plain");
  5162. })
  5163. .Get("/compress-with-charset",
  5164. [&](const Request & /*req*/, Response &res) {
  5165. res.set_content(
  5166. "12345678901234567890123456789012345678901234567890123456789"
  5167. "01234567890123456789012345678901234567890",
  5168. "application/json; charset=utf-8");
  5169. })
  5170. .Get("/nocompress",
  5171. [&](const Request & /*req*/, Response &res) {
  5172. res.set_content(
  5173. "12345678901234567890123456789012345678901234567890123456789"
  5174. "01234567890123456789012345678901234567890",
  5175. "application/octet-stream");
  5176. })
  5177. .Post("/compress-multipart",
  5178. [&](const Request &req, Response & /*res*/) {
  5179. EXPECT_EQ(2u, req.form.fields.size());
  5180. ASSERT_TRUE(!req.form.has_field("???"));
  5181. {
  5182. const auto &text = req.form.get_field("key1");
  5183. EXPECT_EQ("test", text);
  5184. }
  5185. {
  5186. const auto &text = req.form.get_field("key2");
  5187. EXPECT_EQ("--abcdefg123", text);
  5188. }
  5189. })
  5190. #endif
  5191. ;
  5192. persons_["john"] = "programmer";
  5193. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5194. svr_.wait_until_ready();
  5195. }
  5196. virtual void TearDown() {
  5197. svr_.stop();
  5198. if (!request_threads_.empty()) {
  5199. std::this_thread::sleep_for(std::chrono::seconds(1));
  5200. for (auto &t : request_threads_) {
  5201. t.join();
  5202. }
  5203. }
  5204. t_.join();
  5205. }
  5206. map<string, string> persons_;
  5207. #ifdef CPPHTTPLIB_SSL_ENABLED
  5208. SSLClient cli_;
  5209. SSLServer svr_;
  5210. #else
  5211. Client cli_;
  5212. Server svr_;
  5213. #endif
  5214. thread t_;
  5215. std::vector<thread> request_threads_;
  5216. };
  5217. TEST_F(ServerTest, GetMethod200) {
  5218. auto res = cli_.Get("/hi");
  5219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5220. EXPECT_EQ("HTTP/1.1", res->version);
  5221. EXPECT_EQ(StatusCode::OK_200, res->status);
  5222. EXPECT_EQ("OK", res->reason);
  5223. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5224. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5225. EXPECT_EQ("Hello World!", res->body);
  5226. }
  5227. TEST_F(ServerTest, GetEmptyFile) {
  5228. auto res = cli_.Get("/empty_file");
  5229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5230. EXPECT_EQ(StatusCode::OK_200, res->status);
  5231. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5232. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5233. EXPECT_EQ("", res->body);
  5234. }
  5235. TEST_F(ServerTest, GetFileContent) {
  5236. auto res = cli_.Get("/file_content");
  5237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5238. EXPECT_EQ(StatusCode::OK_200, res->status);
  5239. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5240. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5241. EXPECT_EQ("test.html", res->body);
  5242. }
  5243. TEST_F(ServerTest, GetFileContentWithRange) {
  5244. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5246. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5247. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5248. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5249. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5250. EXPECT_EQ("est", res->body);
  5251. }
  5252. TEST_F(ServerTest, GetFileContentWithContentType) {
  5253. auto res = cli_.Get("/file_content_with_content_type");
  5254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5255. EXPECT_EQ(StatusCode::OK_200, res->status);
  5256. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5257. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5258. EXPECT_EQ("file\n", res->body);
  5259. }
  5260. TEST_F(ServerTest, GetInvalidFileContent) {
  5261. auto res = cli_.Get("/invalid_file_content");
  5262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5263. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5264. }
  5265. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5266. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5268. EXPECT_EQ("HTTP/1.1", res->version);
  5269. EXPECT_EQ(StatusCode::OK_200, res->status);
  5270. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5271. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5272. EXPECT_EQ("Hello World!", res->body);
  5273. }
  5274. TEST_F(ServerTest, GetMethod302) {
  5275. auto res = cli_.Get("/");
  5276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5277. EXPECT_EQ(StatusCode::Found_302, res->status);
  5278. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5279. }
  5280. TEST_F(ServerTest, GetMethod302Redirect) {
  5281. cli_.set_follow_location(true);
  5282. auto res = cli_.Get("/");
  5283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5284. EXPECT_EQ(StatusCode::OK_200, res->status);
  5285. EXPECT_EQ("Hello World!", res->body);
  5286. EXPECT_EQ("/hi", res->location);
  5287. }
  5288. TEST_F(ServerTest, GetMethod404) {
  5289. auto res = cli_.Get("/invalid");
  5290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5291. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5292. }
  5293. TEST_F(ServerTest, HeadMethod200) {
  5294. auto res = cli_.Head("/hi");
  5295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5296. EXPECT_EQ(StatusCode::OK_200, res->status);
  5297. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5298. EXPECT_TRUE(res->body.empty());
  5299. }
  5300. TEST_F(ServerTest, HeadMethod200Static) {
  5301. auto res = cli_.Head("/mount/dir/index.html");
  5302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5303. EXPECT_EQ(StatusCode::OK_200, res->status);
  5304. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5305. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5306. EXPECT_TRUE(res->body.empty());
  5307. }
  5308. TEST_F(ServerTest, HeadMethod404) {
  5309. auto res = cli_.Head("/invalid");
  5310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5311. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5312. EXPECT_TRUE(res->body.empty());
  5313. }
  5314. TEST_F(ServerTest, GetMethodPersonJohn) {
  5315. auto res = cli_.Get("/person/john");
  5316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5317. EXPECT_EQ(StatusCode::OK_200, res->status);
  5318. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5319. EXPECT_EQ("programmer", res->body);
  5320. }
  5321. TEST_F(ServerTest, PostMethod1) {
  5322. auto res = cli_.Get("/person/john1");
  5323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5324. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5325. res = cli_.Post("/person", "name=john1&note=coder",
  5326. "application/x-www-form-urlencoded");
  5327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5328. ASSERT_EQ(StatusCode::OK_200, res->status);
  5329. res = cli_.Get("/person/john1");
  5330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5331. ASSERT_EQ(StatusCode::OK_200, res->status);
  5332. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5333. ASSERT_EQ("coder", res->body);
  5334. }
  5335. TEST_F(ServerTest, PostMethod2) {
  5336. auto res = cli_.Get("/person/john2");
  5337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5338. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5339. Params params;
  5340. params.emplace("name", "john2");
  5341. params.emplace("note", "coder");
  5342. res = cli_.Post("/person", params);
  5343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5344. ASSERT_EQ(StatusCode::OK_200, res->status);
  5345. res = cli_.Get("/person/john2");
  5346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5347. ASSERT_EQ(StatusCode::OK_200, res->status);
  5348. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5349. ASSERT_EQ("coder", res->body);
  5350. }
  5351. TEST_F(ServerTest, PutMethod3) {
  5352. auto res = cli_.Get("/person/john3");
  5353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5354. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5355. Params params;
  5356. params.emplace("name", "john3");
  5357. params.emplace("note", "coder");
  5358. res = cli_.Put("/person", params);
  5359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5360. ASSERT_EQ(StatusCode::OK_200, res->status);
  5361. res = cli_.Get("/person/john3");
  5362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5363. ASSERT_EQ(StatusCode::OK_200, res->status);
  5364. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5365. ASSERT_EQ("coder", res->body);
  5366. }
  5367. TEST_F(ServerTest, DeleteMethod1) {
  5368. auto res = cli_.Get("/person/john4");
  5369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5370. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5371. Params params;
  5372. params.emplace("name", "john4");
  5373. params.emplace("note", "coder");
  5374. res = cli_.Post("/person", params);
  5375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5376. ASSERT_EQ(StatusCode::OK_200, res->status);
  5377. res = cli_.Get("/person/john4");
  5378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5379. ASSERT_EQ(StatusCode::OK_200, res->status);
  5380. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5381. ASSERT_EQ("coder", res->body);
  5382. Params delete_params;
  5383. delete_params.emplace("name", "john4");
  5384. res = cli_.Delete("/person", delete_params);
  5385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5386. ASSERT_EQ(StatusCode::OK_200, res->status);
  5387. ASSERT_EQ("DELETED", res->body);
  5388. res = cli_.Get("/person/john4");
  5389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5390. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5391. }
  5392. TEST_F(ServerTest, DeleteMethod2) {
  5393. auto res = cli_.Get("/person/john5");
  5394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5395. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5396. Params params;
  5397. params.emplace("name", "john5");
  5398. params.emplace("note", "developer");
  5399. res = cli_.Post("/person", params);
  5400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5401. ASSERT_EQ(StatusCode::OK_200, res->status);
  5402. res = cli_.Get("/person/john5");
  5403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5404. ASSERT_EQ(StatusCode::OK_200, res->status);
  5405. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5406. ASSERT_EQ("developer", res->body);
  5407. Params delete_params;
  5408. delete_params.emplace("name", "john5");
  5409. Headers headers;
  5410. headers.emplace("Custom-Header", "test-value");
  5411. res = cli_.Delete("/person", headers, delete_params);
  5412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5413. ASSERT_EQ(StatusCode::OK_200, res->status);
  5414. ASSERT_EQ("DELETED", res->body);
  5415. res = cli_.Get("/person/john5");
  5416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5417. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5418. }
  5419. TEST_F(ServerTest, DeleteMethod3) {
  5420. auto res = cli_.Get("/person/john6");
  5421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5422. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5423. Params params;
  5424. params.emplace("name", "john6");
  5425. params.emplace("note", "tester");
  5426. res = cli_.Post("/person", params);
  5427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5428. ASSERT_EQ(StatusCode::OK_200, res->status);
  5429. res = cli_.Get("/person/john6");
  5430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5431. ASSERT_EQ(StatusCode::OK_200, res->status);
  5432. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5433. ASSERT_EQ("tester", res->body);
  5434. Params delete_params;
  5435. delete_params.emplace("name", "john6");
  5436. Headers headers;
  5437. headers.emplace("Custom-Header", "test-value");
  5438. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5440. ASSERT_EQ(StatusCode::OK_200, res->status);
  5441. ASSERT_EQ("DELETED", res->body);
  5442. res = cli_.Get("/person/john6");
  5443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5444. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5445. }
  5446. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5447. Params params;
  5448. params.emplace("json", JSON_DATA);
  5449. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5451. ASSERT_EQ(StatusCode::OK_200, res->status);
  5452. ASSERT_EQ(JSON_DATA, res->body);
  5453. }
  5454. TEST_F(ServerTest, PostEmptyContent) {
  5455. auto res = cli_.Post("/empty", "", "text/plain");
  5456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5457. ASSERT_EQ(StatusCode::OK_200, res->status);
  5458. ASSERT_EQ("empty", res->body);
  5459. }
  5460. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5461. auto res = cli_.Post("/empty-no-content-type");
  5462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5463. ASSERT_EQ(StatusCode::OK_200, res->status);
  5464. ASSERT_EQ("empty-no-content-type", res->body);
  5465. }
  5466. TEST_F(ServerTest, PostPathOnly) {
  5467. auto res = cli_.Post("/path-only");
  5468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5469. ASSERT_EQ(StatusCode::OK_200, res->status);
  5470. ASSERT_EQ("path-only", res->body);
  5471. }
  5472. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5473. auto res = cli_.Post("/path-headers-only",
  5474. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5476. ASSERT_EQ(StatusCode::OK_200, res->status);
  5477. ASSERT_EQ("path-headers-only", res->body);
  5478. }
  5479. TEST_F(ServerTest, PostLarge) {
  5480. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5482. ASSERT_EQ(StatusCode::OK_200, res->status);
  5483. EXPECT_EQ(LARGE_DATA, res->body);
  5484. }
  5485. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5486. auto res = cli_.Put("/empty-no-content-type");
  5487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5488. ASSERT_EQ(StatusCode::OK_200, res->status);
  5489. ASSERT_EQ("empty-no-content-type", res->body);
  5490. }
  5491. TEST_F(ServerTest, GetMethodDir) {
  5492. auto res = cli_.Get("/dir/");
  5493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5494. EXPECT_EQ(StatusCode::OK_200, res->status);
  5495. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5496. auto body = R"(<html>
  5497. <head>
  5498. </head>
  5499. <body>
  5500. <a href="/dir/test.html">Test</a>
  5501. <a href="/hi">hi</a>
  5502. </body>
  5503. </html>
  5504. )";
  5505. EXPECT_EQ(body, res->body);
  5506. }
  5507. TEST_F(ServerTest, GetMethodDirTest) {
  5508. auto res = cli_.Get("/dir/test.html");
  5509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5510. EXPECT_EQ(StatusCode::OK_200, res->status);
  5511. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5512. EXPECT_EQ("test.html", res->body);
  5513. }
  5514. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5515. auto res = cli_.Get("/dir/../dir/test.html");
  5516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5517. EXPECT_EQ(StatusCode::OK_200, res->status);
  5518. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5519. EXPECT_EQ("test.html", res->body);
  5520. }
  5521. TEST_F(ServerTest, GetMethodInvalidPath) {
  5522. auto res = cli_.Get("/dir/../test.html");
  5523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5524. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5525. }
  5526. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5527. auto res = cli_.Get("/../www/dir/test.html");
  5528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5529. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5530. }
  5531. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5532. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5534. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5535. }
  5536. TEST_F(ServerTest, GetMethodDirMountTest) {
  5537. auto res = cli_.Get("/mount/dir/test.html");
  5538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5539. EXPECT_EQ(StatusCode::OK_200, res->status);
  5540. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5541. EXPECT_EQ("test.html", res->body);
  5542. }
  5543. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5544. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5546. EXPECT_EQ(StatusCode::OK_200, res->status);
  5547. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5548. EXPECT_EQ("test.html", res->body);
  5549. }
  5550. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5551. auto res = cli_.Get("/mount/dir/../test.html");
  5552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5553. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5554. }
  5555. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5556. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5558. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5559. }
  5560. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5561. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5563. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5564. }
  5565. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5566. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5568. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5569. }
  5570. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5571. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5573. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5574. }
  5575. TEST_F(ServerTest, PostMethod303) {
  5576. auto res = cli_.Post("/1", "body", "text/plain");
  5577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5578. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5579. EXPECT_EQ("/2", res->get_header_value("Location"));
  5580. }
  5581. TEST_F(ServerTest, PostMethod303Redirect) {
  5582. cli_.set_follow_location(true);
  5583. auto res = cli_.Post("/1", "body", "text/plain");
  5584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5585. EXPECT_EQ(StatusCode::OK_200, res->status);
  5586. EXPECT_EQ("redirected.", res->body);
  5587. EXPECT_EQ("/2", res->location);
  5588. }
  5589. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5590. auto res = cli_.Get("/dir/test.abcde");
  5591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5592. EXPECT_EQ(StatusCode::OK_200, res->status);
  5593. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5594. EXPECT_EQ("abcde", res->body);
  5595. }
  5596. TEST_F(ServerTest, StaticFileRange) {
  5597. auto res =
  5598. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5600. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5601. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5602. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5603. EXPECT_EQ(true, res->has_header("Content-Range"));
  5604. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5605. EXPECT_EQ(std::string("cd"), res->body);
  5606. }
  5607. TEST_F(ServerTest, StaticFileRanges) {
  5608. auto res = cli_.Get("/dir/test.abcde",
  5609. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5611. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5612. EXPECT_TRUE(
  5613. res->get_header_value("Content-Type")
  5614. .find(
  5615. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5616. 0);
  5617. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5618. }
  5619. TEST_F(ServerTest, StaticFileRangeHead) {
  5620. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5622. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5623. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5624. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5625. EXPECT_EQ(true, res->has_header("Content-Range"));
  5626. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5627. }
  5628. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5629. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5631. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5632. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5633. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5634. EXPECT_EQ(true, res->has_header("Content-Range"));
  5635. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5636. res->get_header_value("Content-Range"));
  5637. EXPECT_EQ("LAST\n", res->body);
  5638. }
  5639. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5640. auto res =
  5641. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5643. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5644. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5645. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5646. EXPECT_EQ(true, res->has_header("Content-Range"));
  5647. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5648. }
  5649. TEST_F(ServerTest, StaticFileBigFile) {
  5650. auto res = cli_.Get("/dir/1MB.txt");
  5651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5652. EXPECT_EQ(StatusCode::OK_200, res->status);
  5653. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5654. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5655. }
  5656. TEST_F(ServerTest, InvalidBaseDirMount) {
  5657. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5658. }
  5659. TEST_F(ServerTest, Binary) {
  5660. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5661. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5662. "application/octet-stream");
  5663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5664. ASSERT_EQ(StatusCode::OK_200, res->status);
  5665. ASSERT_EQ(4U, res->body.size());
  5666. res = cli_.Put("/binary", binary.data(), binary.size(),
  5667. "application/octet-stream");
  5668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5669. ASSERT_EQ(StatusCode::OK_200, res->status);
  5670. ASSERT_EQ(4U, res->body.size());
  5671. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5672. "application/octet-stream");
  5673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5674. ASSERT_EQ(StatusCode::OK_200, res->status);
  5675. ASSERT_EQ(4U, res->body.size());
  5676. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5677. "application/octet-stream");
  5678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5679. ASSERT_EQ(StatusCode::OK_200, res->status);
  5680. ASSERT_EQ(4U, res->body.size());
  5681. }
  5682. TEST_F(ServerTest, BinaryString) {
  5683. auto binary = std::string("\x00\x01\x02\x03", 4);
  5684. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5686. ASSERT_EQ(StatusCode::OK_200, res->status);
  5687. ASSERT_EQ(4U, res->body.size());
  5688. res = cli_.Put("/binary", binary, "application/octet-stream");
  5689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5690. ASSERT_EQ(StatusCode::OK_200, res->status);
  5691. ASSERT_EQ(4U, res->body.size());
  5692. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5694. ASSERT_EQ(StatusCode::OK_200, res->status);
  5695. ASSERT_EQ(4U, res->body.size());
  5696. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5698. ASSERT_EQ(StatusCode::OK_200, res->status);
  5699. ASSERT_EQ(4U, res->body.size());
  5700. }
  5701. TEST_F(ServerTest, EmptyRequest) {
  5702. auto res = cli_.Get("");
  5703. ASSERT_TRUE(!res);
  5704. EXPECT_EQ(Error::Connection, res.error());
  5705. }
  5706. TEST_F(ServerTest, LongRequest) {
  5707. std::string request;
  5708. for (size_t i = 0; i < 545; i++) {
  5709. request += "/TooLongRequest";
  5710. }
  5711. request += "OK";
  5712. auto res = cli_.Get(request.c_str());
  5713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5714. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5715. }
  5716. TEST_F(ServerTest, TooLongRequest) {
  5717. std::string request;
  5718. for (size_t i = 0; i < 546; i++) {
  5719. request += "/TooLongRequest";
  5720. }
  5721. request += "_NG";
  5722. auto start = std::chrono::high_resolution_clock::now();
  5723. cli_.set_keep_alive(true);
  5724. auto res = cli_.Get(request.c_str());
  5725. auto end = std::chrono::high_resolution_clock::now();
  5726. auto elapsed =
  5727. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5728. .count();
  5729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5730. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5731. EXPECT_LE(elapsed, 1000);
  5732. EXPECT_EQ("close", res->get_header_value("Connection"));
  5733. EXPECT_FALSE(cli_.is_socket_open());
  5734. }
  5735. TEST_F(ServerTest, AlmostTooLongRequest) {
  5736. // test for #2046 - URI length check shouldn't include other content on req
  5737. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5738. // leading /, space, HTTP/1.1)
  5739. std::string request =
  5740. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5741. auto res = cli_.Get(request.c_str());
  5742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5743. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5744. }
  5745. TEST_F(ServerTest, LongHeader) {
  5746. Request req;
  5747. req.method = "GET";
  5748. req.path = "/hi";
  5749. std::string host_and_port;
  5750. host_and_port += HOST;
  5751. host_and_port += ":";
  5752. host_and_port += std::to_string(PORT);
  5753. req.headers.emplace("Host", host_and_port.c_str());
  5754. req.headers.emplace("Accept", "*/*");
  5755. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5756. req.headers.emplace(
  5757. "Header-Name",
  5758. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5759. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  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. auto res = std::make_shared<Response>();
  5788. auto error = Error::Success;
  5789. auto ret = cli_.send(req, *res, error);
  5790. ASSERT_TRUE(ret);
  5791. EXPECT_EQ(StatusCode::OK_200, res->status);
  5792. }
  5793. TEST_F(ServerTest, LongQueryValue) {
  5794. auto start = std::chrono::high_resolution_clock::now();
  5795. cli_.set_keep_alive(true);
  5796. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5797. auto end = std::chrono::high_resolution_clock::now();
  5798. auto elapsed =
  5799. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5800. .count();
  5801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5802. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5803. EXPECT_LE(elapsed, 1000);
  5804. EXPECT_EQ("close", res->get_header_value("Connection"));
  5805. EXPECT_FALSE(cli_.is_socket_open());
  5806. }
  5807. TEST_F(ServerTest, TooLongQueryValue) {
  5808. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5809. ASSERT_FALSE(res);
  5810. EXPECT_EQ(Error::Read, res.error());
  5811. }
  5812. TEST_F(ServerTest, TooLongHeader) {
  5813. Request req;
  5814. req.method = "GET";
  5815. req.path = "/hi";
  5816. std::string host_and_port;
  5817. host_and_port += HOST;
  5818. host_and_port += ":";
  5819. host_and_port += std::to_string(PORT);
  5820. req.headers.emplace("Host", host_and_port.c_str());
  5821. req.headers.emplace("Accept", "*/*");
  5822. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5823. req.headers.emplace(
  5824. "Header-Name",
  5825. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5826. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  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. auto res = std::make_shared<Response>();
  5855. auto error = Error::Success;
  5856. auto ret = cli_.send(req, *res, error);
  5857. ASSERT_TRUE(ret);
  5858. EXPECT_EQ(StatusCode::OK_200, res->status);
  5859. }
  5860. TEST_F(ServerTest, HeaderCountAtLimit) {
  5861. // Test with headers just under the 100 limit
  5862. httplib::Headers headers;
  5863. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5864. // This should keep us just under the 100 header limit
  5865. for (int i = 0; i < 95; i++) {
  5866. std::string name = "X-Test-Header-" + std::to_string(i);
  5867. std::string value = "value" + std::to_string(i);
  5868. headers.emplace(name, value);
  5869. }
  5870. // This should work fine as we're under the limit
  5871. auto res = cli_.Get("/hi", headers);
  5872. EXPECT_TRUE(res);
  5873. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5874. }
  5875. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5876. // Test with many headers to exceed the 100 limit
  5877. httplib::Headers headers;
  5878. // Add 150 headers to definitely exceed the 100 limit
  5879. for (int i = 0; i < 150; i++) {
  5880. std::string name = "X-Test-Header-" + std::to_string(i);
  5881. std::string value = "value" + std::to_string(i);
  5882. headers.emplace(name, value);
  5883. }
  5884. // This should fail due to exceeding header count limit
  5885. cli_.set_keep_alive(true);
  5886. auto res = cli_.Get("/hi", headers);
  5887. // The server should respond with 400 Bad Request
  5888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5889. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5890. EXPECT_EQ("close", res->get_header_value("Connection"));
  5891. EXPECT_FALSE(cli_.is_socket_open());
  5892. }
  5893. TEST_F(ServerTest, PercentEncoding) {
  5894. auto res = cli_.Get("/e%6edwith%");
  5895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5896. EXPECT_EQ(StatusCode::OK_200, res->status);
  5897. }
  5898. TEST_F(ServerTest, PercentEncodingUnicode) {
  5899. auto res = cli_.Get("/e%u006edwith%");
  5900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5901. EXPECT_EQ(StatusCode::OK_200, res->status);
  5902. }
  5903. TEST_F(ServerTest, InvalidPercentEncoding) {
  5904. auto res = cli_.Get("/%endwith%");
  5905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5906. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5907. }
  5908. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5909. auto res = cli_.Get("/%uendwith%");
  5910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5911. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5912. }
  5913. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5914. auto res = cli_.Get("/hello?aaa=bbb%");
  5915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5916. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5917. }
  5918. TEST_F(ServerTest, PlusSignEncoding) {
  5919. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5921. EXPECT_EQ(StatusCode::OK_200, res->status);
  5922. EXPECT_EQ("a +b", res->body);
  5923. }
  5924. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5925. // This test simulates a potential DoS attack using many headers
  5926. // to verify our security fix prevents memory exhaustion
  5927. httplib::Headers attack_headers;
  5928. // Attempt to add many headers like an attacker would (200 headers to far
  5929. // exceed limit)
  5930. for (int i = 0; i < 200; i++) {
  5931. std::string name = "X-Attack-Header-" + std::to_string(i);
  5932. std::string value = "attack_payload_" + std::to_string(i);
  5933. attack_headers.emplace(name, value);
  5934. }
  5935. // Try to POST with excessive headers
  5936. cli_.set_keep_alive(true);
  5937. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5938. // Should either fail or return 400 Bad Request due to security limit
  5939. if (res) {
  5940. // If we get a response, it should be 400 Bad Request
  5941. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5942. EXPECT_EQ("close", res->get_header_value("Connection"));
  5943. }
  5944. EXPECT_FALSE(cli_.is_socket_open());
  5945. }
  5946. TEST_F(ServerTest, MultipartFormData) {
  5947. UploadFormDataItems items = {
  5948. {"text1", "text default", "", ""},
  5949. {"text2", "aωb", "", ""},
  5950. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5951. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5952. {"file3", "", "", "application/octet-stream"},
  5953. {"file4", "", "", " application/json tmp-string "}};
  5954. auto res = cli_.Post("/multipart", items);
  5955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5956. EXPECT_EQ(StatusCode::OK_200, res->status);
  5957. }
  5958. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5959. UploadFormDataItems items = {
  5960. {"text", "default text", "", ""},
  5961. {"multi_text1", "aaaaa", "", ""},
  5962. {"multi_text1", "bbbbb", "", ""},
  5963. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5964. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5965. "application/json"},
  5966. };
  5967. auto res = cli_.Post("/multipart/multi_file_values", items);
  5968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5969. EXPECT_EQ(StatusCode::OK_200, res->status);
  5970. }
  5971. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5972. auto res = cli_.Get("/hi");
  5973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5974. EXPECT_EQ(StatusCode::OK_200, res->status);
  5975. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5976. EXPECT_EQ("Hello World!", res->body);
  5977. }
  5978. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5979. Request req;
  5980. req.method = "POST";
  5981. req.path = "/chunked";
  5982. std::string host_and_port;
  5983. host_and_port += HOST;
  5984. host_and_port += ":";
  5985. host_and_port += std::to_string(PORT);
  5986. req.headers.emplace("Host", host_and_port.c_str());
  5987. req.headers.emplace("Accept", "*/*");
  5988. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5989. req.headers.emplace("Content-Type", "text/plain");
  5990. req.headers.emplace("Content-Length", "0");
  5991. req.headers.emplace(
  5992. "Transfer-Encoding",
  5993. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5994. // Client does not chunk, so make a chunked body manually.
  5995. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5996. auto res = std::make_shared<Response>();
  5997. auto error = Error::Success;
  5998. auto ret = cli_.send(req, *res, error);
  5999. ASSERT_TRUE(ret);
  6000. EXPECT_EQ(StatusCode::OK_200, res->status);
  6001. }
  6002. template <typename ClientT>
  6003. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6004. int expected_status) {
  6005. Request req;
  6006. req.method = "POST";
  6007. req.path = "/chunked";
  6008. std::string host_and_port;
  6009. host_and_port += HOST;
  6010. host_and_port += ":";
  6011. host_and_port += std::to_string(PORT);
  6012. req.headers.emplace("Host", host_and_port.c_str());
  6013. req.headers.emplace("Content-Length", "0");
  6014. req.headers.emplace("Transfer-Encoding", "chunked");
  6015. req.body = body;
  6016. auto res = std::make_shared<Response>();
  6017. auto error = Error::Success;
  6018. ASSERT_TRUE(cli.send(req, *res, error));
  6019. EXPECT_EQ(expected_status, res->status);
  6020. }
  6021. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6022. // rather than treat them as valid lengths.
  6023. template <typename ClientT>
  6024. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6025. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6026. }
  6027. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6028. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6029. }
  6030. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6031. expect_chunked_body_rejected(
  6032. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6033. }
  6034. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6035. // chunk-size line carries no CR, LF or other control character ahead of its
  6036. // terminator. Such a line must be refused rather than read as extension text.
  6037. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6038. expect_chunked_body_rejected(
  6039. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6040. }
  6041. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6042. expect_chunked_body_rejected(
  6043. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6044. }
  6045. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6046. expect_chunked_body_rejected(
  6047. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6048. }
  6049. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6050. // The literal stays split: a hex escape consumes every hex digit that
  6051. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6052. expect_chunked_body_rejected(
  6053. cli_, "4;a\x01"
  6054. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6055. }
  6056. TEST_F(ServerTest, AcceptsChunkExtension) {
  6057. expect_chunked_body_status(cli_,
  6058. "4;name=value\r\ndech\r\n"
  6059. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6060. "0;last\r\n\r\n",
  6061. StatusCode::OK_200);
  6062. }
  6063. TEST_F(ServerTest, GetStreamed2) {
  6064. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6066. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6067. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6068. EXPECT_EQ(true, res->has_header("Content-Range"));
  6069. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6070. EXPECT_EQ(std::string("ab"), res->body);
  6071. }
  6072. TEST_F(ServerTest, GetStreamed) {
  6073. auto res = cli_.Get("/streamed");
  6074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6075. EXPECT_EQ(StatusCode::OK_200, res->status);
  6076. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6077. EXPECT_EQ(std::string("aaabbb"), res->body);
  6078. }
  6079. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6080. auto res = cli_.Get("/streamed-without-length",
  6081. Headers{make_range_header({{0, -1}})});
  6082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6083. EXPECT_EQ(StatusCode::OK_200, res->status);
  6084. EXPECT_EQ(false, res->has_header("Content-Length"));
  6085. EXPECT_EQ(false, res->has_header("Content-Range"));
  6086. EXPECT_EQ(std::string("abcdefg"), res->body);
  6087. }
  6088. TEST_F(ServerTest, GetStreamedWithRange1) {
  6089. auto res =
  6090. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6092. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6093. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6094. EXPECT_EQ(true, res->has_header("Content-Range"));
  6095. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6096. EXPECT_EQ(std::string("def"), res->body);
  6097. }
  6098. TEST_F(ServerTest, GetStreamedWithRange2) {
  6099. auto res =
  6100. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6102. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6103. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6104. EXPECT_EQ(true, res->has_header("Content-Range"));
  6105. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6106. EXPECT_EQ(std::string("bcdefg"), res->body);
  6107. }
  6108. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6109. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6111. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6112. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6113. EXPECT_EQ(true, res->has_header("Content-Range"));
  6114. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6115. EXPECT_EQ(std::string("efg"), res->body);
  6116. }
  6117. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6118. auto res =
  6119. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  6120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6121. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6122. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6123. EXPECT_EQ(false, res->has_header("Content-Range"));
  6124. EXPECT_EQ(0U, res->body.size());
  6125. }
  6126. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6127. // Only a 206 is served as a partial representation. Under any other status
  6128. // `apply_ranges()` reported the full content length, so the body must match
  6129. // that header, and the content provider must never be asked for an offset
  6130. // outside the representation.
  6131. auto check = [&](int status, const char *range) {
  6132. auto path =
  6133. std::string("/streamed-with-range?status=") + std::to_string(status);
  6134. auto ctx = path + " Range: " + range;
  6135. auto res = cli_.Get(path, Headers{{"Range", range}});
  6136. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6137. EXPECT_EQ(status, res->status) << ctx;
  6138. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6139. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6140. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6141. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6142. };
  6143. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6144. check(403, "bytes=3-5");
  6145. // The offset is far past the representation.
  6146. check(403, "bytes=100000-100200");
  6147. // `first_pos` is still -1 here, and the bounds asserts in
  6148. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6149. check(403, "bytes=-3");
  6150. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6151. // multipart branch would have written one that is empty.
  6152. check(403, "bytes=1-2, 4-5");
  6153. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6154. // covers the whole representation.
  6155. check(200, "bytes=3-5");
  6156. check(200, "bytes=1-2, 4-5");
  6157. }
  6158. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6159. auto res =
  6160. cli_.Get("/streamed-with-range",
  6161. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6162. "92233720368547758079223372036854775807"}});
  6163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6164. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6165. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6166. EXPECT_EQ(false, res->has_header("Content-Range"));
  6167. EXPECT_EQ(0U, res->body.size());
  6168. }
  6169. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6170. auto res = cli_.Get(
  6171. "/with-range",
  6172. Headers{{"Range",
  6173. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6174. {"Accept-Encoding", ""}});
  6175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6176. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6177. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6178. EXPECT_EQ(true, res->has_header("Content-Range"));
  6179. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6180. EXPECT_EQ(std::string("abcdefg"), res->body);
  6181. }
  6182. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6183. auto res = cli_.Get("/with-range", Headers{
  6184. {"Range", "bytes=0-"},
  6185. {"Accept-Encoding", ""},
  6186. });
  6187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6188. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6189. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6190. EXPECT_EQ(true, res->has_header("Content-Range"));
  6191. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6192. EXPECT_EQ(std::string("abcdefg"), res->body);
  6193. }
  6194. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6195. auto res = cli_.Get("/streamed-with-range",
  6196. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6198. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6199. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6200. EXPECT_EQ(false, res->has_header("Content-Range"));
  6201. EXPECT_EQ(267U, res->body.size());
  6202. // Check that both range contents are present
  6203. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6204. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6205. // Check that Content-Range headers are present for both ranges
  6206. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6207. std::string::npos);
  6208. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6209. std::string::npos);
  6210. }
  6211. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6212. Ranges ranges;
  6213. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6214. ranges.emplace_back(0, -1);
  6215. }
  6216. auto res = cli_.Get("/streamed-with-range?error",
  6217. Headers{{make_range_header(ranges)}});
  6218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6219. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6220. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6221. EXPECT_EQ(false, res->has_header("Content-Range"));
  6222. EXPECT_EQ(0U, res->body.size());
  6223. }
  6224. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6225. auto res = cli_.Get("/streamed-with-range",
  6226. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6228. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6229. EXPECT_EQ(5U, res->body.size());
  6230. // Check that overlapping ranges are coalesced into a single range
  6231. EXPECT_EQ("bcdef", res->body);
  6232. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6233. // Should be single range, not multipart
  6234. EXPECT_TRUE(res->has_header("Content-Range"));
  6235. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6236. }
  6237. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6238. auto res = cli_.Get("/streamed-with-range",
  6239. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6241. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6242. EXPECT_EQ(268U, res->body.size());
  6243. // Check that both range contents are present
  6244. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6245. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6246. // Check that Content-Range headers are present for both ranges
  6247. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6248. std::string::npos);
  6249. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6250. std::string::npos);
  6251. }
  6252. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6253. auto res = cli_.Get("/streamed-with-range",
  6254. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6256. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6257. EXPECT_EQ(269U, res->body.size());
  6258. // Check that both duplicate range contents are present
  6259. size_t first_abc = res->body.find("abc\r\n");
  6260. EXPECT_TRUE(first_abc != std::string::npos);
  6261. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6262. EXPECT_TRUE(second_abc != std::string::npos);
  6263. // Check that Content-Range headers are present for both ranges
  6264. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6265. EXPECT_TRUE(first_range != std::string::npos);
  6266. size_t second_range =
  6267. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6268. EXPECT_TRUE(second_range != std::string::npos);
  6269. }
  6270. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6271. auto res =
  6272. cli_.Get("/streamed-with-range?error",
  6273. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6275. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6276. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6277. EXPECT_EQ(false, res->has_header("Content-Range"));
  6278. EXPECT_EQ(0U, res->body.size());
  6279. }
  6280. TEST_F(ServerTest, GetStreamedEndless) {
  6281. uint64_t offset = 0;
  6282. auto res = cli_.Get("/streamed-cancel",
  6283. [&](const char * /*data*/, uint64_t data_length) {
  6284. if (offset < 100) {
  6285. offset += data_length;
  6286. return true;
  6287. }
  6288. return false;
  6289. });
  6290. ASSERT_TRUE(!res);
  6291. EXPECT_EQ(Error::Canceled, res.error());
  6292. }
  6293. TEST_F(ServerTest, ClientStop) {
  6294. std::atomic_size_t count{4};
  6295. std::vector<std::thread> threads;
  6296. for (auto i = count.load(); i != 0; --i) {
  6297. threads.emplace_back([&]() {
  6298. auto res = cli_.Get("/streamed-cancel",
  6299. [&](const char *, uint64_t) { return true; });
  6300. --count;
  6301. ASSERT_TRUE(!res);
  6302. EXPECT_TRUE(res.error() == Error::Canceled ||
  6303. res.error() == Error::Read || res.error() == Error::Write);
  6304. });
  6305. }
  6306. std::this_thread::sleep_for(std::chrono::seconds(2));
  6307. while (count != 0) {
  6308. cli_.stop();
  6309. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6310. }
  6311. for (auto &t : threads) {
  6312. t.join();
  6313. }
  6314. }
  6315. TEST_F(ServerTest, GetWithRange1) {
  6316. auto res = cli_.Get("/with-range", Headers{
  6317. make_range_header({{3, 5}}),
  6318. {"Accept-Encoding", ""},
  6319. });
  6320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6321. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6322. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6323. EXPECT_EQ(true, res->has_header("Content-Range"));
  6324. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6325. EXPECT_EQ(std::string("def"), res->body);
  6326. }
  6327. TEST_F(ServerTest, GetWithRange2) {
  6328. auto res = cli_.Get("/with-range", Headers{
  6329. make_range_header({{1, -1}}),
  6330. {"Accept-Encoding", ""},
  6331. });
  6332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6333. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6334. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6335. EXPECT_EQ(true, res->has_header("Content-Range"));
  6336. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6337. EXPECT_EQ(std::string("bcdefg"), res->body);
  6338. }
  6339. TEST_F(ServerTest, GetWithRange3) {
  6340. auto res = cli_.Get("/with-range", Headers{
  6341. make_range_header({{0, 0}}),
  6342. {"Accept-Encoding", ""},
  6343. });
  6344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6345. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6346. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6347. EXPECT_EQ(true, res->has_header("Content-Range"));
  6348. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6349. EXPECT_EQ(std::string("a"), res->body);
  6350. }
  6351. TEST_F(ServerTest, GetWithRange4) {
  6352. auto res = cli_.Get("/with-range", Headers{
  6353. make_range_header({{-1, 2}}),
  6354. {"Accept-Encoding", ""},
  6355. });
  6356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6357. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6358. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6359. EXPECT_EQ(true, res->has_header("Content-Range"));
  6360. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6361. EXPECT_EQ(std::string("fg"), res->body);
  6362. }
  6363. TEST_F(ServerTest, GetWithRange5) {
  6364. auto res = cli_.Get("/with-range", Headers{
  6365. make_range_header({{0, 5}}),
  6366. {"Accept-Encoding", ""},
  6367. });
  6368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6369. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6370. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6371. EXPECT_EQ(true, res->has_header("Content-Range"));
  6372. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6373. EXPECT_EQ(std::string("abcdef"), res->body);
  6374. }
  6375. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6376. auto res =
  6377. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6379. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6380. }
  6381. TEST_F(ServerTest, GetWithRangeMultipart) {
  6382. auto res =
  6383. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6385. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6386. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6387. EXPECT_EQ(false, res->has_header("Content-Range"));
  6388. EXPECT_EQ(267U, res->body.size());
  6389. }
  6390. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6391. auto res = cli_.Get("/with-range",
  6392. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6394. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6395. }
  6396. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6397. auto res = cli_.Get("/with-range-customized-response",
  6398. Headers{{make_range_header({{1, 2}})}});
  6399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6400. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6401. EXPECT_EQ(true, res->has_header("Content-Length"));
  6402. EXPECT_EQ(false, res->has_header("Content-Range"));
  6403. EXPECT_EQ(JSON_DATA, res->body);
  6404. }
  6405. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6406. auto res = cli_.Get("/with-range-customized-response",
  6407. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6409. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6410. EXPECT_EQ(true, res->has_header("Content-Length"));
  6411. EXPECT_EQ(false, res->has_header("Content-Range"));
  6412. EXPECT_EQ(JSON_DATA, res->body);
  6413. }
  6414. TEST_F(ServerTest, Issue1772) {
  6415. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6417. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6418. }
  6419. TEST_F(ServerTest, Issue609) {
  6420. auto res = cli_.Delete("/issue609");
  6421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6422. EXPECT_EQ(StatusCode::OK_200, res->status);
  6423. EXPECT_EQ(std::string("ok"), res->body);
  6424. }
  6425. TEST_F(ServerTest, GetStreamedChunked) {
  6426. auto res = cli_.Get("/streamed-chunked");
  6427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6428. EXPECT_EQ(StatusCode::OK_200, res->status);
  6429. EXPECT_EQ(std::string("123456789"), res->body);
  6430. }
  6431. TEST_F(ServerTest, GetStreamedChunked2) {
  6432. auto res = cli_.Get("/streamed-chunked2");
  6433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6434. EXPECT_EQ(StatusCode::OK_200, res->status);
  6435. EXPECT_EQ(std::string("123456789"), res->body);
  6436. }
  6437. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6438. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6440. EXPECT_EQ(StatusCode::OK_200, res->status);
  6441. EXPECT_EQ(std::string("123456789"), res->body);
  6442. EXPECT_TRUE(res->has_header("Trailer"));
  6443. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6444. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6445. // Trailers are now stored separately from headers (security fix)
  6446. EXPECT_EQ(2U, res->trailers.size());
  6447. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6448. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6449. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6450. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6451. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6452. // Verify trailers are NOT in headers (security verification)
  6453. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6454. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6455. }
  6456. TEST_F(ServerTest, LargeChunkedPost) {
  6457. Request req;
  6458. req.method = "POST";
  6459. req.path = "/large-chunked";
  6460. std::string host_and_port;
  6461. host_and_port += HOST;
  6462. host_and_port += ":";
  6463. host_and_port += std::to_string(PORT);
  6464. req.headers.emplace("Host", host_and_port.c_str());
  6465. req.headers.emplace("Accept", "*/*");
  6466. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6467. req.headers.emplace("Content-Type", "text/plain");
  6468. req.headers.emplace("Content-Length", "0");
  6469. req.headers.emplace("Transfer-Encoding", "chunked");
  6470. std::string long_string(30 * 1024u, 'a');
  6471. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6472. // Attempt to make a large enough post to exceed OS buffers, to test that
  6473. // the server handles short reads if the full chunk data isn't available.
  6474. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6475. auto res = std::make_shared<Response>();
  6476. auto error = Error::Success;
  6477. auto ret = cli_.send(req, *res, error);
  6478. ASSERT_TRUE(ret);
  6479. EXPECT_EQ(StatusCode::OK_200, res->status);
  6480. }
  6481. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6482. auto res = cli_.Get("/remote_addr");
  6483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6484. EXPECT_EQ(StatusCode::OK_200, res->status);
  6485. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6486. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6487. }
  6488. TEST_F(ServerTest, GetMethodLocalAddr) {
  6489. auto res = cli_.Get("/local_addr");
  6490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6491. EXPECT_EQ(StatusCode::OK_200, res->status);
  6492. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6493. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6494. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6495. }
  6496. TEST_F(ServerTest, HTTPResponseSplitting) {
  6497. auto res = cli_.Get("/http_response_splitting");
  6498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6499. EXPECT_EQ(StatusCode::OK_200, res->status);
  6500. }
  6501. TEST_F(ServerTest, SlowRequest) {
  6502. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6503. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6504. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6505. }
  6506. #if 0
  6507. TEST_F(ServerTest, SlowPost) {
  6508. char buffer[64 * 1024];
  6509. memset(buffer, 0x42, sizeof(buffer));
  6510. auto res = cli_.Post(
  6511. "/slowpost", 64 * 1024 * 1024,
  6512. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6513. auto ret = sink.write(buffer, sizeof(buffer));
  6514. EXPECT_TRUE(ret);
  6515. return true;
  6516. },
  6517. "text/plain");
  6518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6519. EXPECT_EQ(StatusCode::OK_200, res->status);
  6520. }
  6521. TEST_F(ServerTest, SlowPostFail) {
  6522. char buffer[64 * 1024];
  6523. memset(buffer, 0x42, sizeof(buffer));
  6524. cli_.set_write_timeout(std::chrono::seconds(0));
  6525. auto res = cli_.Post(
  6526. "/slowpost", 64 * 1024 * 1024,
  6527. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6528. sink.write(buffer, sizeof(buffer));
  6529. return true;
  6530. },
  6531. "text/plain");
  6532. ASSERT_TRUE(!res);
  6533. EXPECT_EQ(Error::Write, res.error());
  6534. }
  6535. #endif
  6536. TEST_F(ServerTest, Put) {
  6537. auto res = cli_.Put("/put", "PUT", "text/plain");
  6538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6539. EXPECT_EQ(StatusCode::OK_200, res->status);
  6540. EXPECT_EQ("PUT", res->body);
  6541. }
  6542. TEST_F(ServerTest, PutWithContentProvider) {
  6543. auto res = cli_.Put(
  6544. "/put", 3,
  6545. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6546. sink.os << "PUT";
  6547. return true;
  6548. },
  6549. "text/plain");
  6550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6551. EXPECT_EQ(StatusCode::OK_200, res->status);
  6552. EXPECT_EQ("PUT", res->body);
  6553. }
  6554. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6555. auto res = cli_.Post(
  6556. "/post", 42,
  6557. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6558. return false;
  6559. },
  6560. "text/plain");
  6561. ASSERT_TRUE(!res);
  6562. EXPECT_EQ(Error::Canceled, res.error());
  6563. }
  6564. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6565. auto res = cli_.Put(
  6566. "/put",
  6567. [](size_t /*offset*/, DataSink &sink) {
  6568. sink.os << "PUT";
  6569. sink.done();
  6570. return true;
  6571. },
  6572. "text/plain");
  6573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6574. EXPECT_EQ(StatusCode::OK_200, res->status);
  6575. EXPECT_EQ("PUT", res->body);
  6576. }
  6577. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6578. auto res = cli_.Post(
  6579. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6580. "text/plain");
  6581. ASSERT_TRUE(!res);
  6582. EXPECT_EQ(Error::Canceled, res.error());
  6583. }
  6584. TEST_F(ServerTest, PostLoopBack) {
  6585. std::string body;
  6586. auto res = cli_.Post(
  6587. "/post-loopback", 9,
  6588. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6589. EXPECT_EQ(9u, length);
  6590. sink.write("123", 3);
  6591. sink.write("456", 3);
  6592. sink.write("789", 3);
  6593. return true;
  6594. },
  6595. "text/plain",
  6596. [&body](const char *data, size_t data_length) {
  6597. body.append(data, data_length);
  6598. return true;
  6599. });
  6600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6601. EXPECT_EQ(StatusCode::OK_200, res->status);
  6602. EXPECT_EQ("123456789", body);
  6603. }
  6604. TEST_F(ServerTest, PutLoopBack) {
  6605. std::string body;
  6606. auto res = cli_.Put(
  6607. "/put-loopback", 9,
  6608. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6609. EXPECT_EQ(9u, length);
  6610. sink.write("123", 3);
  6611. sink.write("456", 3);
  6612. sink.write("789", 3);
  6613. return true;
  6614. },
  6615. "text/plain",
  6616. [&body](const char *data, size_t data_length) {
  6617. body.append(data, data_length);
  6618. return true;
  6619. });
  6620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6621. EXPECT_EQ(StatusCode::OK_200, res->status);
  6622. EXPECT_EQ("123456789", body);
  6623. }
  6624. TEST_F(ServerTest, PatchLoopBack) {
  6625. std::string body;
  6626. auto res = cli_.Patch(
  6627. "/patch-loopback", 9,
  6628. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6629. EXPECT_EQ(9u, length);
  6630. sink.write("123", 3);
  6631. sink.write("456", 3);
  6632. sink.write("789", 3);
  6633. return true;
  6634. },
  6635. "text/plain",
  6636. [&body](const char *data, size_t data_length) {
  6637. body.append(data, data_length);
  6638. return true;
  6639. });
  6640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6641. EXPECT_EQ(StatusCode::OK_200, res->status);
  6642. EXPECT_EQ("123456789", body);
  6643. }
  6644. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6645. std::string body;
  6646. auto res = cli_.Post(
  6647. "/post-loopback",
  6648. [](size_t /*offset*/, DataSink &sink) {
  6649. sink.write("123", 3);
  6650. sink.write("456", 3);
  6651. sink.write("789", 3);
  6652. sink.done();
  6653. return true;
  6654. },
  6655. "text/plain",
  6656. [&body](const char *data, size_t data_length) {
  6657. body.append(data, data_length);
  6658. return true;
  6659. });
  6660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6661. EXPECT_EQ(StatusCode::OK_200, res->status);
  6662. EXPECT_EQ("123456789", body);
  6663. }
  6664. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6665. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6666. cli_.set_compress(true);
  6667. auto res = cli_.Put(
  6668. "/put", 3,
  6669. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6670. sink.os << "PUT";
  6671. return true;
  6672. },
  6673. "text/plain");
  6674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6675. EXPECT_EQ(StatusCode::OK_200, res->status);
  6676. EXPECT_EQ("PUT", res->body);
  6677. }
  6678. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6679. cli_.set_compress(true);
  6680. auto res = cli_.Post(
  6681. "/post", 42,
  6682. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6683. return false;
  6684. },
  6685. "text/plain");
  6686. ASSERT_TRUE(!res);
  6687. EXPECT_EQ(Error::Canceled, res.error());
  6688. }
  6689. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6690. cli_.set_compress(true);
  6691. auto res = cli_.Put(
  6692. "/put",
  6693. [](size_t /*offset*/, DataSink &sink) {
  6694. sink.os << "PUT";
  6695. sink.done();
  6696. return true;
  6697. },
  6698. "text/plain");
  6699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6700. EXPECT_EQ(StatusCode::OK_200, res->status);
  6701. EXPECT_EQ("PUT", res->body);
  6702. }
  6703. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6704. cli_.set_compress(true);
  6705. auto res = cli_.Post(
  6706. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6707. "text/plain");
  6708. ASSERT_TRUE(!res);
  6709. EXPECT_EQ(Error::Canceled, res.error());
  6710. }
  6711. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6712. cli_.set_compress(true);
  6713. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6715. EXPECT_EQ(StatusCode::OK_200, res->status);
  6716. EXPECT_EQ(LARGE_DATA, res->body);
  6717. }
  6718. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6719. #ifdef CPPHTTPLIB_SSL_ENABLED
  6720. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6721. Client cli(s.c_str());
  6722. cli.enable_server_certificate_verification(false);
  6723. #else
  6724. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6725. Client cli(s.c_str());
  6726. #endif
  6727. cli.set_compress(true);
  6728. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6730. EXPECT_EQ(StatusCode::OK_200, res->status);
  6731. EXPECT_EQ(LARGE_DATA, res->body);
  6732. // The compressed size should be less than a 10th of the original. May vary
  6733. // depending on the zlib library.
  6734. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6735. static_cast<uint64_t>(10 * 1024 * 1024));
  6736. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6737. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6738. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6739. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6740. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6741. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6742. #endif
  6743. }
  6744. TEST_F(ServerTest, PutContentWithDeflate) {
  6745. cli_.set_compress(false);
  6746. Headers headers;
  6747. headers.emplace("Content-Encoding", "deflate");
  6748. // PUT in deflate format:
  6749. auto res = cli_.Put("/put", headers,
  6750. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6752. EXPECT_EQ(StatusCode::OK_200, res->status);
  6753. EXPECT_EQ("PUT", res->body);
  6754. }
  6755. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6756. Headers headers;
  6757. headers.emplace("Accept-Encoding", "gzip, deflate");
  6758. auto res = cli_.Get("/streamed-chunked", headers);
  6759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6760. EXPECT_EQ(StatusCode::OK_200, res->status);
  6761. EXPECT_EQ(std::string("123456789"), res->body);
  6762. }
  6763. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6764. Headers headers;
  6765. headers.emplace("Accept-Encoding", "gzip, deflate");
  6766. auto res = cli_.Get("/streamed-chunked2", headers);
  6767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6768. EXPECT_EQ(StatusCode::OK_200, res->status);
  6769. EXPECT_EQ(std::string("123456789"), res->body);
  6770. }
  6771. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6772. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6774. EXPECT_EQ(StatusCode::OK_200, res->status);
  6775. }
  6776. TEST(GzipDecompressor, ChunkedDecompression) {
  6777. std::string data;
  6778. for (size_t i = 0; i < 32 * 1024; ++i) {
  6779. data.push_back(static_cast<char>('a' + i % 26));
  6780. }
  6781. std::string compressed_data;
  6782. {
  6783. httplib::detail::gzip_compressor compressor;
  6784. bool result = compressor.compress(
  6785. data.data(), data.size(),
  6786. /*last=*/true,
  6787. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6788. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6789. compressed_data_size);
  6790. return true;
  6791. });
  6792. ASSERT_TRUE(result);
  6793. }
  6794. std::string decompressed_data;
  6795. {
  6796. httplib::detail::gzip_decompressor decompressor;
  6797. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6798. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6799. size_t chunk_size = 130;
  6800. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6801. chunk_begin += chunk_size) {
  6802. size_t current_chunk_size =
  6803. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6804. bool result = decompressor.decompress(
  6805. compressed_data.data() + chunk_begin, current_chunk_size,
  6806. [&](const char *decompressed_data_chunk,
  6807. size_t decompressed_data_chunk_size) {
  6808. decompressed_data.insert(decompressed_data.size(),
  6809. decompressed_data_chunk,
  6810. decompressed_data_chunk_size);
  6811. return true;
  6812. });
  6813. ASSERT_TRUE(result);
  6814. }
  6815. }
  6816. ASSERT_EQ(data, decompressed_data);
  6817. }
  6818. TEST(GzipDecompressor, DeflateDecompression) {
  6819. std::string original_text = "Raw deflate without gzip";
  6820. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6821. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6822. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6823. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6824. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6825. std::string decompressed_data;
  6826. {
  6827. httplib::detail::gzip_decompressor decompressor;
  6828. bool result = decompressor.decompress(
  6829. compressed_data.data(), compressed_data.size(),
  6830. [&](const char *decompressed_data_chunk,
  6831. size_t decompressed_data_chunk_size) {
  6832. decompressed_data.insert(decompressed_data.size(),
  6833. decompressed_data_chunk,
  6834. decompressed_data_chunk_size);
  6835. return true;
  6836. });
  6837. ASSERT_TRUE(result);
  6838. }
  6839. ASSERT_EQ(original_text, decompressed_data);
  6840. }
  6841. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6842. std::string original_text = "Raw deflate without gzip";
  6843. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6844. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6845. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6846. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6847. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6848. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6849. std::string decompressed_data;
  6850. {
  6851. httplib::detail::gzip_decompressor decompressor;
  6852. bool result = decompressor.decompress(
  6853. compressed_data.data(), compressed_data.size(),
  6854. [&](const char *decompressed_data_chunk,
  6855. size_t decompressed_data_chunk_size) {
  6856. decompressed_data.insert(decompressed_data.size(),
  6857. decompressed_data_chunk,
  6858. decompressed_data_chunk_size);
  6859. return true;
  6860. });
  6861. ASSERT_TRUE(result);
  6862. }
  6863. ASSERT_EQ(original_text, decompressed_data);
  6864. }
  6865. #endif
  6866. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6867. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6868. Headers headers;
  6869. headers.emplace("Accept-Encoding", "br");
  6870. auto res = cli_.Get("/streamed-chunked", headers);
  6871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6872. EXPECT_EQ(StatusCode::OK_200, res->status);
  6873. EXPECT_EQ(std::string("123456789"), res->body);
  6874. }
  6875. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6876. Headers headers;
  6877. headers.emplace("Accept-Encoding", "br");
  6878. auto res = cli_.Get("/streamed-chunked2", headers);
  6879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6880. EXPECT_EQ(StatusCode::OK_200, res->status);
  6881. EXPECT_EQ(std::string("123456789"), res->body);
  6882. }
  6883. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6884. cli_.set_compress(true);
  6885. auto res = cli_.Put(
  6886. "/put", 3,
  6887. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6888. sink.os << "PUT";
  6889. return true;
  6890. },
  6891. "text/plain");
  6892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6893. EXPECT_EQ(StatusCode::OK_200, res->status);
  6894. EXPECT_EQ("PUT", res->body);
  6895. }
  6896. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6897. cli_.set_compress(true);
  6898. auto res = cli_.Put(
  6899. "/put",
  6900. [](size_t /*offset*/, DataSink &sink) {
  6901. sink.os << "PUT";
  6902. sink.done();
  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, PutLargeFileWithBrotli) {
  6911. cli_.set_compress(true);
  6912. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6914. EXPECT_EQ(StatusCode::OK_200, res->status);
  6915. EXPECT_EQ(LARGE_DATA, res->body);
  6916. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6917. }
  6918. #endif
  6919. TEST_F(ServerTest, Patch) {
  6920. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6922. EXPECT_EQ(StatusCode::OK_200, res->status);
  6923. EXPECT_EQ("PATCH", res->body);
  6924. }
  6925. TEST_F(ServerTest, Delete) {
  6926. auto res = cli_.Delete("/delete");
  6927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6928. EXPECT_EQ(StatusCode::OK_200, res->status);
  6929. EXPECT_EQ("DELETE", res->body);
  6930. }
  6931. TEST_F(ServerTest, DeleteContentReceiver) {
  6932. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6934. EXPECT_EQ(StatusCode::OK_200, res->status);
  6935. EXPECT_EQ("content", res->body);
  6936. }
  6937. TEST_F(ServerTest, Options) {
  6938. auto res = cli_.Options("*");
  6939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6940. EXPECT_EQ(StatusCode::OK_200, res->status);
  6941. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6942. EXPECT_TRUE(res->body.empty());
  6943. }
  6944. TEST_F(ServerTest, URL) {
  6945. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6947. EXPECT_EQ(StatusCode::OK_200, res->status);
  6948. }
  6949. TEST_F(ServerTest, ArrayParam) {
  6950. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6952. EXPECT_EQ(StatusCode::OK_200, res->status);
  6953. }
  6954. TEST_F(ServerTest, ArrayParamValues) {
  6955. auto res =
  6956. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6958. EXPECT_EQ(StatusCode::OK_200, res->status);
  6959. }
  6960. TEST_F(ServerTest, NoMultipleHeaders) {
  6961. Headers headers = {{"Content-Length", "5"}};
  6962. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6963. "text/plain");
  6964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6965. EXPECT_EQ(StatusCode::OK_200, res->status);
  6966. }
  6967. TEST_F(ServerTest, PostContentReceiver) {
  6968. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6970. ASSERT_EQ(StatusCode::OK_200, res->status);
  6971. ASSERT_EQ("content", res->body);
  6972. }
  6973. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6974. UploadFormDataItems items = {
  6975. {"text1", "text default", "", ""},
  6976. {"text2", "aωb", "", ""},
  6977. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6978. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6979. {"file3", "", "", "application/octet-stream"},
  6980. };
  6981. auto res = cli_.Post("/content_receiver", items);
  6982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6983. EXPECT_EQ(StatusCode::OK_200, res->status);
  6984. }
  6985. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6986. UploadFormDataItems items = {
  6987. {"text1", "text default", "", ""},
  6988. {"text2", "aωb", "", ""},
  6989. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6990. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6991. {"file3", "", "", "application/octet-stream"},
  6992. };
  6993. auto boundary = std::string("+++++");
  6994. std::string body;
  6995. for (const auto &item : items) {
  6996. body += "--" + boundary + "\r\n";
  6997. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6998. if (!item.filename.empty()) {
  6999. body += "; filename=\"" + item.filename + "\"";
  7000. }
  7001. body += "\r\n";
  7002. if (!item.content_type.empty()) {
  7003. body += "Content-Type: " + item.content_type + "\r\n";
  7004. }
  7005. body += "\r\n";
  7006. body += item.content + "\r\n";
  7007. }
  7008. body += "--" + boundary + "--\r\n";
  7009. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7010. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7012. EXPECT_EQ(StatusCode::OK_200, res->status);
  7013. }
  7014. TEST(MultipartFormDataTest, FieldEscaping) {
  7015. Server svr;
  7016. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7017. const ContentReader &content_reader) {
  7018. ASSERT_TRUE(req.is_multipart_form_data());
  7019. std::vector<FormData> received;
  7020. content_reader(
  7021. [&](const FormData &file) {
  7022. received.push_back(file);
  7023. return true;
  7024. },
  7025. [&](const char *data, size_t data_length) {
  7026. received.back().content.append(data, data_length);
  7027. return true;
  7028. });
  7029. // '"', CR and LF in names and filenames are escaped following the
  7030. // WHATWG HTML standard, so each part still parses as a single part
  7031. // with no injected headers. Content types get CR/LF escaped too,
  7032. // while '"' (legal there, e.g. quoted charset) is preserved.
  7033. ASSERT_EQ(4U, received.size());
  7034. EXPECT_EQ("na%22me", received[0].name);
  7035. EXPECT_EQ("quoted name", received[0].content);
  7036. EXPECT_EQ("file", received[1].name);
  7037. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7038. received[1].filename);
  7039. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7040. EXPECT_EQ("injected", received[1].content);
  7041. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7042. EXPECT_EQ("my%22file.txt", received[2].filename);
  7043. EXPECT_EQ("cr lf name", received[2].content);
  7044. EXPECT_EQ("typed", received[3].name);
  7045. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7046. received[3].content_type);
  7047. EXPECT_EQ("typed content", received[3].content);
  7048. });
  7049. auto port = svr.bind_to_any_port("localhost");
  7050. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7051. auto se = detail::scope_exit([&] {
  7052. svr.stop();
  7053. t.join();
  7054. ASSERT_FALSE(svr.is_running());
  7055. });
  7056. svr.wait_until_ready();
  7057. Client cli("localhost", port);
  7058. UploadFormDataItems items = {
  7059. {"na\"me", "quoted name", "", ""},
  7060. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7061. "application/octet-stream"},
  7062. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7063. {"typed", "typed content", "",
  7064. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7065. };
  7066. auto res = cli.Post("/post", items);
  7067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7068. EXPECT_EQ(StatusCode::OK_200, res->status);
  7069. }
  7070. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7071. const UploadFormDataItems items = {
  7072. {"name1", "Content 1", "", ""},
  7073. {"name2", "Content 2", "file2.txt", "text/plain"},
  7074. };
  7075. Server svr;
  7076. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7077. const ContentReader &content_reader) {
  7078. ASSERT_TRUE(req.is_multipart_form_data());
  7079. std::vector<FormData> received;
  7080. content_reader(
  7081. [&](const FormData &file) {
  7082. received.push_back(file);
  7083. return true;
  7084. },
  7085. [&](const char *data, size_t data_length) {
  7086. received.back().content.append(data, data_length);
  7087. return true;
  7088. });
  7089. ASSERT_EQ(2U, received.size());
  7090. EXPECT_EQ("name1", received[0].name);
  7091. EXPECT_EQ("Content 1", received[0].content);
  7092. EXPECT_EQ("name2", received[1].name);
  7093. EXPECT_EQ("Content 2", received[1].content);
  7094. EXPECT_EQ("file2.txt", received[1].filename);
  7095. EXPECT_EQ("text/plain", received[1].content_type);
  7096. });
  7097. auto port = svr.bind_to_any_port("localhost");
  7098. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7099. auto se = detail::scope_exit([&] {
  7100. svr.stop();
  7101. t.join();
  7102. ASSERT_FALSE(svr.is_running());
  7103. });
  7104. svr.wait_until_ready();
  7105. Client cli("localhost", port);
  7106. // Whole-body serialization with a generated boundary
  7107. {
  7108. MultipartFormDataWriter writer;
  7109. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7110. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7111. writer.content_type());
  7112. auto body = writer.serialize(items);
  7113. EXPECT_EQ(body.size(), writer.content_length(items));
  7114. auto res = cli.Post("/post", body, writer.content_type());
  7115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7116. EXPECT_EQ(StatusCode::OK_200, res->status);
  7117. }
  7118. // Per-part framing with a custom boundary via a content provider
  7119. {
  7120. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7121. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7122. MultipartFormDataWriter writer("custom-boundary_123");
  7123. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7124. std::string body;
  7125. for (const auto &item : items) {
  7126. body += writer.item_begin(item);
  7127. body += item.content;
  7128. body += MultipartFormDataWriter::item_end();
  7129. }
  7130. body += writer.finish();
  7131. EXPECT_EQ(body.size(), writer.content_length(items));
  7132. auto res = cli.Post(
  7133. "/post", body.size(),
  7134. [&](size_t offset, size_t length, DataSink &sink) {
  7135. sink.write(body.data() + offset, length);
  7136. return true;
  7137. },
  7138. writer.content_type());
  7139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7140. EXPECT_EQ(StatusCode::OK_200, res->status);
  7141. }
  7142. }
  7143. TEST_F(ServerTest, PostContentReceiverGzip) {
  7144. cli_.set_compress(true);
  7145. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7147. ASSERT_EQ(StatusCode::OK_200, res->status);
  7148. ASSERT_EQ("content", res->body);
  7149. }
  7150. TEST_F(ServerTest, PutContentReceiver) {
  7151. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7153. ASSERT_EQ(StatusCode::OK_200, res->status);
  7154. ASSERT_EQ("content", res->body);
  7155. }
  7156. TEST_F(ServerTest, PatchContentReceiver) {
  7157. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7159. ASSERT_EQ(StatusCode::OK_200, res->status);
  7160. ASSERT_EQ("content", res->body);
  7161. }
  7162. template <typename ClientType>
  7163. void TestWithHeadersAndContentReceiver(
  7164. ClientType &cli,
  7165. std::function<Result(ClientType &, const std::string &, const Headers &,
  7166. const std::string &, const std::string &,
  7167. ContentReceiver, DownloadProgress)>
  7168. request_func) {
  7169. Headers headers;
  7170. headers.emplace("X-Custom-Header", "test-value");
  7171. std::string received_body;
  7172. auto res = request_func(
  7173. cli, "/content_receiver", headers, "content", "application/json",
  7174. [&](const char *data, size_t data_length) {
  7175. received_body.append(data, data_length);
  7176. return true;
  7177. },
  7178. nullptr);
  7179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7180. EXPECT_EQ(StatusCode::OK_200, res->status);
  7181. EXPECT_EQ("content", received_body);
  7182. }
  7183. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7184. #ifdef CPPHTTPLIB_SSL_ENABLED
  7185. using ClientT = SSLClient;
  7186. #else
  7187. using ClientT = Client;
  7188. #endif
  7189. TestWithHeadersAndContentReceiver<ClientT>(
  7190. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7191. const std::string &body, const std::string &content_type,
  7192. ContentReceiver receiver, DownloadProgress progress) {
  7193. return cli.Post(path, headers, body, content_type, receiver, progress);
  7194. });
  7195. }
  7196. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7197. #ifdef CPPHTTPLIB_SSL_ENABLED
  7198. using ClientT = SSLClient;
  7199. #else
  7200. using ClientT = Client;
  7201. #endif
  7202. TestWithHeadersAndContentReceiver<ClientT>(
  7203. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7204. const std::string &body, const std::string &content_type,
  7205. ContentReceiver receiver, DownloadProgress progress) {
  7206. return cli.Put(path, headers, body, content_type, receiver, progress);
  7207. });
  7208. }
  7209. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7210. #ifdef CPPHTTPLIB_SSL_ENABLED
  7211. using ClientT = SSLClient;
  7212. #else
  7213. using ClientT = Client;
  7214. #endif
  7215. TestWithHeadersAndContentReceiver<ClientT>(
  7216. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7217. const std::string &body, const std::string &content_type,
  7218. ContentReceiver receiver, DownloadProgress progress) {
  7219. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7220. });
  7221. }
  7222. template <typename ClientType>
  7223. void TestWithHeadersAndContentReceiverWithProgress(
  7224. ClientType &cli,
  7225. std::function<Result(ClientType &, const std::string &, const Headers &,
  7226. const std::string &, const std::string &,
  7227. ContentReceiver, DownloadProgress)>
  7228. request_func) {
  7229. Headers headers;
  7230. headers.emplace("X-Test-Header", "progress-test");
  7231. std::string received_body;
  7232. auto progress_called = false;
  7233. auto res = request_func(
  7234. cli, "/content_receiver", headers, "content", "text/plain",
  7235. [&](const char *data, size_t data_length) {
  7236. received_body.append(data, data_length);
  7237. return true;
  7238. },
  7239. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7240. progress_called = true;
  7241. return true;
  7242. });
  7243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7244. EXPECT_EQ(StatusCode::OK_200, res->status);
  7245. EXPECT_EQ("content", received_body);
  7246. EXPECT_TRUE(progress_called);
  7247. }
  7248. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7249. #ifdef CPPHTTPLIB_SSL_ENABLED
  7250. using ClientT = SSLClient;
  7251. #else
  7252. using ClientT = Client;
  7253. #endif
  7254. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7255. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7256. const std::string &body, const std::string &content_type,
  7257. ContentReceiver receiver, DownloadProgress progress) {
  7258. return cli.Post(path, headers, body, content_type, receiver, progress);
  7259. });
  7260. }
  7261. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7262. #ifdef CPPHTTPLIB_SSL_ENABLED
  7263. using ClientT = SSLClient;
  7264. #else
  7265. using ClientT = Client;
  7266. #endif
  7267. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7268. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7269. const std::string &body, const std::string &content_type,
  7270. ContentReceiver receiver, DownloadProgress progress) {
  7271. return cli.Put(path, headers, body, content_type, receiver, progress);
  7272. });
  7273. }
  7274. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7275. #ifdef CPPHTTPLIB_SSL_ENABLED
  7276. using ClientT = SSLClient;
  7277. #else
  7278. using ClientT = Client;
  7279. #endif
  7280. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7281. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7282. const std::string &body, const std::string &content_type,
  7283. ContentReceiver receiver, DownloadProgress progress) {
  7284. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7285. });
  7286. }
  7287. template <typename ClientType>
  7288. void TestWithHeadersAndContentReceiverError(
  7289. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7290. const Headers &, const std::string &,
  7291. const std::string &, ContentReceiver)>
  7292. request_func) {
  7293. Headers headers;
  7294. headers.emplace("X-Error-Test", "true");
  7295. std::string received_body;
  7296. auto receiver_failed = false;
  7297. auto res =
  7298. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7299. [&](const char *data, size_t data_length) {
  7300. received_body.append(data, data_length);
  7301. receiver_failed = true;
  7302. return false;
  7303. });
  7304. ASSERT_FALSE(res);
  7305. EXPECT_TRUE(receiver_failed);
  7306. }
  7307. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7308. #ifdef CPPHTTPLIB_SSL_ENABLED
  7309. using ClientT = SSLClient;
  7310. #else
  7311. using ClientT = Client;
  7312. #endif
  7313. TestWithHeadersAndContentReceiverError<ClientT>(
  7314. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7315. const std::string &body, const std::string &content_type,
  7316. ContentReceiver receiver) {
  7317. return cli.Post(path, headers, body, content_type, receiver);
  7318. });
  7319. }
  7320. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7321. #ifdef CPPHTTPLIB_SSL_ENABLED
  7322. using ClientT = SSLClient;
  7323. #else
  7324. using ClientT = Client;
  7325. #endif
  7326. TestWithHeadersAndContentReceiverError<ClientT>(
  7327. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7328. const std::string &body, const std::string &content_type,
  7329. ContentReceiver receiver) {
  7330. return cli.Put(path, headers, body, content_type, receiver);
  7331. });
  7332. }
  7333. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7334. #ifdef CPPHTTPLIB_SSL_ENABLED
  7335. using ClientT = SSLClient;
  7336. #else
  7337. using ClientT = Client;
  7338. #endif
  7339. TestWithHeadersAndContentReceiverError<ClientT>(
  7340. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7341. const std::string &body, const std::string &content_type,
  7342. ContentReceiver receiver) {
  7343. return cli.Patch(path, headers, body, content_type, receiver);
  7344. });
  7345. }
  7346. TEST_F(ServerTest, PostQueryStringAndBody) {
  7347. auto res =
  7348. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7350. ASSERT_EQ(StatusCode::OK_200, res->status);
  7351. }
  7352. TEST_F(ServerTest, HTTP2Magic) {
  7353. Request req;
  7354. req.method = "PRI";
  7355. req.path = "*";
  7356. req.body = "SM";
  7357. auto res = std::make_shared<Response>();
  7358. auto error = Error::Success;
  7359. auto ret = cli_.send(req, *res, error);
  7360. ASSERT_TRUE(ret);
  7361. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7362. }
  7363. TEST_F(ServerTest, KeepAlive) {
  7364. auto res = cli_.Get("/hi");
  7365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7366. EXPECT_EQ(StatusCode::OK_200, res->status);
  7367. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7368. EXPECT_EQ("Hello World!", res->body);
  7369. res = cli_.Get("/hi");
  7370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7371. EXPECT_EQ(StatusCode::OK_200, res->status);
  7372. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7373. EXPECT_EQ("Hello World!", res->body);
  7374. res = cli_.Get("/hi");
  7375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7376. EXPECT_EQ(StatusCode::OK_200, res->status);
  7377. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7378. EXPECT_EQ("Hello World!", res->body);
  7379. res = cli_.Get("/not-exist");
  7380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7381. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7382. res = cli_.Post("/empty", "", "text/plain");
  7383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7384. EXPECT_EQ(StatusCode::OK_200, res->status);
  7385. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7386. EXPECT_EQ("empty", res->body);
  7387. EXPECT_EQ("close", res->get_header_value("Connection"));
  7388. res = cli_.Post(
  7389. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7390. "text/plain");
  7391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7392. EXPECT_EQ(StatusCode::OK_200, res->status);
  7393. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7394. EXPECT_EQ("empty", res->body);
  7395. cli_.set_keep_alive(false);
  7396. res = cli_.Get("/last-request");
  7397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7398. EXPECT_EQ(StatusCode::OK_200, res->status);
  7399. EXPECT_EQ("close", res->get_header_value("Connection"));
  7400. }
  7401. TEST_F(ServerTest, TooManyRedirect) {
  7402. cli_.set_follow_location(true);
  7403. auto res = cli_.Get("/redirect/0");
  7404. ASSERT_TRUE(!res);
  7405. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7406. }
  7407. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7408. Request req;
  7409. req.method = "FOOBAR";
  7410. req.path = "/hi";
  7411. cli_.set_keep_alive(true);
  7412. auto res = cli_.send(req);
  7413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7414. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7415. EXPECT_EQ("close", res->get_header_value("Connection"));
  7416. EXPECT_FALSE(cli_.is_socket_open());
  7417. }
  7418. TEST_F(ServerTest, CustomRouteReadsBody) {
  7419. const std::string xml =
  7420. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7421. Request req;
  7422. req.method = "PROPFIND";
  7423. req.path = "/dav/dir";
  7424. req.set_header("Depth", "1");
  7425. req.body = xml;
  7426. auto res = cli_.send(req);
  7427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7428. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7429. EXPECT_EQ(xml, res->body);
  7430. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7431. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7432. }
  7433. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7434. Request req;
  7435. req.method = "PROPFIND";
  7436. req.path = "/dav/42";
  7437. auto res = cli_.send(req);
  7438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7439. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7440. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7441. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7442. }
  7443. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7444. Request req;
  7445. req.method = "PROPFIND";
  7446. req.path = "/dav-re/123";
  7447. auto res = cli_.send(req);
  7448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7449. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7450. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7451. }
  7452. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7453. Request req;
  7454. req.method = "MKCOL";
  7455. req.path = "/dav-mkcol";
  7456. auto res = cli_.send(req);
  7457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7458. EXPECT_EQ(StatusCode::Created_201, res->status);
  7459. }
  7460. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7461. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7462. Request req;
  7463. req.method = "REPORT";
  7464. req.path = "/dav-report";
  7465. req.body = xml;
  7466. auto res = cli_.send(req);
  7467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7468. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7469. EXPECT_EQ(xml, res->body);
  7470. }
  7471. // A content reader route must fire even when the request carries no body,
  7472. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7473. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7474. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7475. Request req;
  7476. req.method = "REPORT";
  7477. req.path = "/dav-report";
  7478. auto res = cli_.send(req);
  7479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7480. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7481. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7482. }
  7483. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7484. Request req;
  7485. req.method = "PROPFIND";
  7486. req.path = "/not-dav";
  7487. auto res = cli_.send(req);
  7488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7489. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7490. }
  7491. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7492. Request req;
  7493. req.method = "UNLOCK";
  7494. req.path = "/dav/dir";
  7495. cli_.set_keep_alive(true);
  7496. auto res = cli_.send(req);
  7497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7498. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7499. EXPECT_EQ("close", res->get_header_value("Connection"));
  7500. EXPECT_FALSE(cli_.is_socket_open());
  7501. }
  7502. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7503. // The mount point serves this path, but only for GET and HEAD.
  7504. auto get_res = cli_.Get("/dir/index.html");
  7505. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7506. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7507. Request req;
  7508. req.method = "PROPFIND";
  7509. req.path = "/dir/index.html";
  7510. auto res = cli_.send(req);
  7511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7512. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7513. }
  7514. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7515. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7516. cli_.set_keep_alive(true);
  7517. for (auto i = 0; i < 2; i++) {
  7518. Request req;
  7519. req.method = "PROPFIND";
  7520. req.path = "/dav/dir";
  7521. req.body = xml;
  7522. auto res = cli_.send(req);
  7523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7524. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7525. EXPECT_EQ(xml, res->body);
  7526. EXPECT_TRUE(cli_.is_socket_open());
  7527. }
  7528. // A built-in method must still be served on the same connection.
  7529. cli_.set_keep_alive(false);
  7530. auto res = cli_.Get("/hi");
  7531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7532. EXPECT_EQ(StatusCode::OK_200, res->status);
  7533. EXPECT_EQ("close", res->get_header_value("Connection"));
  7534. }
  7535. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7536. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7537. Request req;
  7538. req.method = "PROPFIND";
  7539. req.path = "/dav/dir";
  7540. req.set_header("Expect", "100-continue");
  7541. req.body = xml;
  7542. auto res = cli_.send(req);
  7543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7544. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7545. EXPECT_EQ(xml, res->body);
  7546. }
  7547. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7548. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7549. TEST_F(ServerTest, Gzip) {
  7550. Headers headers;
  7551. headers.emplace("Accept-Encoding", "gzip, deflate");
  7552. auto res = cli_.Get("/compress", headers);
  7553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7554. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7555. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7556. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7557. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7558. "7890123456789012345678901234567890",
  7559. res->body);
  7560. EXPECT_EQ(StatusCode::OK_200, res->status);
  7561. }
  7562. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7563. Headers headers;
  7564. headers.emplace("Accept-Encoding", "gzip, deflate");
  7565. auto res = cli_.Get("/compress-with-charset", headers);
  7566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7567. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7568. EXPECT_EQ("application/json; charset=utf-8",
  7569. res->get_header_value("Content-Type"));
  7570. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7571. "7890123456789012345678901234567890",
  7572. res->body);
  7573. EXPECT_EQ(StatusCode::OK_200, res->status);
  7574. }
  7575. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7576. Headers headers;
  7577. headers.emplace("Accept-Encoding", "");
  7578. auto res = cli_.Get("/compress", headers);
  7579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7580. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7581. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7582. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7583. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7584. "7890123456789012345678901234567890",
  7585. res->body);
  7586. EXPECT_EQ(StatusCode::OK_200, res->status);
  7587. }
  7588. TEST_F(ServerTest, GzipWithContentReceiver) {
  7589. Headers headers;
  7590. headers.emplace("Accept-Encoding", "gzip, deflate");
  7591. std::string body;
  7592. auto res = cli_.Get("/compress", headers,
  7593. [&](const char *data, uint64_t data_length) {
  7594. EXPECT_EQ(100U, data_length);
  7595. body.append(data, data_length);
  7596. return true;
  7597. });
  7598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7599. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7600. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7601. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7602. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7603. "7890123456789012345678901234567890",
  7604. body);
  7605. EXPECT_EQ(StatusCode::OK_200, res->status);
  7606. }
  7607. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7608. Headers headers;
  7609. headers.emplace("Accept-Encoding", "gzip, deflate");
  7610. cli_.set_decompress(false);
  7611. auto res = cli_.Get("/compress", headers);
  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(33U, res->body.size());
  7617. EXPECT_EQ(StatusCode::OK_200, res->status);
  7618. }
  7619. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7620. Headers headers;
  7621. headers.emplace("Accept-Encoding", "");
  7622. std::string body;
  7623. auto res = cli_.Get("/compress", headers,
  7624. [&](const char *data, uint64_t data_length) {
  7625. EXPECT_EQ(100U, data_length);
  7626. body.append(data, data_length);
  7627. return true;
  7628. });
  7629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7630. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7631. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7632. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7633. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7634. "7890123456789012345678901234567890",
  7635. body);
  7636. EXPECT_EQ(StatusCode::OK_200, res->status);
  7637. }
  7638. TEST_F(ServerTest, NoGzip) {
  7639. Headers headers;
  7640. headers.emplace("Accept-Encoding", "gzip, deflate");
  7641. auto res = cli_.Get("/nocompress", headers);
  7642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7643. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7644. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7645. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7646. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7647. "7890123456789012345678901234567890",
  7648. res->body);
  7649. EXPECT_EQ(StatusCode::OK_200, res->status);
  7650. }
  7651. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7652. Headers headers;
  7653. headers.emplace("Accept-Encoding", "gzip, deflate");
  7654. std::string body;
  7655. auto res = cli_.Get("/nocompress", headers,
  7656. [&](const char *data, uint64_t data_length) {
  7657. EXPECT_EQ(100U, data_length);
  7658. body.append(data, data_length);
  7659. return true;
  7660. });
  7661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7662. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7663. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7664. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7665. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7666. "7890123456789012345678901234567890",
  7667. body);
  7668. EXPECT_EQ(StatusCode::OK_200, res->status);
  7669. }
  7670. TEST_F(ServerTest, MultipartFormDataGzip) {
  7671. UploadFormDataItems items = {
  7672. {"key1", "test", "", ""},
  7673. {"key2", "--abcdefg123", "", ""},
  7674. };
  7675. cli_.set_compress(true);
  7676. auto res = cli_.Post("/compress-multipart", items);
  7677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7678. EXPECT_EQ(StatusCode::OK_200, res->status);
  7679. }
  7680. #endif
  7681. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7682. // Static file compression is opt-in, so these run their own server rather than
  7683. // flipping it on for the shared ServerTest fixture, which would silently
  7684. // rewrite what every other static file test is asserting.
  7685. class StaticFileCompressionTest : public ::testing::Test {
  7686. protected:
  7687. void TearDown() override {
  7688. if (t_.joinable()) {
  7689. svr_.stop();
  7690. t_.join();
  7691. }
  7692. }
  7693. int start(const std::function<void(Server &)> &configure = nullptr) {
  7694. // Serves the same tree as a directory of build-time compressed assets
  7695. // would be served: the mount point names the coding the files are already
  7696. // stored in. Registered before "/" so it is the one that matches.
  7697. svr_.set_mount_point("/pre-encoded", "./www",
  7698. {{"Content-Encoding", "gzip"}});
  7699. svr_.set_mount_point("/", "./www");
  7700. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7701. res.set_file_content("./www/dir/index.html", "text/html");
  7702. });
  7703. svr_.Get("/pre-encoded-file-content",
  7704. [](const Request & /*req*/, Response &res) {
  7705. res.set_header("Content-Encoding", "gzip");
  7706. res.set_file_content("./www/dir/index.html", "text/html");
  7707. });
  7708. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7709. res.set_content_provider(
  7710. 6, "text/plain",
  7711. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7712. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7713. return true;
  7714. });
  7715. });
  7716. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7717. res.set_content_provider(
  7718. 1000, "text/plain",
  7719. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7720. if (offset < 100) {
  7721. std::string data(100, 'A');
  7722. sink.write(data.data(), data.size());
  7723. return true;
  7724. }
  7725. std::this_thread::sleep_for(std::chrono::seconds(2));
  7726. std::string data(900, 'B');
  7727. sink.write(data.data(), data.size());
  7728. return true;
  7729. });
  7730. });
  7731. if (configure) { configure(svr_); }
  7732. auto port = svr_.bind_to_any_port(HOST);
  7733. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7734. svr_.wait_until_ready();
  7735. return port;
  7736. }
  7737. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7738. // Every file under ./www except 1MB.txt is smaller than the default
  7739. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7740. // it out of the way.
  7741. static void enable_without_floor(Server &svr) {
  7742. svr.set_static_file_compression(true);
  7743. svr.set_static_file_compression_min_length(0);
  7744. }
  7745. Server svr_;
  7746. std::thread t_;
  7747. };
  7748. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7749. auto port = start();
  7750. Client cli(HOST, port);
  7751. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7753. EXPECT_EQ(StatusCode::OK_200, res->status);
  7754. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7755. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7756. EXPECT_EQ(1048576U, res->body.size());
  7757. }
  7758. TEST_F(StaticFileCompressionTest, MountPoint) {
  7759. auto port = start(enable);
  7760. Client cli(HOST, port);
  7761. cli.set_decompress(false);
  7762. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7764. EXPECT_EQ(StatusCode::OK_200, res->status);
  7765. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7766. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7767. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7768. // The response stays self-delimiting: a length, not a chunked body.
  7769. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7770. EXPECT_EQ(std::to_string(res->body.size()),
  7771. res->get_header_value("Content-Length"));
  7772. EXPECT_LT(res->body.size(), 1048576U);
  7773. EXPECT_FALSE(res->body.empty());
  7774. }
  7775. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7776. auto port = start(enable);
  7777. Client cli(HOST, port);
  7778. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7780. EXPECT_EQ(StatusCode::OK_200, res->status);
  7781. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7782. EXPECT_EQ(1048576U, res->body.size());
  7783. }
  7784. TEST_F(StaticFileCompressionTest, FileContent) {
  7785. auto port = start(enable_without_floor);
  7786. Client cli(HOST, port);
  7787. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7789. EXPECT_EQ(StatusCode::OK_200, res->status);
  7790. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7791. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7792. EXPECT_EQ(104U, res->body.size());
  7793. }
  7794. // A handler that serves an already-encoded file names the coding itself. The
  7795. // file-backed path decided its coding from Accept-Encoding and the content
  7796. // type alone, so it compressed the stored bytes a second time and appended a
  7797. // second Content-Encoding field line.
  7798. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  7799. auto port = start(enable_without_floor);
  7800. Client cli(HOST, port);
  7801. cli.set_decompress(false);
  7802. auto res = cli.Get("/pre-encoded-file-content",
  7803. Headers{{"Accept-Encoding", "gzip"}});
  7804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7805. EXPECT_EQ(StatusCode::OK_200, res->status);
  7806. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7807. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7808. // Vary belongs to a coding the server chose, and it chose none here.
  7809. EXPECT_FALSE(res->has_header("Vary"));
  7810. // The file travels exactly as it is stored on disk.
  7811. EXPECT_EQ(104U, res->body.size());
  7812. }
  7813. // The 1MB file clears the default floor, so this one runs the configuration a
  7814. // deployment would actually have.
  7815. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  7816. auto port = start(enable);
  7817. Client cli(HOST, port);
  7818. cli.set_decompress(false);
  7819. auto res =
  7820. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7822. EXPECT_EQ(StatusCode::OK_200, res->status);
  7823. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7824. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7825. EXPECT_FALSE(res->has_header("Vary"));
  7826. EXPECT_EQ(1048576U, res->body.size());
  7827. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7828. }
  7829. TEST_F(StaticFileCompressionTest, Head) {
  7830. auto port = start(enable);
  7831. Client cli(HOST, port);
  7832. cli.set_decompress(false);
  7833. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7834. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  7835. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7837. EXPECT_EQ(StatusCode::OK_200, res->status);
  7838. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7839. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7840. // HEAD still reports the size a GET would return.
  7841. EXPECT_EQ(get->get_header_value("Content-Length"),
  7842. res->get_header_value("Content-Length"));
  7843. EXPECT_TRUE(res->body.empty());
  7844. }
  7845. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  7846. auto port = start(enable);
  7847. Client cli(HOST, port);
  7848. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  7849. {"Accept-Encoding", "gzip"}});
  7850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7851. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7852. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7853. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7854. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7855. EXPECT_EQ("cd", res->body);
  7856. }
  7857. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  7858. auto port = start(enable);
  7859. Client cli(HOST, port);
  7860. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  7861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7862. EXPECT_EQ(StatusCode::OK_200, res->status);
  7863. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7864. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7865. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7866. }
  7867. TEST_F(StaticFileCompressionTest, EmptyFile) {
  7868. auto port = start(enable);
  7869. Client cli(HOST, port);
  7870. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  7871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7872. EXPECT_EQ(StatusCode::OK_200, res->status);
  7873. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7874. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7875. EXPECT_TRUE(res->body.empty());
  7876. }
  7877. TEST_F(StaticFileCompressionTest, MinLength) {
  7878. auto port = start(enable);
  7879. Client cli(HOST, port);
  7880. // 104 bytes, well under the default floor. Compressing it would add the
  7881. // gzip header and trailer to a body that already fits in one packet.
  7882. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7884. EXPECT_EQ(StatusCode::OK_200, res->status);
  7885. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7886. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  7887. }
  7888. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  7889. auto port = start([](Server &svr) {
  7890. svr.set_static_file_compression(true);
  7891. svr.set_static_file_compression_min_length(1);
  7892. });
  7893. Client cli(HOST, port);
  7894. cli.set_decompress(false);
  7895. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  7896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7897. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7898. // A 9-byte file comes back larger than it went in, because gzip's header and
  7899. // trailer outweigh anything deflate can save. That is the end of the range
  7900. // the floor exists to keep out.
  7901. EXPECT_GT(res->body.size(), 9U);
  7902. }
  7903. TEST_F(StaticFileCompressionTest, MaxLength) {
  7904. auto port = start([](Server &svr) {
  7905. svr.set_static_file_compression(true);
  7906. svr.set_static_file_compression_min_length(0);
  7907. svr.set_static_file_compression_max_length(1024);
  7908. });
  7909. Client cli(HOST, port);
  7910. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  7911. // defines `small` as a macro on Windows.
  7912. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7913. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  7914. EXPECT_FALSE(over->has_header("Content-Encoding"));
  7915. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  7916. // Under it: compressed.
  7917. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7918. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  7919. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  7920. }
  7921. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  7922. auto port = start(enable_without_floor);
  7923. Client cli(HOST, port);
  7924. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  7925. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  7926. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  7927. auto identity_etag = identity->get_header_value("ETag");
  7928. ASSERT_FALSE(identity_etag.empty());
  7929. auto gzipped =
  7930. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7931. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  7932. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  7933. auto gzip_etag = gzipped->get_header_value("ETag");
  7934. ASSERT_FALSE(gzip_etag.empty());
  7935. // Two representations, two validators.
  7936. EXPECT_NE(identity_etag, gzip_etag);
  7937. // Each one revalidates against the request that would produce it...
  7938. auto fresh =
  7939. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  7940. {"If-None-Match", gzip_etag}});
  7941. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  7942. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  7943. auto fresh_identity =
  7944. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  7945. {"If-None-Match", identity_etag}});
  7946. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  7947. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  7948. // ...and not against the other representation.
  7949. auto crossed =
  7950. cli.Get("/dir/index.html",
  7951. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  7952. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  7953. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  7954. }
  7955. // The opt-in covers responses the server reads off disk itself. A caller's own
  7956. // known-length provider keeps its Content-Length and, more importantly, keeps
  7957. // delivering incrementally: routing it through a compressor would hold every
  7958. // write back until zlib's window filled.
  7959. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  7960. auto port = start(enable);
  7961. Client cli(HOST, port);
  7962. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  7963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7964. EXPECT_EQ(StatusCode::OK_200, res->status);
  7965. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7966. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7967. EXPECT_EQ("aaabbb", res->body);
  7968. }
  7969. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  7970. auto port = start(enable);
  7971. Client cli(HOST, port);
  7972. cli.set_read_timeout(1, 0);
  7973. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  7974. Headers{{"Accept-Encoding", "gzip"}});
  7975. ASSERT_TRUE(handle.is_valid());
  7976. // The provider writes 100 bytes and then stalls for longer than the read
  7977. // timeout. Those first bytes have to arrive anyway: run the response through
  7978. // a compressor and zlib holds them until its window fills, so the read would
  7979. // come back empty instead.
  7980. char buf[256];
  7981. auto n = handle.read(buf, sizeof(buf));
  7982. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  7983. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  7984. }
  7985. #endif
  7986. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7987. TEST_F(ServerTest, Brotli) {
  7988. Headers headers;
  7989. headers.emplace("Accept-Encoding", "br");
  7990. auto res = cli_.Get("/compress", headers);
  7991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7992. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7993. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7994. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  7995. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7996. "7890123456789012345678901234567890",
  7997. res->body);
  7998. EXPECT_EQ(StatusCode::OK_200, res->status);
  7999. }
  8000. #endif
  8001. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8002. TEST_F(ServerTest, Zstd) {
  8003. Headers headers;
  8004. headers.emplace("Accept-Encoding", "zstd");
  8005. auto res = cli_.Get("/compress", headers);
  8006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8007. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8008. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8009. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8010. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8011. "7890123456789012345678901234567890",
  8012. res->body);
  8013. EXPECT_EQ(StatusCode::OK_200, res->status);
  8014. }
  8015. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8016. Headers headers;
  8017. headers.emplace("Accept-Encoding", "");
  8018. auto res = cli_.Get("/compress", headers);
  8019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8020. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8021. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8022. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8023. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8024. "7890123456789012345678901234567890",
  8025. res->body);
  8026. EXPECT_EQ(StatusCode::OK_200, res->status);
  8027. }
  8028. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8029. Headers headers;
  8030. headers.emplace("Accept-Encoding", "zstd");
  8031. std::string body;
  8032. auto res = cli_.Get("/compress", headers,
  8033. [&](const char *data, uint64_t data_length) {
  8034. EXPECT_EQ(100U, data_length);
  8035. body.append(data, data_length);
  8036. return true;
  8037. });
  8038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8039. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8040. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8041. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8042. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8043. "7890123456789012345678901234567890",
  8044. body);
  8045. EXPECT_EQ(StatusCode::OK_200, res->status);
  8046. }
  8047. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8048. Headers headers;
  8049. headers.emplace("Accept-Encoding", "zstd");
  8050. cli_.set_decompress(false);
  8051. auto res = cli_.Get("/compress", headers);
  8052. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8053. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8054. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8055. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8057. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8058. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8059. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8060. EXPECT_EQ(StatusCode::OK_200, res->status);
  8061. ASSERT_EQ(26U, res->body.size());
  8062. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8063. 0);
  8064. }
  8065. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8066. Headers headers;
  8067. headers.emplace("Accept-Encoding", "");
  8068. std::string body;
  8069. auto res = cli_.Get("/compress", headers,
  8070. [&](const char *data, uint64_t data_length) {
  8071. EXPECT_EQ(100U, data_length);
  8072. body.append(data, data_length);
  8073. return true;
  8074. });
  8075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8076. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8077. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8078. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8079. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8080. "7890123456789012345678901234567890",
  8081. body);
  8082. EXPECT_EQ(StatusCode::OK_200, res->status);
  8083. }
  8084. TEST_F(ServerTest, NoZstd) {
  8085. Headers headers;
  8086. headers.emplace("Accept-Encoding", "zstd");
  8087. auto res = cli_.Get("/nocompress", headers);
  8088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8089. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8090. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8091. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8092. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8093. "7890123456789012345678901234567890",
  8094. res->body);
  8095. EXPECT_EQ(StatusCode::OK_200, res->status);
  8096. }
  8097. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8098. Headers headers;
  8099. headers.emplace("Accept-Encoding", "zstd");
  8100. std::string body;
  8101. auto res = cli_.Get("/nocompress", headers,
  8102. [&](const char *data, uint64_t data_length) {
  8103. EXPECT_EQ(100U, data_length);
  8104. body.append(data, data_length);
  8105. return true;
  8106. });
  8107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8108. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8109. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8110. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8111. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8112. "7890123456789012345678901234567890",
  8113. body);
  8114. EXPECT_EQ(StatusCode::OK_200, res->status);
  8115. }
  8116. // TODO: How to enable zstd ??
  8117. TEST_F(ServerTest, MultipartFormDataZstd) {
  8118. UploadFormDataItems items = {
  8119. {"key1", "test", "", ""},
  8120. {"key2", "--abcdefg123", "", ""},
  8121. };
  8122. Headers headers;
  8123. headers.emplace("Accept-Encoding", "zstd");
  8124. cli_.set_compress(true);
  8125. auto res = cli_.Post("/compress-multipart", headers, items);
  8126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8127. EXPECT_EQ(StatusCode::OK_200, res->status);
  8128. }
  8129. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8130. Headers headers;
  8131. headers.emplace("Accept-Encoding", "zstd");
  8132. cli_.set_compress(true);
  8133. auto res = cli_.Put(
  8134. "/put", headers, 3,
  8135. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8136. sink.os << "PUT";
  8137. return true;
  8138. },
  8139. "text/plain");
  8140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8141. EXPECT_EQ(StatusCode::OK_200, res->status);
  8142. EXPECT_EQ("PUT", res->body);
  8143. }
  8144. // Pre-compression logging tests
  8145. TEST_F(ServerTest, PreCompressionLogging) {
  8146. // Test data for compression (matches the actual /compress endpoint content)
  8147. const std::string test_content =
  8148. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8149. "3456789012345678901234567890";
  8150. // Variables to capture logging data
  8151. std::string pre_compression_body;
  8152. std::string pre_compression_content_type;
  8153. std::string pre_compression_content_encoding;
  8154. std::string post_compression_body;
  8155. std::string post_compression_content_type;
  8156. std::string post_compression_content_encoding;
  8157. // Set up pre-compression logger
  8158. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8159. const Response &res) {
  8160. pre_compression_body = res.body;
  8161. pre_compression_content_type = res.get_header_value("Content-Type");
  8162. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8163. });
  8164. // Set up post-compression logger
  8165. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8166. post_compression_body = res.body;
  8167. post_compression_content_type = res.get_header_value("Content-Type");
  8168. post_compression_content_encoding =
  8169. res.get_header_value("Content-Encoding");
  8170. });
  8171. // Test with gzip compression
  8172. Headers headers;
  8173. headers.emplace("Accept-Encoding", "gzip");
  8174. auto res = cli_.Get("/compress", headers);
  8175. // Verify response was compressed
  8176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8177. EXPECT_EQ(StatusCode::OK_200, res->status);
  8178. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8179. // Verify pre-compression logger captured uncompressed content
  8180. EXPECT_EQ(test_content, pre_compression_body);
  8181. EXPECT_EQ("text/plain", pre_compression_content_type);
  8182. EXPECT_TRUE(pre_compression_content_encoding
  8183. .empty()); // No encoding header before compression
  8184. // Verify post-compression logger captured compressed content
  8185. EXPECT_NE(test_content,
  8186. post_compression_body); // Should be different after compression
  8187. EXPECT_EQ("text/plain", post_compression_content_type);
  8188. EXPECT_EQ("gzip", post_compression_content_encoding);
  8189. // Verify compressed content is smaller
  8190. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8191. }
  8192. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8193. const std::string test_content =
  8194. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8195. "3456789012345678901234567890";
  8196. std::string pre_compression_body;
  8197. std::string post_compression_body;
  8198. svr_.set_pre_compression_logger(
  8199. [&](const Request & /*req*/, const Response &res) {
  8200. pre_compression_body = res.body;
  8201. });
  8202. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8203. post_compression_body = res.body;
  8204. });
  8205. Headers headers;
  8206. headers.emplace("Accept-Encoding", "br");
  8207. auto res = cli_.Get("/compress", headers);
  8208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8209. EXPECT_EQ(StatusCode::OK_200, res->status);
  8210. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8211. // Verify pre-compression content is uncompressed
  8212. EXPECT_EQ(test_content, pre_compression_body);
  8213. // Verify post-compression content is compressed
  8214. EXPECT_NE(test_content, post_compression_body);
  8215. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8216. }
  8217. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8218. const std::string test_content =
  8219. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8220. "3456789012345678901234567890";
  8221. std::string pre_compression_body;
  8222. std::string post_compression_body;
  8223. svr_.set_pre_compression_logger(
  8224. [&](const Request & /*req*/, const Response &res) {
  8225. pre_compression_body = res.body;
  8226. });
  8227. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8228. post_compression_body = res.body;
  8229. });
  8230. // Request without compression (use /nocompress endpoint)
  8231. Headers headers;
  8232. auto res = cli_.Get("/nocompress", headers);
  8233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8234. EXPECT_EQ(StatusCode::OK_200, res->status);
  8235. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8236. // Pre-compression logger should not be called when no compression is applied
  8237. EXPECT_TRUE(
  8238. pre_compression_body.empty()); // Pre-compression logger not called
  8239. EXPECT_EQ(
  8240. test_content,
  8241. post_compression_body); // Post-compression logger captures final content
  8242. }
  8243. TEST_F(ServerTest, LoggerSeesContentLength) {
  8244. size_t logged_content_length = 0;
  8245. std::string logged_content_length_header;
  8246. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8247. logged_content_length = res.content_length_;
  8248. logged_content_length_header = res.get_header_value("Content-Length");
  8249. });
  8250. auto res = cli_.Get("/nocompress");
  8251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8252. EXPECT_EQ(StatusCode::OK_200, res->status);
  8253. EXPECT_EQ(res->body.size(), logged_content_length);
  8254. EXPECT_EQ(std::to_string(logged_content_length),
  8255. logged_content_length_header);
  8256. }
  8257. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8258. const std::string test_content =
  8259. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8260. "3456789012345678901234567890";
  8261. std::string pre_compression_body;
  8262. bool pre_logger_called = false;
  8263. // Set only pre-compression logger
  8264. svr_.set_pre_compression_logger(
  8265. [&](const Request & /*req*/, const Response &res) {
  8266. pre_compression_body = res.body;
  8267. pre_logger_called = true;
  8268. });
  8269. Headers headers;
  8270. headers.emplace("Accept-Encoding", "gzip");
  8271. auto res = cli_.Get("/compress", headers);
  8272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8273. EXPECT_EQ(StatusCode::OK_200, res->status);
  8274. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8275. // Verify pre-compression logger was called
  8276. EXPECT_TRUE(pre_logger_called);
  8277. EXPECT_EQ(test_content, pre_compression_body);
  8278. }
  8279. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8280. {
  8281. // Test with Expect: 100-continue header - success case
  8282. // Server returns 100 Continue, client sends body, server returns 200 OK
  8283. Request req;
  8284. req.method = "POST";
  8285. req.path = "/post-large";
  8286. req.set_header("Expect", "100-continue");
  8287. req.body = LARGE_DATA;
  8288. Response res;
  8289. auto error = Error::Success;
  8290. cli_.set_keep_alive(true);
  8291. auto ret = cli_.send(req, res, error);
  8292. EXPECT_TRUE(ret);
  8293. EXPECT_EQ(StatusCode::OK_200, res.status);
  8294. EXPECT_EQ(LARGE_DATA, res.body);
  8295. }
  8296. {
  8297. // Test with Expect: 100-continue header - error case
  8298. // Client should not send the body when server returns an error
  8299. Request req;
  8300. req.method = "POST";
  8301. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8302. req.set_header("Expect", "100-continue");
  8303. req.body = LARGE_DATA;
  8304. Response res;
  8305. auto error = Error::Success;
  8306. auto start = std::chrono::high_resolution_clock::now();
  8307. cli_.set_keep_alive(true);
  8308. auto ret = cli_.send(req, res, error);
  8309. auto end = std::chrono::high_resolution_clock::now();
  8310. auto elapsed =
  8311. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8312. .count();
  8313. // With Expect: 100-continue, request completes successfully but with error
  8314. EXPECT_TRUE(ret);
  8315. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8316. EXPECT_EQ("close", res.get_header_value("Connection"));
  8317. EXPECT_FALSE(cli_.is_socket_open());
  8318. EXPECT_LE(elapsed, 2000);
  8319. }
  8320. {
  8321. // Send an extra GET request to ensure error recovery without hanging
  8322. Request req;
  8323. req.method = "GET";
  8324. req.path = "/hi";
  8325. auto start = std::chrono::high_resolution_clock::now();
  8326. auto res = cli_.send(req);
  8327. auto end = std::chrono::high_resolution_clock::now();
  8328. auto elapsed =
  8329. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8330. .count();
  8331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8332. EXPECT_EQ(StatusCode::OK_200, res->status);
  8333. EXPECT_EQ("Hello World!", res->body);
  8334. EXPECT_LE(elapsed, 500);
  8335. }
  8336. }
  8337. TEST(ZstdDecompressor, ChunkedDecompression) {
  8338. std::string data;
  8339. for (size_t i = 0; i < 32 * 1024; ++i) {
  8340. data.push_back(static_cast<char>('a' + i % 26));
  8341. }
  8342. std::string compressed_data;
  8343. {
  8344. httplib::detail::zstd_compressor compressor;
  8345. bool result = compressor.compress(
  8346. data.data(), data.size(),
  8347. /*last=*/true,
  8348. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8349. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8350. compressed_data_size);
  8351. return true;
  8352. });
  8353. ASSERT_TRUE(result);
  8354. }
  8355. std::string decompressed_data;
  8356. {
  8357. httplib::detail::zstd_decompressor decompressor;
  8358. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8359. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8360. size_t chunk_size = 130;
  8361. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8362. chunk_begin += chunk_size) {
  8363. size_t current_chunk_size =
  8364. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8365. bool result = decompressor.decompress(
  8366. compressed_data.data() + chunk_begin, current_chunk_size,
  8367. [&](const char *decompressed_data_chunk,
  8368. size_t decompressed_data_chunk_size) {
  8369. decompressed_data.insert(decompressed_data.size(),
  8370. decompressed_data_chunk,
  8371. decompressed_data_chunk_size);
  8372. return true;
  8373. });
  8374. ASSERT_TRUE(result);
  8375. }
  8376. }
  8377. ASSERT_EQ(data, decompressed_data);
  8378. }
  8379. TEST(ZstdDecompressor, Decompress) {
  8380. std::string original_text = "Compressed with ZSTD";
  8381. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8382. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8383. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8384. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8385. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8386. std::string decompressed_data;
  8387. {
  8388. httplib::detail::zstd_decompressor decompressor;
  8389. bool result = decompressor.decompress(
  8390. compressed_data.data(), compressed_data.size(),
  8391. [&](const char *decompressed_data_chunk,
  8392. size_t decompressed_data_chunk_size) {
  8393. decompressed_data.insert(decompressed_data.size(),
  8394. decompressed_data_chunk,
  8395. decompressed_data_chunk_size);
  8396. return true;
  8397. });
  8398. ASSERT_TRUE(result);
  8399. }
  8400. ASSERT_EQ(original_text, decompressed_data);
  8401. }
  8402. #endif
  8403. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8404. // separate chunks so that the server sees each part in its own read(). Used to
  8405. // place a read boundary at a specific offset of a request body.
  8406. static bool send_request_in_parts(time_t read_timeout_sec,
  8407. const std::vector<std::string> &parts,
  8408. std::string *resp = nullptr,
  8409. int port = PORT) {
  8410. auto error = Error::Success;
  8411. auto client_sock = detail::create_client_socket(
  8412. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8413. /*connection_timeout_sec=*/5, 0,
  8414. /*read_timeout_sec=*/5, 0,
  8415. /*write_timeout_sec=*/5, 0, std::string(), error);
  8416. if (client_sock == INVALID_SOCKET) { return false; }
  8417. auto ret = detail::process_client_socket(
  8418. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8419. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8420. for (size_t i = 0; i < parts.size(); i++) {
  8421. const auto &part = parts[i];
  8422. if (part.size() !=
  8423. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8424. return false;
  8425. }
  8426. if (i + 1 < parts.size()) {
  8427. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8428. }
  8429. }
  8430. char buf[512];
  8431. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8432. while (line_reader.getline()) {
  8433. if (resp) { *resp += line_reader.ptr(); }
  8434. }
  8435. return true;
  8436. });
  8437. detail::close_socket(client_sock);
  8438. return ret;
  8439. }
  8440. // Sends a raw request to a server listening at HOST:PORT.
  8441. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8442. std::string *resp = nullptr, int port = PORT) {
  8443. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8444. }
  8445. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8446. Server svr;
  8447. std::string header_value;
  8448. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8449. header_value = req.get_header_value("foo");
  8450. res.set_content("ok", "text/plain");
  8451. });
  8452. thread t = thread([&] { svr.listen(HOST, PORT); });
  8453. auto se = detail::scope_exit([&] {
  8454. svr.stop();
  8455. t.join();
  8456. ASSERT_FALSE(svr.is_running());
  8457. });
  8458. svr.wait_until_ready();
  8459. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8460. // like characters are not treated the same - use vertical tab and escape.
  8461. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8462. "foo: \t \v bar \x1B\t \r\n"
  8463. "Connection: close\r\n"
  8464. "\r\n";
  8465. std::string res;
  8466. ASSERT_TRUE(send_request(5, req, &res));
  8467. EXPECT_EQ(header_value, "");
  8468. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8469. }
  8470. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8471. Server svr;
  8472. std::string received;
  8473. svr.Get("/order", [&](const Request &req, Response &res) {
  8474. received = entries_to_string(req.headers);
  8475. res.set_content("ok", "text/plain");
  8476. });
  8477. auto port = svr.bind_to_any_port(HOST);
  8478. thread t = thread([&] { svr.listen_after_bind(); });
  8479. auto se = detail::scope_exit([&] {
  8480. svr.stop();
  8481. t.join();
  8482. ASSERT_FALSE(svr.is_running());
  8483. });
  8484. svr.wait_until_ready();
  8485. const std::string req = "GET /order HTTP/1.1\r\n"
  8486. "X-First: 1\r\n"
  8487. "X-Dup: a\r\n"
  8488. "X-Second: 2\r\n"
  8489. "X-Dup: b\r\n"
  8490. "Connection: close\r\n"
  8491. "\r\n";
  8492. std::string res;
  8493. ASSERT_TRUE(send_request(5, req, &res, port));
  8494. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8495. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8496. }
  8497. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8498. Server svr;
  8499. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8500. res.set_header("Set-Cookie", "first=1");
  8501. res.set_header("X-Between", "y");
  8502. res.set_header("Set-Cookie", "second=2");
  8503. res.set_content("ok", "text/plain");
  8504. });
  8505. auto port = svr.bind_to_any_port(HOST);
  8506. thread t = thread([&] { svr.listen_after_bind(); });
  8507. auto se = detail::scope_exit([&] {
  8508. svr.stop();
  8509. t.join();
  8510. ASSERT_FALSE(svr.is_running());
  8511. });
  8512. svr.wait_until_ready();
  8513. Client cli(HOST, port);
  8514. auto res = cli.Get("/cookies");
  8515. ASSERT_TRUE(res);
  8516. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8517. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8518. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8519. }
  8520. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8521. Server svr;
  8522. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8523. auto i = new int(0);
  8524. res.set_header("Trailer", "X-Safe, X-Reflected");
  8525. res.set_chunked_content_provider(
  8526. "text/plain",
  8527. [i](size_t /*offset*/, DataSink &sink) {
  8528. if (*i == 0) {
  8529. sink.os << "body";
  8530. } else {
  8531. Headers trailer;
  8532. // A valid trailer that must survive.
  8533. trailer.emplace("X-Safe", "safe");
  8534. // Attacker-controlled value carrying CR/LF (response splitting).
  8535. trailer.emplace("X-Reflected",
  8536. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8537. // Attacker-controlled name carrying CR/LF.
  8538. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8539. sink.done_with_trailer(trailer);
  8540. }
  8541. (*i)++;
  8542. return true;
  8543. },
  8544. [i](bool /*success*/) { delete i; });
  8545. });
  8546. thread t = thread([&] { svr.listen(HOST, PORT); });
  8547. auto se = detail::scope_exit([&] {
  8548. svr.stop();
  8549. t.join();
  8550. ASSERT_FALSE(svr.is_running());
  8551. });
  8552. svr.wait_until_ready();
  8553. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8554. "Host: " + HOST +
  8555. "\r\n"
  8556. "Connection: close\r\n"
  8557. "\r\n";
  8558. std::string res;
  8559. ASSERT_TRUE(send_request(5, req, &res));
  8560. // The injected fields must not appear anywhere in the raw response.
  8561. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8562. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8563. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8564. // Invalid trailers are dropped entirely, matching set_header().
  8565. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8566. // The valid trailer still passes through.
  8567. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8568. }
  8569. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8570. Server svr;
  8571. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8572. // res.headers is a public field an application can populate directly,
  8573. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8574. // A valid header that must survive.
  8575. res.headers.emplace("X-Safe", "safe");
  8576. // Attacker-controlled value carrying CR/LF (response splitting).
  8577. res.headers.emplace("X-Reflected",
  8578. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8579. // Attacker-controlled name carrying CR/LF.
  8580. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8581. res.set_content("body", "text/plain");
  8582. });
  8583. thread t = thread([&] { svr.listen(HOST, PORT); });
  8584. auto se = detail::scope_exit([&] {
  8585. svr.stop();
  8586. t.join();
  8587. ASSERT_FALSE(svr.is_running());
  8588. });
  8589. svr.wait_until_ready();
  8590. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8591. "Host: " + HOST +
  8592. "\r\n"
  8593. "Connection: close\r\n"
  8594. "\r\n";
  8595. std::string res;
  8596. ASSERT_TRUE(send_request(5, req, &res));
  8597. // The injected fields must not appear anywhere in the raw response.
  8598. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8599. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8600. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8601. // Invalid headers are dropped entirely, matching set_header().
  8602. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8603. // The valid header still passes through.
  8604. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8605. }
  8606. // Forward declaration: in split builds split.py strips `inline` and moves the
  8607. // definition into httplib.cc, so detail::write_request_line is not visible from
  8608. // the public httplib.h. Re-declaring it here lets the tests link against the
  8609. // symbol in both header-only and split builds.
  8610. namespace httplib {
  8611. namespace detail {
  8612. ssize_t write_request_line(Stream &strm, const std::string &method,
  8613. const std::string &path);
  8614. } // namespace detail
  8615. } // namespace httplib
  8616. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8617. // A well-formed target is written verbatim.
  8618. {
  8619. detail::BufferStream strm;
  8620. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8621. EXPECT_GT(n, 0);
  8622. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8623. }
  8624. // A target carrying CR/LF, SP or other control octets must be rejected
  8625. // before anything reaches the wire, otherwise it splits the request line and
  8626. // injects a header or a whole request. This is what a decoded redirect
  8627. // Location ("%0D%0A") turns into when path encoding is disabled.
  8628. const std::string evil_targets[] = {
  8629. "/a\r\nInjected: pwned",
  8630. "/a\rInjected",
  8631. "/a\nInjected",
  8632. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8633. "/a b",
  8634. "/a\tb",
  8635. "/a\x7f",
  8636. };
  8637. for (const auto &evil : evil_targets) {
  8638. detail::BufferStream strm;
  8639. auto n = detail::write_request_line(strm, "GET", evil);
  8640. EXPECT_LT(n, 0);
  8641. EXPECT_TRUE(strm.get_buffer().empty());
  8642. }
  8643. }
  8644. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8645. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8646. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8647. // target -- what a redirect Location "%0D%0A" decodes to -- reaches
  8648. // write_request. The client must fail cleanly with Error::Write instead of
  8649. // putting a request-line-less, header-injecting request on the wire.
  8650. Server svr;
  8651. svr.Get("/a", [](const Request &, Response &res) {
  8652. res.set_content("ok", "text/plain");
  8653. });
  8654. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8655. auto se = detail::scope_exit([&] {
  8656. svr.stop();
  8657. thread.join();
  8658. ASSERT_FALSE(svr.is_running());
  8659. });
  8660. svr.wait_until_ready();
  8661. {
  8662. Client cli(HOST, PORT);
  8663. cli.set_path_encode(false);
  8664. // The request is rejected before anything is written, so the connection
  8665. // stays silent and the subsequent response read would otherwise block for
  8666. // the full default read timeout. Shorten it -- the assertion is on the
  8667. // error, not the timeout.
  8668. cli.set_read_timeout(1, 0);
  8669. auto res = cli.Get("/a\r\nInjected: pwned");
  8670. EXPECT_FALSE(res);
  8671. EXPECT_EQ(Error::Write, res.error());
  8672. }
  8673. }
  8674. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8675. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8676. // including extension methods.
  8677. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8678. for (const auto &method : good_methods) {
  8679. detail::BufferStream strm;
  8680. auto n = detail::write_request_line(strm, method, "/");
  8681. EXPECT_GT(n, 0);
  8682. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8683. }
  8684. // A method carrying CR/LF would split the request line and smuggle a whole
  8685. // request ahead of the real one. A space or an empty method corrupts the
  8686. // request line. All must be rejected before anything reaches the wire.
  8687. const std::string evil_methods[] = {
  8688. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8689. "GET\r\nInjected: pwned",
  8690. "GET\r",
  8691. "GET\n",
  8692. "GE T",
  8693. "",
  8694. };
  8695. for (const auto &evil : evil_methods) {
  8696. detail::BufferStream strm;
  8697. auto n = detail::write_request_line(strm, evil, "/");
  8698. EXPECT_LT(n, 0);
  8699. EXPECT_TRUE(strm.get_buffer().empty());
  8700. }
  8701. }
  8702. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  8703. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  8704. // through Client::send must fail with Error::Write and no request, neither
  8705. // the smuggled one nor the real one, may reach the server.
  8706. Server svr;
  8707. std::atomic<int> request_count(0);
  8708. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  8709. request_count++;
  8710. res.status = StatusCode::OK_200;
  8711. return Server::HandlerResponse::Handled;
  8712. });
  8713. auto port = svr.bind_to_any_port(HOST);
  8714. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8715. auto se = detail::scope_exit([&] {
  8716. svr.stop();
  8717. thread.join();
  8718. ASSERT_FALSE(svr.is_running());
  8719. });
  8720. svr.wait_until_ready();
  8721. {
  8722. Client cli(HOST, port);
  8723. const std::string evil_methods[] = {
  8724. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8725. "GE T",
  8726. "",
  8727. };
  8728. for (const auto &evil : evil_methods) {
  8729. Request req;
  8730. req.method = evil;
  8731. req.path = "/";
  8732. auto res = cli.send(req);
  8733. EXPECT_FALSE(res);
  8734. EXPECT_EQ(Error::Write, res.error());
  8735. }
  8736. auto handle =
  8737. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  8738. EXPECT_FALSE(handle.is_valid());
  8739. EXPECT_EQ(Error::Write, handle.error);
  8740. // A valid request on the same client still goes through.
  8741. auto res = cli.Get("/");
  8742. ASSERT_TRUE(res);
  8743. EXPECT_EQ(StatusCode::OK_200, res->status);
  8744. }
  8745. EXPECT_EQ(1, request_count.load());
  8746. }
  8747. // Sends a raw request and verifies that there isn't a crash or exception.
  8748. static void test_raw_request(const std::string &req,
  8749. std::string *out = nullptr) {
  8750. Server svr;
  8751. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8752. res.set_content("ok", "text/plain");
  8753. });
  8754. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8755. res.set_content("ok", "text/plain");
  8756. });
  8757. svr.Get("/header_field_value_check",
  8758. [&](const Request & /*req*/, Response &res) {
  8759. res.set_content("ok", "text/plain");
  8760. });
  8761. svr.CustomRoute("PROPFIND", "/dav",
  8762. [&](const Request & /*req*/, Response &res) {
  8763. res.status = StatusCode::MultiStatus_207;
  8764. });
  8765. // Server read timeout must be longer than the client read timeout for the
  8766. // bug to reproduce, probably to force the server to process a request
  8767. // without a trailing blank line.
  8768. const time_t client_read_timeout_sec = 1;
  8769. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8770. bool listen_thread_ok = false;
  8771. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8772. auto se = detail::scope_exit([&] {
  8773. svr.stop();
  8774. t.join();
  8775. ASSERT_FALSE(svr.is_running());
  8776. EXPECT_TRUE(listen_thread_ok);
  8777. });
  8778. svr.wait_until_ready();
  8779. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8780. }
  8781. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8782. // A certain header line causes an exception if the header property is parsed
  8783. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8784. test_raw_request(
  8785. "GET /hi HTTP/1.1\r\n"
  8786. " : "
  8787. " "
  8788. " ");
  8789. }
  8790. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8791. // A certain header line causes an exception if the header property *name* is
  8792. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8793. // greedy matcher and requires backtracking when there are a lot of ":"
  8794. // characters.
  8795. // This occurs with libc++ but not libstdc++.
  8796. test_raw_request(
  8797. "GET /hi HTTP/1.1\r\n"
  8798. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8799. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8800. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8801. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8802. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8803. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8804. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8805. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8806. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8807. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8808. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8809. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8810. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8811. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8812. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8813. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8814. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8815. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8816. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8817. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8818. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8819. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8820. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8821. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8822. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8823. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8824. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8825. "&&&%%%");
  8826. }
  8827. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8828. // Make sure this doesn't crash the server.
  8829. // In a previous version of the header line regex, the "\r" rendered the line
  8830. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8831. // a new position where the leading white space ended and the field value
  8832. // began.
  8833. // The crash occurs with libc++ but not libstdc++.
  8834. test_raw_request("GET /hi HTTP/1.1\r\n"
  8835. "a:" +
  8836. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8837. "\r\n"
  8838. "\r\n");
  8839. }
  8840. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8841. std::string out;
  8842. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8843. "Content-Type: text/plain\r\n"
  8844. "Transfer-Encoding: chunked\r\n"
  8845. "\r\n"
  8846. "nothex\r\n",
  8847. &out);
  8848. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8849. }
  8850. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8851. std::string out;
  8852. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8853. "Content-Type: text/plain\r\n"
  8854. "Transfer-Encoding: chunked\r\n"
  8855. "\r\n"
  8856. "3\r\n"
  8857. "xyz\r\n"
  8858. "NaN\r\n",
  8859. &out);
  8860. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8861. }
  8862. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8863. std::string out;
  8864. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8865. "Content-Type: text/plain\r\n"
  8866. "Transfer-Encoding: chunked\r\n"
  8867. "\r\n"
  8868. // Length is too large for 64 bits.
  8869. "1ffffffffffffffff\r\n"
  8870. "xyz\r\n",
  8871. &out);
  8872. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8873. }
  8874. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8875. test_raw_request("GET /hi HTTP/1.1\r\n"
  8876. "Content-Type: text/plain\r\n\r");
  8877. }
  8878. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8879. std::string out;
  8880. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8881. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8882. }
  8883. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  8884. for (auto target : {"/h\ri", "/h\x7fi"}) {
  8885. std::string out;
  8886. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  8887. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  8888. }
  8889. }
  8890. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  8891. std::string out;
  8892. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  8893. "Connection: close\r\n\r\n",
  8894. &out);
  8895. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8896. }
  8897. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8898. Server svr;
  8899. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8900. EXPECT_TRUE(!req.remote_addr.empty());
  8901. });
  8902. thread t = thread([&] { svr.listen(HOST, PORT); });
  8903. auto se = detail::scope_exit([&] {
  8904. svr.stop();
  8905. t.join();
  8906. ASSERT_FALSE(svr.is_running());
  8907. });
  8908. svr.wait_until_ready();
  8909. // Send an invalid request line to trigger Bad Request
  8910. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8911. std::string out;
  8912. ASSERT_TRUE(send_request(5, bad_req, &out));
  8913. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8914. }
  8915. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8916. // answered right away rather than blocking on a read that waits for EOF.
  8917. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  8918. std::string out;
  8919. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  8920. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  8921. }
  8922. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  8923. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  8924. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  8925. for (const auto *method : methods) {
  8926. Server svr;
  8927. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8928. EXPECT_FALSE(svr.is_valid()) << method;
  8929. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  8930. }
  8931. }
  8932. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  8933. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  8934. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  8935. for (const auto *method : methods) {
  8936. Server svr;
  8937. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8938. EXPECT_FALSE(svr.is_valid()) << method;
  8939. }
  8940. }
  8941. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  8942. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  8943. "COPY", "MOVE", "LOCK",
  8944. "UNLOCK", "REPORT", "SUBSCRIBE"};
  8945. Server svr;
  8946. for (const auto *method : methods) {
  8947. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8948. }
  8949. EXPECT_TRUE(svr.is_valid());
  8950. }
  8951. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  8952. Server svr;
  8953. svr.CustomRoute("POST", "/x",
  8954. [](const Request &, Response &, const ContentReader &) {});
  8955. EXPECT_FALSE(svr.is_valid());
  8956. }
  8957. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  8958. Server svr;
  8959. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  8960. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  8961. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  8962. EXPECT_FALSE(svr.is_valid());
  8963. }
  8964. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  8965. Server svr;
  8966. auto captured = Error::Success;
  8967. svr.set_error_logger(
  8968. [&](const Error &err, const Request * /*req*/) { captured = err; });
  8969. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  8970. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  8971. }
  8972. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  8973. std::string out;
  8974. std::string request(
  8975. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  8976. test_raw_request(request, &out);
  8977. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8978. }
  8979. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  8980. std::string out;
  8981. std::string request(
  8982. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  8983. test_raw_request(request, &out);
  8984. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8985. }
  8986. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  8987. std::string out;
  8988. std::string request(
  8989. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  8990. test_raw_request(request, &out);
  8991. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8992. }
  8993. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  8994. std::string out;
  8995. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  8996. "Test: \r\n\r\n",
  8997. &out);
  8998. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8999. }
  9000. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9001. Server svr;
  9002. std::string x_custom;
  9003. std::string cookie;
  9004. std::string xff;
  9005. std::string x_unicode;
  9006. std::string x_iis;
  9007. svr.Get("/check", [&](const Request &req, Response &res) {
  9008. x_custom = req.get_header_value("X-Custom");
  9009. cookie = req.get_header_value("Cookie");
  9010. xff = req.get_header_value("X-Forwarded-For");
  9011. x_unicode = req.get_header_value("X-Unicode");
  9012. x_iis = req.get_header_value("X-IIS");
  9013. res.set_content("ok", "text/plain");
  9014. });
  9015. thread t = thread([&] { svr.listen(HOST, PORT); });
  9016. auto se = detail::scope_exit([&] {
  9017. svr.stop();
  9018. t.join();
  9019. ASSERT_FALSE(svr.is_running());
  9020. });
  9021. svr.wait_until_ready();
  9022. const std::string req = "GET /check HTTP/1.1\r\n"
  9023. "Host: localhost\r\n"
  9024. "X-Custom: a%0D%0AInjected: b\r\n"
  9025. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9026. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9027. "X-Unicode: %E3%81%82\r\n"
  9028. "X-IIS: %u00E9\r\n"
  9029. "Connection: close\r\n"
  9030. "\r\n";
  9031. std::string res;
  9032. ASSERT_TRUE(send_request(5, req, &res));
  9033. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9034. // Every value must be returned verbatim (wire form), with no decoding.
  9035. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9036. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9037. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9038. EXPECT_EQ("%E3%81%82", x_unicode);
  9039. EXPECT_EQ("%u00E9", x_iis);
  9040. }
  9041. // Applications that previously relied on automatic percent-decoding can
  9042. // reproduce the old behavior by explicitly calling decode_path_component()
  9043. // or, for RFC 3986 conformance, decode_uri_component().
  9044. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9045. Server svr;
  9046. std::string decoded;
  9047. svr.Get("/check", [&](const Request &req, Response &res) {
  9048. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9049. res.set_content("ok", "text/plain");
  9050. });
  9051. thread t = thread([&] { svr.listen(HOST, PORT); });
  9052. auto se = detail::scope_exit([&] {
  9053. svr.stop();
  9054. t.join();
  9055. ASSERT_FALSE(svr.is_running());
  9056. });
  9057. svr.wait_until_ready();
  9058. const std::string req = "GET /check HTTP/1.1\r\n"
  9059. "Host: localhost\r\n"
  9060. "X-Custom: hello%20world\r\n"
  9061. "Connection: close\r\n"
  9062. "\r\n";
  9063. std::string res;
  9064. ASSERT_TRUE(send_request(5, req, &res));
  9065. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9066. EXPECT_EQ("hello world", decoded);
  9067. }
  9068. // Regression test for #2033. Browsers send Referer values that include
  9069. // percent-encoded characters such as %0A inside the URL. Decoding the
  9070. // header value would either trip the post-decode CR/LF/NUL guard (the
  9071. // original bug, returning 400) or, after that guard was relaxed, silently
  9072. // store a literal LF — both unacceptable. The wire form must round-trip.
  9073. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9074. Server svr;
  9075. std::string referer;
  9076. svr.Get("/check", [&](const Request &req, Response &res) {
  9077. referer = req.get_header_value("Referer");
  9078. res.set_content("ok", "text/plain");
  9079. });
  9080. thread t = thread([&] { svr.listen(HOST, PORT); });
  9081. auto se = detail::scope_exit([&] {
  9082. svr.stop();
  9083. t.join();
  9084. ASSERT_FALSE(svr.is_running());
  9085. });
  9086. svr.wait_until_ready();
  9087. const std::string req = "GET /check HTTP/1.1\r\n"
  9088. "Host: localhost\r\n"
  9089. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9090. "Connection: close\r\n"
  9091. "\r\n";
  9092. std::string res;
  9093. ASSERT_TRUE(send_request(5, req, &res));
  9094. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9095. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9096. }
  9097. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9098. Server svr;
  9099. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9100. res.set_header("Cache-Control", "no-cache");
  9101. res.set_chunked_content_provider(
  9102. "text/event-stream", [](size_t offset, DataSink &sink) {
  9103. std::string s = "data:";
  9104. s += std::to_string(offset);
  9105. s += "\n\n";
  9106. auto ret = sink.write(s.data(), s.size());
  9107. EXPECT_TRUE(ret);
  9108. std::this_thread::sleep_for(std::chrono::seconds(1));
  9109. return true;
  9110. });
  9111. });
  9112. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9113. svr.wait_until_ready();
  9114. Client client(HOST, PORT);
  9115. const Headers headers = {{"Accept", "text/event-stream"}};
  9116. auto get_thread = std::thread([&client, &headers]() {
  9117. auto res = client.Get(
  9118. "/events", headers,
  9119. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9120. });
  9121. auto se = detail::scope_exit([&] {
  9122. svr.stop();
  9123. get_thread.join();
  9124. listen_thread.join();
  9125. ASSERT_FALSE(svr.is_running());
  9126. });
  9127. // Give GET time to get a few messages.
  9128. std::this_thread::sleep_for(std::chrono::seconds(2));
  9129. }
  9130. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9131. httplib::Server svr;
  9132. svr.Post("/hi",
  9133. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9134. res.status = StatusCode::OK_200;
  9135. });
  9136. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9137. svr.wait_until_ready();
  9138. Client cli(HOST, PORT);
  9139. auto res = cli.Post("/hi", "data", "text/plain");
  9140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9141. EXPECT_EQ(StatusCode::OK_200, res->status);
  9142. svr.stop();
  9143. thread.join();
  9144. ASSERT_FALSE(svr.is_running());
  9145. res = cli.Post("/hi", "data", "text/plain");
  9146. ASSERT_FALSE(res);
  9147. }
  9148. TEST(ServerStopTest, ListenFailure) {
  9149. Server svr;
  9150. auto t = thread([&]() {
  9151. auto ret = svr.listen("????", PORT);
  9152. EXPECT_FALSE(ret);
  9153. });
  9154. svr.wait_until_ready();
  9155. svr.stop();
  9156. t.join();
  9157. }
  9158. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9159. TEST(ServerStopTest, Decommision) {
  9160. Server svr;
  9161. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9162. for (int i = 0; i < 4; i++) {
  9163. auto is_even = !(i % 2);
  9164. std::thread t{[&] {
  9165. try {
  9166. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9167. if (is_even) {
  9168. throw std::runtime_error("Some thing that happens to go wrong.");
  9169. }
  9170. svr.listen(HOST, PORT);
  9171. } catch (...) { svr.decommission(); }
  9172. }};
  9173. svr.wait_until_ready();
  9174. // Server is up
  9175. {
  9176. Client cli(HOST, PORT);
  9177. auto res = cli.Get("/hi");
  9178. if (is_even) {
  9179. EXPECT_FALSE(res);
  9180. } else {
  9181. EXPECT_TRUE(res);
  9182. EXPECT_EQ("hi...", res->body);
  9183. }
  9184. }
  9185. svr.stop();
  9186. t.join();
  9187. // Server is down...
  9188. {
  9189. Client cli(HOST, PORT);
  9190. auto res = cli.Get("/hi");
  9191. EXPECT_FALSE(res);
  9192. }
  9193. }
  9194. }
  9195. #endif
  9196. // Helper function for string body upload progress tests
  9197. template <typename SetupHandler, typename ClientCall>
  9198. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9199. ClientCall &&client_call,
  9200. const string &body) {
  9201. Server svr;
  9202. setup_handler(svr);
  9203. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9204. auto se = detail::scope_exit([&] {
  9205. svr.stop();
  9206. t.join();
  9207. });
  9208. svr.wait_until_ready();
  9209. Client cli(HOST, PORT);
  9210. vector<uint64_t> progress_values;
  9211. bool progress_called = false;
  9212. auto res =
  9213. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9214. progress_values.push_back(current);
  9215. progress_called = true;
  9216. return true;
  9217. });
  9218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9219. EXPECT_EQ(200, res->status);
  9220. EXPECT_TRUE(progress_called);
  9221. }
  9222. TEST(UploadProgressTest, PostStringBodyBasic) {
  9223. TestStringBodyUploadProgress(
  9224. [](Server &svr) {
  9225. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9226. res.set_content("received", "text/plain");
  9227. });
  9228. },
  9229. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9230. return cli.Post("/test", body, "text/plain", progress_callback);
  9231. },
  9232. "test data for upload progress");
  9233. }
  9234. TEST(UploadProgressTest, PutStringBodyBasic) {
  9235. TestStringBodyUploadProgress(
  9236. [](Server &svr) {
  9237. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9238. res.set_content("put received", "text/plain");
  9239. });
  9240. },
  9241. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9242. return cli.Put("/test", body, "text/plain", progress_callback);
  9243. },
  9244. "put test data for upload progress");
  9245. }
  9246. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9247. TestStringBodyUploadProgress(
  9248. [](Server &svr) {
  9249. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9250. res.set_content("patch received", "text/plain");
  9251. });
  9252. },
  9253. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9254. return cli.Patch("/test", body, "text/plain", progress_callback);
  9255. },
  9256. "patch test data for upload progress");
  9257. }
  9258. // Helper function for content provider upload progress tests
  9259. template <typename SetupHandler, typename ClientCall>
  9260. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9261. ClientCall &&client_call) {
  9262. Server svr;
  9263. setup_handler(svr);
  9264. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9265. auto se = detail::scope_exit([&] {
  9266. svr.stop();
  9267. t.join();
  9268. });
  9269. svr.wait_until_ready();
  9270. Client cli(HOST, PORT);
  9271. vector<uint64_t> progress_values;
  9272. auto res =
  9273. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9274. progress_values.push_back(current);
  9275. return true;
  9276. });
  9277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9278. EXPECT_EQ(200, res->status);
  9279. EXPECT_FALSE(progress_values.empty());
  9280. }
  9281. TEST(UploadProgressTest, PostContentProviderProgress) {
  9282. TestContentProviderUploadProgress(
  9283. [](Server &svr) {
  9284. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9285. res.set_content("provider received", "text/plain");
  9286. });
  9287. },
  9288. [](Client &cli, UploadProgress progress_callback) {
  9289. return cli.Post(
  9290. "/test", 10,
  9291. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9292. sink.os << "test data";
  9293. return true;
  9294. },
  9295. "text/plain", progress_callback);
  9296. });
  9297. }
  9298. // Helper function for multipart upload progress tests
  9299. template <typename SetupHandler, typename ClientCall>
  9300. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9301. ClientCall &&client_call,
  9302. const string &endpoint) {
  9303. Server svr;
  9304. setup_handler(svr);
  9305. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9306. auto se = detail::scope_exit([&] {
  9307. svr.stop();
  9308. t.join();
  9309. });
  9310. svr.wait_until_ready();
  9311. Client cli(HOST, PORT);
  9312. vector<uint64_t> progress_values;
  9313. UploadFormDataItems items = {
  9314. {"field1", "value1", "", ""},
  9315. {"field2", "longer value for progress tracking test", "", ""},
  9316. {"file1", "file content data for upload progress", "test.txt",
  9317. "text/plain"}};
  9318. auto res = client_call(cli, endpoint, items,
  9319. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9320. progress_values.push_back(current);
  9321. return true;
  9322. });
  9323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9324. EXPECT_EQ(200, res->status);
  9325. EXPECT_FALSE(progress_values.empty());
  9326. }
  9327. TEST(UploadProgressTest, PostMultipartProgress) {
  9328. TestMultipartUploadProgress(
  9329. [](Server &svr) {
  9330. svr.Post("/multipart", [](const Request &req, Response &res) {
  9331. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9332. res.set_content("multipart received", "text/plain");
  9333. });
  9334. },
  9335. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9336. UploadProgress progress_callback) {
  9337. return cli.Post(endpoint, items, progress_callback);
  9338. },
  9339. "/multipart");
  9340. }
  9341. // Helper function for basic download progress tests
  9342. template <typename SetupHandler, typename ClientCall>
  9343. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9344. ClientCall &&client_call, const string &endpoint,
  9345. size_t expected_content_size) {
  9346. Server svr;
  9347. setup_handler(svr);
  9348. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9349. auto se = detail::scope_exit([&] {
  9350. svr.stop();
  9351. t.join();
  9352. });
  9353. svr.wait_until_ready();
  9354. Client cli(HOST, PORT);
  9355. vector<uint64_t> progress_values;
  9356. auto res = client_call(cli, endpoint,
  9357. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9358. progress_values.push_back(current);
  9359. return true;
  9360. });
  9361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9362. EXPECT_EQ(200, res->status);
  9363. EXPECT_FALSE(progress_values.empty());
  9364. EXPECT_EQ(expected_content_size, res->body.size());
  9365. }
  9366. TEST(DownloadProgressTest, GetBasic) {
  9367. TestBasicDownloadProgress(
  9368. [](Server &svr) {
  9369. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9370. string content(1000, 'D');
  9371. res.set_content(content, "text/plain");
  9372. });
  9373. },
  9374. [](Client &cli, const string &endpoint,
  9375. DownloadProgress progress_callback) {
  9376. return cli.Get(endpoint, progress_callback);
  9377. },
  9378. "/download", 1000u);
  9379. }
  9380. // Helper function for content receiver download progress tests
  9381. template <typename SetupHandler, typename ClientCall>
  9382. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9383. ClientCall &&client_call,
  9384. const string &endpoint,
  9385. size_t expected_content_size) {
  9386. Server svr;
  9387. setup_handler(svr);
  9388. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9389. auto se = detail::scope_exit([&] {
  9390. svr.stop();
  9391. t.join();
  9392. });
  9393. svr.wait_until_ready();
  9394. Client cli(HOST, PORT);
  9395. vector<uint64_t> progress_values;
  9396. string received_body;
  9397. auto res = client_call(
  9398. cli, endpoint,
  9399. [&](const char *data, size_t data_length) -> bool {
  9400. received_body.append(data, data_length);
  9401. return true;
  9402. },
  9403. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9404. progress_values.push_back(current);
  9405. return true;
  9406. });
  9407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9408. EXPECT_EQ(200, res->status);
  9409. EXPECT_FALSE(progress_values.empty());
  9410. EXPECT_EQ(expected_content_size, received_body.size());
  9411. EXPECT_TRUE(res->body.empty());
  9412. }
  9413. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9414. TestContentReceiverDownloadProgress(
  9415. [](Server &svr) {
  9416. svr.Get("/download-receiver",
  9417. [](const Request & /*req*/, Response &res) {
  9418. string content(2000, 'R');
  9419. res.set_content(content, "text/plain");
  9420. });
  9421. },
  9422. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9423. DownloadProgress progress_callback) {
  9424. return cli.Get(endpoint, content_receiver, progress_callback);
  9425. },
  9426. "/download-receiver", 2000u);
  9427. }
  9428. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9429. // A provider reaching a pass with nothing to hand over - an empty buffer
  9430. // popped off a queue, say - must not be taken to mean the body is finished.
  9431. // It used to end the loop with the terminating chunk unwritten while the
  9432. // server still considered the response complete, so the peer waited for an
  9433. // end that never arrived.
  9434. Server svr;
  9435. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9436. auto step = std::make_shared<int>(0);
  9437. res.set_chunked_content_provider("text/plain",
  9438. [step](size_t /*offset*/, DataSink &sink) {
  9439. switch ((*step)++) {
  9440. case 0: sink.write("", 0); break;
  9441. case 1: sink.write("hello", 5); break;
  9442. default: sink.done(); break;
  9443. }
  9444. return true;
  9445. });
  9446. });
  9447. auto port = svr.bind_to_any_port(HOST);
  9448. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9449. auto listen_se = detail::scope_exit([&] {
  9450. svr.stop();
  9451. listen_thread.join();
  9452. ASSERT_FALSE(svr.is_running());
  9453. });
  9454. svr.wait_until_ready();
  9455. Client cli(HOST, port);
  9456. // Without the fix the body is never terminated, so bound the wait rather
  9457. // than letting the test hang on the default read timeout.
  9458. cli.set_read_timeout(5, 0);
  9459. auto res = cli.Get("/stream");
  9460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9461. EXPECT_EQ(StatusCode::OK_200, res->status);
  9462. EXPECT_EQ("hello", res->body);
  9463. }
  9464. TEST(StreamingTest, NoContentLengthStreaming) {
  9465. Server svr;
  9466. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9467. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9468. if (offset < 6) {
  9469. sink.os << (offset < 3 ? "a" : "b");
  9470. } else {
  9471. sink.done();
  9472. }
  9473. return true;
  9474. });
  9475. });
  9476. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9477. auto listen_se = detail::scope_exit([&] {
  9478. svr.stop();
  9479. listen_thread.join();
  9480. ASSERT_FALSE(svr.is_running());
  9481. });
  9482. svr.wait_until_ready();
  9483. Client client(HOST, PORT);
  9484. auto get_thread = std::thread([&client]() {
  9485. std::string s;
  9486. auto res =
  9487. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9488. s += std::string(data, len);
  9489. return true;
  9490. });
  9491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9492. EXPECT_EQ(StatusCode::OK_200, res->status);
  9493. EXPECT_EQ("aaabbb", s);
  9494. });
  9495. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9496. // Give GET time to get a few messages.
  9497. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9498. }
  9499. TEST(MountTest, Unmount) {
  9500. Server svr;
  9501. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9502. auto se = detail::scope_exit([&] {
  9503. svr.stop();
  9504. listen_thread.join();
  9505. ASSERT_FALSE(svr.is_running());
  9506. });
  9507. svr.wait_until_ready();
  9508. Client cli("localhost", PORT);
  9509. svr.set_mount_point("/mount2", "./www2");
  9510. auto res = cli.Get("/");
  9511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9512. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9513. res = cli.Get("/mount2/dir/test.html");
  9514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9515. EXPECT_EQ(StatusCode::OK_200, res->status);
  9516. svr.set_mount_point("/", "./www");
  9517. res = cli.Get("/dir/");
  9518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9519. EXPECT_EQ(StatusCode::OK_200, res->status);
  9520. svr.remove_mount_point("/");
  9521. res = cli.Get("/dir/");
  9522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9523. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9524. svr.remove_mount_point("/mount2");
  9525. res = cli.Get("/mount2/dir/test.html");
  9526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9527. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9528. }
  9529. TEST(MountTest, PathSegmentBoundary) {
  9530. Server svr;
  9531. svr.set_mount_point("/mount2", "./www2");
  9532. svr.set_mount_point("/", "./www");
  9533. auto port = svr.bind_to_any_port(HOST);
  9534. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9535. auto se = detail::scope_exit([&] {
  9536. svr.stop();
  9537. listen_thread.join();
  9538. ASSERT_FALSE(svr.is_running());
  9539. });
  9540. svr.wait_until_ready();
  9541. Client cli(HOST, port);
  9542. auto res = cli.Get("/mount2/dir/test.html");
  9543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9544. EXPECT_EQ(StatusCode::OK_200, res->status);
  9545. // "/mount2" must not match part-way through a path segment.
  9546. res = cli.Get("/mount2dir/test.html");
  9547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9548. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9549. // A mount point ending in '/' keeps matching every path below it.
  9550. res = cli.Get("/dir/test.html");
  9551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9552. EXPECT_EQ(StatusCode::OK_200, res->status);
  9553. }
  9554. TEST(MountTest, Redicect) {
  9555. Server svr;
  9556. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9557. auto se = detail::scope_exit([&] {
  9558. svr.stop();
  9559. listen_thread.join();
  9560. ASSERT_FALSE(svr.is_running());
  9561. });
  9562. svr.set_mount_point("/", "./www");
  9563. svr.wait_until_ready();
  9564. Client cli("localhost", PORT);
  9565. auto res = cli.Get("/dir/");
  9566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9567. EXPECT_EQ(StatusCode::OK_200, res->status);
  9568. res = cli.Get("/dir");
  9569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9570. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9571. res = cli.Get("/file");
  9572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9573. EXPECT_EQ(StatusCode::OK_200, res->status);
  9574. res = cli.Get("/file/");
  9575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9576. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9577. cli.set_follow_location(true);
  9578. res = cli.Get("/dir");
  9579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9580. EXPECT_EQ(StatusCode::OK_200, res->status);
  9581. }
  9582. TEST(MountTest, MultibytesPathName) {
  9583. Server svr;
  9584. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9585. auto se = detail::scope_exit([&] {
  9586. svr.stop();
  9587. listen_thread.join();
  9588. ASSERT_FALSE(svr.is_running());
  9589. });
  9590. svr.set_mount_point("/", "./www");
  9591. svr.wait_until_ready();
  9592. Client cli("localhost", PORT);
  9593. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9595. EXPECT_EQ(StatusCode::OK_200, res->status);
  9596. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9597. }
  9598. #ifdef _WIN32
  9599. // Issue #2435: mmap::open() must succeed even when another handle holds
  9600. // the file open for writing (e.g. an active log file).
  9601. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9602. const char *path = "mmap_concurrent_writer_test.txt";
  9603. const char *content = "hello";
  9604. {
  9605. std::ofstream f(path, std::ios::binary);
  9606. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9607. }
  9608. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9609. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9610. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9611. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9612. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9613. detail::mmap m(path);
  9614. ASSERT_TRUE(m.is_open());
  9615. EXPECT_EQ(strlen(content), m.size());
  9616. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9617. }
  9618. #endif
  9619. #ifndef _WIN32
  9620. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9621. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9622. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9623. TEST(MmapTest, FailedMappingIsNotOpen) {
  9624. const char *path = "./mmap_failed_mapping_test_dir";
  9625. ASSERT_EQ(0, ::mkdir(path, 0755));
  9626. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9627. detail::mmap m(path);
  9628. EXPECT_FALSE(m.is_open());
  9629. EXPECT_EQ(0U, m.size());
  9630. EXPECT_NE(static_cast<const void *>(m.data()),
  9631. static_cast<const void *>(MAP_FAILED));
  9632. }
  9633. #endif
  9634. TEST(KeepAliveTest, ReadTimeout) {
  9635. Server svr;
  9636. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9637. std::this_thread::sleep_for(std::chrono::seconds(2));
  9638. res.set_content("a", "text/plain");
  9639. });
  9640. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9641. res.set_content("b", "text/plain");
  9642. });
  9643. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9644. auto se = detail::scope_exit([&] {
  9645. svr.stop();
  9646. listen_thread.join();
  9647. ASSERT_FALSE(svr.is_running());
  9648. });
  9649. svr.wait_until_ready();
  9650. Client cli("localhost", PORT);
  9651. cli.set_keep_alive(true);
  9652. cli.set_read_timeout(std::chrono::seconds(1));
  9653. auto resa = cli.Get("/a");
  9654. ASSERT_FALSE(resa);
  9655. EXPECT_EQ(Error::Read, resa.error());
  9656. auto resb = cli.Get("/b");
  9657. ASSERT_TRUE(resb);
  9658. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9659. EXPECT_EQ("b", resb->body);
  9660. }
  9661. TEST(KeepAliveTest, MaxCount) {
  9662. size_t keep_alive_max_count = 3;
  9663. Server svr;
  9664. svr.set_keep_alive_max_count(keep_alive_max_count);
  9665. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9666. res.set_content("Hello World!", "text/plain");
  9667. });
  9668. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9669. auto se = detail::scope_exit([&] {
  9670. svr.stop();
  9671. listen_thread.join();
  9672. ASSERT_FALSE(svr.is_running());
  9673. });
  9674. svr.wait_until_ready();
  9675. Client cli(HOST, PORT);
  9676. cli.set_keep_alive(true);
  9677. for (size_t i = 0; i < 5; i++) {
  9678. auto result = cli.Get("/hi");
  9679. ASSERT_TRUE(result);
  9680. EXPECT_EQ(StatusCode::OK_200, result->status);
  9681. if (i == keep_alive_max_count - 1) {
  9682. EXPECT_EQ("close", result->get_header_value("Connection"));
  9683. } else {
  9684. EXPECT_FALSE(result->has_header("Connection"));
  9685. }
  9686. }
  9687. }
  9688. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  9689. // can pull the next one into the server's buffer. The server must serve it
  9690. // without waiting for the socket to become readable again. The keep-alive
  9691. // timeout outlasts the client's read timeout, so a request left waiting for it
  9692. // shows up as a missing response.
  9693. static void serve_pipelining_routes(Server &svr,
  9694. const std::function<void(int)> &client) {
  9695. svr.set_keep_alive_timeout(5);
  9696. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  9697. res.set_content("hi " + req.matches[1].str(), "text/plain");
  9698. });
  9699. svr.Post("/echo", [](const Request &req, Response &res) {
  9700. res.set_content("echo " + req.body, "text/plain");
  9701. });
  9702. auto port = svr.bind_to_any_port(HOST);
  9703. thread t = thread([&] { svr.listen_after_bind(); });
  9704. auto se = detail::scope_exit([&] {
  9705. svr.stop();
  9706. t.join();
  9707. });
  9708. svr.wait_until_ready();
  9709. client(port);
  9710. }
  9711. static std::string
  9712. send_pipelined_requests(const std::vector<std::string> &parts) {
  9713. Server svr;
  9714. std::string res;
  9715. serve_pipelining_routes(svr, [&](int port) {
  9716. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  9717. });
  9718. return res;
  9719. }
  9720. static void expect_in_order(const std::string &res,
  9721. const std::vector<std::string> &bodies) {
  9722. size_t pos = 0;
  9723. for (const auto &body : bodies) {
  9724. pos = res.find(body, pos);
  9725. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  9726. pos += body.size();
  9727. }
  9728. }
  9729. TEST(KeepAliveTest, PipelinedRequests) {
  9730. auto res = send_pipelined_requests(
  9731. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9732. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9733. "Content-Length: 4\r\n\r\nbody"
  9734. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9735. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  9736. }
  9737. // The second request starts in the server's buffer and ends on the socket.
  9738. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  9739. auto res =
  9740. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9741. "GET /hi/2 HTTP/1.1\r\nHo",
  9742. "st: localhost\r\nConnection: close\r\n\r\n"});
  9743. expect_in_order(res, {"hi 1", "hi 2"});
  9744. }
  9745. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  9746. // CRLF after a body does not turn into a 400 for the next request.
  9747. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  9748. auto res = send_pipelined_requests(
  9749. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9750. "Content-Length: 4\r\n\r\nbody\r\n"
  9751. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9752. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  9753. expect_in_order(res, {"echo body", "hi 2"});
  9754. }
  9755. // Where an unparsable request ends is unknown, so what follows it in the buffer
  9756. // must not be served as the next request.
  9757. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  9758. auto res = send_pipelined_requests(
  9759. {"INVALID REQUEST LINE\r\n\r\n"
  9760. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  9761. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9762. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  9763. }
  9764. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9765. // Over TLS, the next request is held by the TLS library as already decrypted
  9766. // data rather than on the socket.
  9767. TEST(KeepAliveTest, SSLPipelinedRequests) {
  9768. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9769. std::string res;
  9770. serve_pipelining_routes(svr, [&](int port) {
  9771. auto error = Error::Success;
  9772. auto sock = detail::create_client_socket(
  9773. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9774. /*connection_timeout_sec=*/5, 0,
  9775. /*read_timeout_sec=*/2, 0,
  9776. /*write_timeout_sec=*/5, 0, std::string(), error);
  9777. ASSERT_NE(INVALID_SOCKET, sock);
  9778. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9779. auto ctx = SSL_CTX_new(TLS_client_method());
  9780. auto ssl = SSL_new(ctx);
  9781. auto ssl_se = detail::scope_exit([&] {
  9782. SSL_free(ssl);
  9783. SSL_CTX_free(ctx);
  9784. });
  9785. SSL_set_fd(ssl, static_cast<int>(sock));
  9786. ASSERT_EQ(1, SSL_connect(ssl));
  9787. // One write, so all three requests arrive in one TLS record
  9788. const std::string req =
  9789. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9790. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9791. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  9792. ASSERT_EQ(static_cast<int>(req.size()),
  9793. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  9794. char buf[512];
  9795. int n;
  9796. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9797. res.append(buf, static_cast<size_t>(n));
  9798. }
  9799. });
  9800. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  9801. }
  9802. #endif
  9803. TEST(KeepAliveTest, Issue1041) {
  9804. Server svr;
  9805. svr.set_keep_alive_timeout(3);
  9806. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9807. res.set_content("Hello World!", "text/plain");
  9808. });
  9809. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9810. auto se = detail::scope_exit([&] {
  9811. svr.stop();
  9812. listen_thread.join();
  9813. ASSERT_FALSE(svr.is_running());
  9814. });
  9815. svr.wait_until_ready();
  9816. Client cli(HOST, PORT);
  9817. cli.set_keep_alive(true);
  9818. auto result = cli.Get("/hi");
  9819. ASSERT_TRUE(result);
  9820. EXPECT_EQ(StatusCode::OK_200, result->status);
  9821. std::this_thread::sleep_for(std::chrono::seconds(5));
  9822. result = cli.Get("/hi");
  9823. ASSERT_TRUE(result);
  9824. EXPECT_EQ(StatusCode::OK_200, result->status);
  9825. }
  9826. TEST(KeepAliveTest, Issue1959) {
  9827. Server svr;
  9828. svr.set_keep_alive_timeout(5);
  9829. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9830. res.set_content("a", "text/plain");
  9831. });
  9832. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9833. auto se = detail::scope_exit([&] {
  9834. if (!svr.is_running()) return;
  9835. svr.stop();
  9836. listen_thread.join();
  9837. ASSERT_FALSE(svr.is_running());
  9838. });
  9839. svr.wait_until_ready();
  9840. Client cli("localhost", PORT);
  9841. cli.set_keep_alive(true);
  9842. using namespace std::chrono;
  9843. auto start = steady_clock::now();
  9844. cli.Get("/a");
  9845. svr.stop();
  9846. listen_thread.join();
  9847. auto end = steady_clock::now();
  9848. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9849. EXPECT_LT(elapsed, 5000);
  9850. }
  9851. #ifdef CPPHTTPLIB_SSL_ENABLED
  9852. TEST(KeepAliveTest, SSLClientReconnection) {
  9853. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9854. ASSERT_TRUE(svr.is_valid());
  9855. svr.set_keep_alive_timeout(1);
  9856. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9857. res.set_content("Hello World!", "text/plain");
  9858. });
  9859. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9860. auto se = detail::scope_exit([&] {
  9861. svr.stop();
  9862. listen_thread.join();
  9863. ASSERT_FALSE(svr.is_running());
  9864. });
  9865. svr.wait_until_ready();
  9866. SSLClient cli(HOST, PORT);
  9867. cli.enable_server_certificate_verification(false);
  9868. cli.set_keep_alive(true);
  9869. auto result = cli.Get("/hi");
  9870. ASSERT_TRUE(result);
  9871. EXPECT_EQ(StatusCode::OK_200, result->status);
  9872. result = cli.Get("/hi");
  9873. ASSERT_TRUE(result);
  9874. EXPECT_EQ(StatusCode::OK_200, result->status);
  9875. std::this_thread::sleep_for(std::chrono::seconds(2));
  9876. // Recoonect
  9877. result = cli.Get("/hi");
  9878. ASSERT_TRUE(result);
  9879. EXPECT_EQ(StatusCode::OK_200, result->status);
  9880. result = cli.Get("/hi");
  9881. ASSERT_TRUE(result);
  9882. EXPECT_EQ(StatusCode::OK_200, result->status);
  9883. }
  9884. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9885. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9886. ASSERT_TRUE(svr.is_valid());
  9887. svr.set_keep_alive_timeout(1);
  9888. std::string content = "reconnect";
  9889. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9890. res.set_content("Hello World!", "text/plain");
  9891. });
  9892. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9893. auto se = detail::scope_exit([&] {
  9894. svr.stop();
  9895. listen_thread.join();
  9896. ASSERT_FALSE(svr.is_running());
  9897. });
  9898. svr.wait_until_ready();
  9899. SSLClient cli(HOST, PORT);
  9900. cli.enable_server_certificate_verification(false);
  9901. cli.set_keep_alive(true);
  9902. auto result = cli.Post(
  9903. "/hi", content.size(),
  9904. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9905. sink.write(content.c_str(), content.size());
  9906. return true;
  9907. },
  9908. "text/plain");
  9909. ASSERT_TRUE(result);
  9910. EXPECT_EQ(200, result->status);
  9911. std::this_thread::sleep_for(std::chrono::seconds(2));
  9912. // Recoonect
  9913. result = cli.Post(
  9914. "/hi", content.size(),
  9915. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9916. sink.write(content.c_str(), content.size());
  9917. return true;
  9918. },
  9919. "text/plain");
  9920. ASSERT_TRUE(result);
  9921. EXPECT_EQ(200, result->status);
  9922. result = cli.Post(
  9923. "/hi", content.size(),
  9924. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9925. sink.write(content.c_str(), content.size());
  9926. return true;
  9927. },
  9928. "text/plain");
  9929. ASSERT_TRUE(result);
  9930. EXPECT_EQ(200, result->status);
  9931. }
  9932. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  9933. using namespace httplib::tls;
  9934. {
  9935. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9936. ASSERT_TRUE(svr.is_valid());
  9937. svr.Get("/sni", [&](const Request &req, Response &res) {
  9938. std::string expected = req.sni();
  9939. EXPECT_EQ(expected, req.get_param_value("expected"));
  9940. res.set_content("ok", "text/plain");
  9941. });
  9942. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9943. auto se = detail::scope_exit([&] {
  9944. svr.stop();
  9945. listen_thread.join();
  9946. ASSERT_FALSE(svr.is_running());
  9947. });
  9948. svr.wait_until_ready();
  9949. {
  9950. SSLClient cli("localhost", PORT);
  9951. cli.enable_server_certificate_verification(false);
  9952. auto res = cli.Get("/sni?expected=localhost");
  9953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9954. }
  9955. {
  9956. SSLClient cli("::1", PORT);
  9957. cli.enable_server_certificate_verification(false);
  9958. auto res = cli.Get("/sni?expected=");
  9959. // NOTE: This may fail if the server is listening on IPv4 only
  9960. // (e.g., when localhost resolves to 127.0.0.1 only)
  9961. if (res) {
  9962. EXPECT_EQ(StatusCode::OK_200, res->status);
  9963. } else {
  9964. EXPECT_EQ(Error::Connection, res.error());
  9965. }
  9966. }
  9967. }
  9968. }
  9969. #endif
  9970. TEST(ClientProblemDetectionTest, ContentProvider) {
  9971. Server svr;
  9972. size_t content_length = 1024 * 1024;
  9973. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9974. res.set_content_provider(
  9975. content_length, "text/plain",
  9976. [&](size_t offset, size_t length, DataSink &sink) {
  9977. auto out_len = std::min(length, static_cast<size_t>(1024));
  9978. std::string out(out_len, '@');
  9979. sink.write(out.data(), out_len);
  9980. return offset < 4096;
  9981. },
  9982. [](bool success) { ASSERT_FALSE(success); });
  9983. });
  9984. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  9985. res.set_content_provider(
  9986. 0, "text/plain",
  9987. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  9988. EXPECT_TRUE(false);
  9989. return true;
  9990. },
  9991. [](bool success) { ASSERT_FALSE(success); });
  9992. });
  9993. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9994. auto se = detail::scope_exit([&] {
  9995. svr.stop();
  9996. listen_thread.join();
  9997. ASSERT_FALSE(svr.is_running());
  9998. });
  9999. svr.wait_until_ready();
  10000. Client cli("localhost", PORT);
  10001. {
  10002. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10003. size_t /*data_length*/) { return false; });
  10004. ASSERT_FALSE(res);
  10005. }
  10006. {
  10007. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10008. size_t /*data_length*/) { return false; });
  10009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10010. }
  10011. }
  10012. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10013. // A provider that reports success without writing anything and without
  10014. // calling done() used to be handed the same offset and length again on every
  10015. // pass, so it spun for as long as the peer stayed connected.
  10016. Server svr;
  10017. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10018. res.set_content("ok", "text/plain");
  10019. });
  10020. auto port = svr.bind_to_any_port(HOST);
  10021. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10022. auto se = detail::scope_exit([&] {
  10023. svr.stop();
  10024. listen_thread.join();
  10025. ASSERT_FALSE(svr.is_running());
  10026. });
  10027. svr.wait_until_ready();
  10028. std::atomic<int> call_count{0};
  10029. Client cli(HOST, port);
  10030. auto res = cli.Post(
  10031. "/", 1024,
  10032. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10033. // Give up after enough passes to show the spin, so that losing the
  10034. // check below fails this test instead of hanging it.
  10035. return ++call_count < 100;
  10036. },
  10037. "text/plain");
  10038. ASSERT_FALSE(res);
  10039. EXPECT_EQ(Error::Write, res.error());
  10040. EXPECT_EQ(1, call_count.load());
  10041. }
  10042. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10043. // A writer only has to assign `write`. The other three used to be left as
  10044. // empty std::functions, so a provider calling one threw
  10045. // std::bad_function_call out of the thread running it and took the whole
  10046. // process down.
  10047. DataSink sink;
  10048. std::string written;
  10049. sink.write = [&](const char *data, size_t data_len) {
  10050. written.append(data, data_len);
  10051. return true;
  10052. };
  10053. EXPECT_TRUE(sink.is_writable());
  10054. sink.done();
  10055. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10056. EXPECT_TRUE(written.empty());
  10057. }
  10058. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10059. // A sink that cannot carry trailers still has to finish.
  10060. DataSink sink;
  10061. auto done_count = 0;
  10062. sink.done = [&]() { done_count++; };
  10063. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10064. EXPECT_EQ(1, done_count);
  10065. }
  10066. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10067. Server svr;
  10068. const std::string body(4096, 'x');
  10069. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10070. res.set_content_provider(body.size(), "text/plain",
  10071. [&](size_t offset, size_t length, DataSink &sink) {
  10072. sink.write(body.data() + offset, length);
  10073. sink.done();
  10074. return true;
  10075. });
  10076. });
  10077. auto port = svr.bind_to_any_port(HOST);
  10078. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10079. auto se = detail::scope_exit([&] {
  10080. svr.stop();
  10081. listen_thread.join();
  10082. ASSERT_FALSE(svr.is_running());
  10083. });
  10084. svr.wait_until_ready();
  10085. Client cli(HOST, port);
  10086. auto res = cli.Get("/");
  10087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10088. EXPECT_EQ(StatusCode::OK_200, res->status);
  10089. EXPECT_EQ(body, res->body);
  10090. }
  10091. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10092. Server svr;
  10093. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10094. res.set_content_provider(
  10095. 1024, "text/plain",
  10096. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10097. sink.write("hello", 5);
  10098. sink.done(); // short of the 1024 bytes the response promised
  10099. return true;
  10100. });
  10101. });
  10102. auto port = svr.bind_to_any_port(HOST);
  10103. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10104. auto se = detail::scope_exit([&] {
  10105. svr.stop();
  10106. listen_thread.join();
  10107. ASSERT_FALSE(svr.is_running());
  10108. });
  10109. svr.wait_until_ready();
  10110. Client cli(HOST, port);
  10111. cli.set_read_timeout(5, 0);
  10112. // The response is short of its Content-Length, so the client cannot read a
  10113. // complete body. What matters is that this returns at all: a no-op done()
  10114. // would leave the writer looping over a provider that never makes progress.
  10115. auto res = cli.Get("/");
  10116. EXPECT_FALSE(res);
  10117. }
  10118. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10119. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10120. // The compressed path builds the whole body before connecting, so this
  10121. // fails client-side and never reaches a server.
  10122. Client cli(HOST, PORT);
  10123. cli.set_compress(true);
  10124. auto res = cli.Post(
  10125. "/", 1024,
  10126. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10127. sink.write("hello", 5);
  10128. sink.done(); // short of the 1024 bytes the request announced
  10129. return true;
  10130. },
  10131. "text/plain");
  10132. ASSERT_FALSE(res);
  10133. EXPECT_EQ(Error::Write, res.error());
  10134. }
  10135. #endif
  10136. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10137. Server svr;
  10138. svr.set_error_handler([](Request const &, Response &res) -> void {
  10139. res.set_chunked_content_provider(
  10140. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10141. sink.os << "hello";
  10142. sink.os << "world";
  10143. sink.done();
  10144. return true;
  10145. });
  10146. });
  10147. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10148. auto se = detail::scope_exit([&] {
  10149. svr.stop();
  10150. listen_thread.join();
  10151. ASSERT_FALSE(svr.is_running());
  10152. });
  10153. svr.wait_until_ready();
  10154. Client cli("localhost", PORT);
  10155. auto res = cli.Get("/");
  10156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10157. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10158. EXPECT_EQ("helloworld", res->body);
  10159. }
  10160. TEST(LongPollingTest, ClientCloseDetection) {
  10161. Server svr;
  10162. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10163. res.set_chunked_content_provider(
  10164. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10165. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10166. sink.os << "hello";
  10167. auto count = 10;
  10168. while (count > 0 && sink.is_writable()) {
  10169. this_thread::sleep_for(chrono::milliseconds(10));
  10170. count--;
  10171. }
  10172. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10173. return true;
  10174. });
  10175. });
  10176. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10177. auto se = detail::scope_exit([&] {
  10178. svr.stop();
  10179. listen_thread.join();
  10180. ASSERT_FALSE(svr.is_running());
  10181. });
  10182. svr.wait_until_ready();
  10183. Client cli("localhost", PORT);
  10184. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10185. EXPECT_EQ("hello", string(data, data_length));
  10186. return false; // close the socket immediately.
  10187. });
  10188. ASSERT_FALSE(res);
  10189. }
  10190. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10191. Server svr;
  10192. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10193. res.set_chunked_content_provider(
  10194. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10195. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10196. sink.os << "hello";
  10197. EXPECT_TRUE(sink.os.good());
  10198. // Wait for the client to close the connection
  10199. auto count = 10;
  10200. while (count > 0 && sink.is_writable()) {
  10201. this_thread::sleep_for(chrono::milliseconds(10));
  10202. count--;
  10203. }
  10204. // After client disconnect, write repeatedly until the socket
  10205. // write actually fails (small writes may be absorbed by the
  10206. // kernel buffer)
  10207. std::string chunk(1024, 'x');
  10208. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10209. sink.os << chunk;
  10210. }
  10211. EXPECT_TRUE(sink.os.fail());
  10212. return true;
  10213. });
  10214. });
  10215. auto port = svr.bind_to_any_port("localhost");
  10216. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10217. auto se = detail::scope_exit([&] {
  10218. svr.stop();
  10219. listen_thread.join();
  10220. ASSERT_FALSE(svr.is_running());
  10221. });
  10222. svr.wait_until_ready();
  10223. Client cli("localhost", port);
  10224. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10225. EXPECT_EQ("hello", string(data, data_length));
  10226. return false; // close the socket immediately.
  10227. });
  10228. ASSERT_FALSE(res);
  10229. }
  10230. TEST(GetWithParametersTest, GetWithParameters) {
  10231. Server svr;
  10232. svr.Get("/", [&](const Request &req, Response &) {
  10233. EXPECT_EQ("world", req.get_param_value("hello"));
  10234. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10235. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10236. });
  10237. svr.Get("/params", [&](const Request &req, Response &) {
  10238. EXPECT_EQ("world", req.get_param_value("hello"));
  10239. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10240. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10241. });
  10242. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10243. EXPECT_EQ("resource-id", req.matches[1]);
  10244. EXPECT_EQ("foo", req.get_param_value("param1"));
  10245. EXPECT_EQ("bar", req.get_param_value("param2"));
  10246. });
  10247. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10248. EXPECT_EQ("user-id", req.path_params.at("id"));
  10249. EXPECT_EQ("foo", req.get_param_value("param1"));
  10250. EXPECT_EQ("bar", req.get_param_value("param2"));
  10251. });
  10252. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10253. auto se = detail::scope_exit([&] {
  10254. svr.stop();
  10255. listen_thread.join();
  10256. ASSERT_FALSE(svr.is_running());
  10257. });
  10258. svr.wait_until_ready();
  10259. {
  10260. Client cli(HOST, PORT);
  10261. Params params;
  10262. params.emplace("hello", "world");
  10263. params.emplace("hello2", "world2");
  10264. params.emplace("hello3", "world3");
  10265. auto res = cli.Get("/", params, Headers{});
  10266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10267. EXPECT_EQ(StatusCode::OK_200, res->status);
  10268. }
  10269. {
  10270. Client cli(HOST, PORT);
  10271. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10273. EXPECT_EQ(StatusCode::OK_200, res->status);
  10274. }
  10275. {
  10276. Client cli(HOST, PORT);
  10277. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10279. EXPECT_EQ(StatusCode::OK_200, res->status);
  10280. }
  10281. {
  10282. Client cli(HOST, PORT);
  10283. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10285. EXPECT_EQ(StatusCode::OK_200, res->status);
  10286. }
  10287. }
  10288. TEST(GetWithParametersTest, GetWithParameters2) {
  10289. Server svr;
  10290. svr.Get("/", [&](const Request &req, Response &res) {
  10291. auto text = req.get_param_value("hello");
  10292. res.set_content(text, "text/plain");
  10293. });
  10294. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10295. auto se = detail::scope_exit([&] {
  10296. svr.stop();
  10297. listen_thread.join();
  10298. ASSERT_FALSE(svr.is_running());
  10299. });
  10300. svr.wait_until_ready();
  10301. Client cli("localhost", PORT);
  10302. Params params;
  10303. params.emplace("hello", "world");
  10304. std::string body;
  10305. auto res = cli.Get("/", params, Headers{},
  10306. [&](const char *data, size_t data_length) {
  10307. body.append(data, data_length);
  10308. return true;
  10309. });
  10310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10311. EXPECT_EQ(StatusCode::OK_200, res->status);
  10312. EXPECT_EQ("world", body);
  10313. }
  10314. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10315. Server svr;
  10316. svr.Get("/search", [&](const Request &req, Response &res) {
  10317. auto q = req.get_param_value("q");
  10318. res.set_content(q, "text/plain");
  10319. });
  10320. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10321. auto se = detail::scope_exit([&] {
  10322. svr.stop();
  10323. listen_thread.join();
  10324. ASSERT_FALSE(svr.is_running());
  10325. });
  10326. svr.wait_until_ready();
  10327. Client cli("localhost", PORT);
  10328. // Verify that Get(path, params) works without requiring Headers argument
  10329. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10331. EXPECT_EQ(StatusCode::OK_200, res->status);
  10332. EXPECT_EQ("cpp-httplib", res->body);
  10333. }
  10334. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10335. auto host = "httpbingo.org";
  10336. auto path = std::string{"/range/32"};
  10337. #ifdef CPPHTTPLIB_SSL_ENABLED
  10338. SSLClient cli(host);
  10339. #else
  10340. Client cli(host);
  10341. #endif
  10342. cli.set_default_headers({make_range_header({{1, 10}})});
  10343. cli.set_connection_timeout(5);
  10344. {
  10345. auto res = cli.Get(path);
  10346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10347. EXPECT_EQ("bcdefghijk", res->body);
  10348. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10349. }
  10350. {
  10351. auto res = cli.Get(path);
  10352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10353. EXPECT_EQ("bcdefghijk", res->body);
  10354. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10355. }
  10356. }
  10357. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10358. Server svr;
  10359. svr.set_default_headers({{"Hello", "World"}});
  10360. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10361. res.set_content("ok", "text/plain");
  10362. });
  10363. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10364. auto se = detail::scope_exit([&] {
  10365. svr.stop();
  10366. listen_thread.join();
  10367. ASSERT_FALSE(svr.is_running());
  10368. });
  10369. svr.wait_until_ready();
  10370. Client cli("localhost", PORT);
  10371. auto res = cli.Get("/");
  10372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10373. EXPECT_EQ(StatusCode::OK_200, res->status);
  10374. EXPECT_EQ("ok", res->body);
  10375. EXPECT_EQ("World", res->get_header_value("Hello"));
  10376. }
  10377. #ifdef CPPHTTPLIB_SSL_ENABLED
  10378. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10379. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10380. ASSERT_TRUE(svr.is_valid());
  10381. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10382. std::this_thread::sleep_for(std::chrono::seconds(2));
  10383. res.set_content("a", "text/plain");
  10384. });
  10385. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10386. res.set_content("b", "text/plain");
  10387. });
  10388. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10389. auto se = detail::scope_exit([&] {
  10390. svr.stop();
  10391. listen_thread.join();
  10392. ASSERT_FALSE(svr.is_running());
  10393. });
  10394. svr.wait_until_ready();
  10395. SSLClient cli("localhost", PORT);
  10396. cli.enable_server_certificate_verification(false);
  10397. cli.set_keep_alive(true);
  10398. cli.set_read_timeout(std::chrono::seconds(1));
  10399. auto resa = cli.Get("/a");
  10400. ASSERT_TRUE(!resa);
  10401. EXPECT_EQ(Error::Read, resa.error());
  10402. auto resb = cli.Get("/b");
  10403. ASSERT_TRUE(resb);
  10404. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10405. EXPECT_EQ("b", resb->body);
  10406. }
  10407. // Closing an idle keep-alive connection sends close_notify and returns. The
  10408. // server must not wait for the client's close_notify: an idle client never
  10409. // sends one, so the worker would be held until the read timeout expires, and
  10410. // stop() would wait for it.
  10411. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10412. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10413. ASSERT_TRUE(svr.is_valid());
  10414. svr.set_keep_alive_timeout(1);
  10415. svr.set_read_timeout(10, 0);
  10416. svr.Get("/", [](const Request &, Response &res) {
  10417. res.set_content("ok", "text/plain");
  10418. });
  10419. auto port = svr.bind_to_any_port(HOST);
  10420. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10421. auto se = detail::scope_exit([&] {
  10422. if (listen_thread.joinable()) {
  10423. svr.stop();
  10424. listen_thread.join();
  10425. }
  10426. });
  10427. svr.wait_until_ready();
  10428. SSLClient cli(HOST, port);
  10429. cli.enable_server_certificate_verification(false);
  10430. cli.set_keep_alive(true);
  10431. auto res = cli.Get("/");
  10432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10433. EXPECT_EQ(StatusCode::OK_200, res->status);
  10434. // Stay idle past the keep-alive timeout so the server closes the connection.
  10435. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10436. auto start = std::chrono::steady_clock::now();
  10437. svr.stop();
  10438. listen_thread.join();
  10439. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10440. std::chrono::steady_clock::now() - start)
  10441. .count();
  10442. EXPECT_LT(elapsed, 3000);
  10443. }
  10444. #endif
  10445. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10446. protected:
  10447. ServerTestWithAI_PASSIVE()
  10448. : cli_(HOST, PORT)
  10449. #ifdef CPPHTTPLIB_SSL_ENABLED
  10450. ,
  10451. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10452. #endif
  10453. {
  10454. #ifdef CPPHTTPLIB_SSL_ENABLED
  10455. cli_.enable_server_certificate_verification(false);
  10456. #endif
  10457. }
  10458. virtual void SetUp() {
  10459. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10460. res.set_content("Hello World!", "text/plain");
  10461. });
  10462. t_ = thread(
  10463. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10464. svr_.wait_until_ready();
  10465. }
  10466. virtual void TearDown() {
  10467. svr_.stop();
  10468. t_.join();
  10469. }
  10470. #ifdef CPPHTTPLIB_SSL_ENABLED
  10471. SSLClient cli_;
  10472. SSLServer svr_;
  10473. #else
  10474. Client cli_;
  10475. Server svr_;
  10476. #endif
  10477. thread t_;
  10478. };
  10479. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10480. auto res = cli_.Get("/hi");
  10481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10482. EXPECT_EQ(StatusCode::OK_200, res->status);
  10483. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10484. EXPECT_EQ("Hello World!", res->body);
  10485. }
  10486. class ServerUpDownTest : public ::testing::Test {
  10487. protected:
  10488. ServerUpDownTest() : cli_(HOST, PORT) {}
  10489. virtual void SetUp() {
  10490. t_ = thread([&]() {
  10491. svr_.bind_to_any_port(HOST);
  10492. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10493. ASSERT_TRUE(svr_.listen_after_bind());
  10494. });
  10495. svr_.wait_until_ready();
  10496. }
  10497. virtual void TearDown() {
  10498. svr_.stop();
  10499. t_.join();
  10500. }
  10501. Client cli_;
  10502. Server svr_;
  10503. thread t_;
  10504. };
  10505. TEST_F(ServerUpDownTest, QuickStartStop) {
  10506. // Should not crash, especially when run with
  10507. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10508. }
  10509. class PayloadMaxLengthTest : public ::testing::Test {
  10510. protected:
  10511. PayloadMaxLengthTest()
  10512. : cli_(HOST, PORT)
  10513. #ifdef CPPHTTPLIB_SSL_ENABLED
  10514. ,
  10515. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10516. #endif
  10517. {
  10518. #ifdef CPPHTTPLIB_SSL_ENABLED
  10519. cli_.enable_server_certificate_verification(false);
  10520. #endif
  10521. }
  10522. virtual void SetUp() {
  10523. svr_.set_payload_max_length(8);
  10524. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10525. res.set_content("test", "text/plain");
  10526. });
  10527. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10528. svr_.wait_until_ready();
  10529. }
  10530. virtual void TearDown() {
  10531. svr_.stop();
  10532. t_.join();
  10533. }
  10534. #ifdef CPPHTTPLIB_SSL_ENABLED
  10535. SSLClient cli_;
  10536. SSLServer svr_;
  10537. #else
  10538. Client cli_;
  10539. Server svr_;
  10540. #endif
  10541. thread t_;
  10542. };
  10543. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10544. auto res = cli_.Post("/test", "123456789", "text/plain");
  10545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10546. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10547. res = cli_.Post("/test", "12345678", "text/plain");
  10548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10549. EXPECT_EQ(StatusCode::OK_200, res->status);
  10550. }
  10551. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10552. // Test chunked encoding with payload exceeding the 8-byte limit
  10553. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10554. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10556. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10557. }
  10558. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10559. // Test chunked encoding with payload within the 8-byte limit
  10560. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10561. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10563. EXPECT_EQ(StatusCode::OK_200, res->status);
  10564. }
  10565. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10566. // Test using send_request to send chunked data exceeding payload limit
  10567. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10568. "Host: " +
  10569. std::string(HOST) + ":" + std::to_string(PORT) +
  10570. "\r\n"
  10571. "Transfer-Encoding: chunked\r\n"
  10572. "Connection: close\r\n"
  10573. "\r\n"
  10574. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10575. "0123456789\r\n"
  10576. "0\r\n" // End chunk
  10577. "\r\n";
  10578. std::string response;
  10579. bool result = send_request(1, chunked_request, &response);
  10580. if (!result) {
  10581. // If send_request fails, it might be because the server closed the
  10582. // connection due to payload limit enforcement, which is acceptable
  10583. SUCCEED()
  10584. << "Server rejected oversized chunked request (connection closed)";
  10585. } else {
  10586. // If we got a response, check if it's an error response or connection was
  10587. // closed early Short response length indicates connection was closed due to
  10588. // payload limit
  10589. if (response.length() <= 10) {
  10590. SUCCEED() << "Server closed connection for oversized chunked request";
  10591. } else {
  10592. // Check for error status codes
  10593. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10594. response.find("Payload Too Large") != std::string::npos ||
  10595. response.find("400") != std::string::npos);
  10596. }
  10597. }
  10598. }
  10599. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10600. // Test request without Content-Length header exceeding payload limit
  10601. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10602. "Host: " +
  10603. std::string(HOST) + ":" +
  10604. std::to_string(PORT) +
  10605. "\r\n"
  10606. "Connection: close\r\n"
  10607. "\r\n";
  10608. // Add payload exceeding the 8-byte limit
  10609. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10610. request_without_content_length += large_payload;
  10611. std::string response;
  10612. bool result = send_request(1, request_without_content_length, &response);
  10613. if (!result) {
  10614. // If send_request fails, server likely closed connection due to payload
  10615. // limit
  10616. SUCCEED() << "Server rejected oversized request without Content-Length "
  10617. "(connection closed)";
  10618. } else {
  10619. // Check if server responded with error or closed connection early
  10620. if (response.length() <= 10) {
  10621. SUCCEED() << "Server closed connection for oversized request without "
  10622. "Content-Length";
  10623. } else {
  10624. // Check for error status codes
  10625. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10626. response.find("Payload Too Large") != std::string::npos ||
  10627. response.find("400") != std::string::npos);
  10628. }
  10629. }
  10630. }
  10631. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  10632. // Test request without Content-Length header within payload limit
  10633. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10634. "Host: " +
  10635. std::string(HOST) + ":" +
  10636. std::to_string(PORT) +
  10637. "\r\n"
  10638. "Connection: close\r\n"
  10639. "\r\n";
  10640. // Add payload within the 8-byte limit
  10641. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  10642. request_without_content_length += small_payload;
  10643. std::string response;
  10644. bool result = send_request(1, request_without_content_length, &response);
  10645. // For requests without Content-Length, the server may have different behavior
  10646. // The key is that it should not reject due to payload limit for small
  10647. // payloads
  10648. if (result) {
  10649. // Check for any HTTP response (success or error, but not connection closed)
  10650. if (response.length() > 10) {
  10651. SUCCEED()
  10652. << "Server processed request without Content-Length within limit";
  10653. } else {
  10654. // Short response might indicate connection closed, which is acceptable
  10655. SUCCEED() << "Server closed connection for request without "
  10656. "Content-Length (acceptable behavior)";
  10657. }
  10658. } else {
  10659. // Connection failure might be due to protocol requirements
  10660. SUCCEED() << "Connection issue with request without Content-Length "
  10661. "(environment-specific)";
  10662. }
  10663. }
  10664. class LargePayloadMaxLengthTest : public ::testing::Test {
  10665. protected:
  10666. LargePayloadMaxLengthTest()
  10667. : cli_(HOST, PORT)
  10668. #ifdef CPPHTTPLIB_SSL_ENABLED
  10669. ,
  10670. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10671. #endif
  10672. {
  10673. #ifdef CPPHTTPLIB_SSL_ENABLED
  10674. cli_.enable_server_certificate_verification(false);
  10675. #endif
  10676. }
  10677. virtual void SetUp() {
  10678. // Set 10MB payload limit
  10679. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  10680. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  10681. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10682. res.set_content("Large payload test", "text/plain");
  10683. });
  10684. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10685. svr_.wait_until_ready();
  10686. }
  10687. virtual void TearDown() {
  10688. svr_.stop();
  10689. t_.join();
  10690. }
  10691. #ifdef CPPHTTPLIB_SSL_ENABLED
  10692. SSLClient cli_;
  10693. SSLServer svr_;
  10694. #else
  10695. Client cli_;
  10696. Server svr_;
  10697. #endif
  10698. thread t_;
  10699. };
  10700. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  10701. // Test chunked encoding with payload within 10MB limit
  10702. std::string medium_payload(5 * 1024 * 1024,
  10703. 'A'); // 5MB payload, within 10MB limit
  10704. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  10705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10706. EXPECT_EQ(StatusCode::OK_200, res->status);
  10707. }
  10708. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  10709. // Test chunked encoding with payload exceeding 10MB limit
  10710. std::string large_payload(12 * 1024 * 1024,
  10711. 'B'); // 12MB payload, exceeds 10MB limit
  10712. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  10713. // Server may either return 413 or close the connection
  10714. if (res) {
  10715. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10716. } else {
  10717. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  10718. }
  10719. }
  10720. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  10721. // Test request without Content-Length header within 10MB limit
  10722. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10723. "Host: " +
  10724. std::string(HOST) + ":" +
  10725. std::to_string(PORT) +
  10726. "\r\n"
  10727. "Connection: close\r\n"
  10728. "\r\n";
  10729. // Add 1MB payload (within 10MB limit)
  10730. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  10731. request_without_content_length += medium_payload;
  10732. std::string response;
  10733. bool result = send_request(5, request_without_content_length, &response);
  10734. if (result) {
  10735. // Should get a proper HTTP response for payloads within limit
  10736. if (response.length() > 10) {
  10737. SUCCEED() << "Server processed 1MB request without Content-Length within "
  10738. "10MB limit";
  10739. } else {
  10740. SUCCEED() << "Server closed connection (acceptable behavior for no "
  10741. "Content-Length)";
  10742. }
  10743. } else {
  10744. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  10745. }
  10746. }
  10747. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  10748. // Test request without Content-Length header exceeding 10MB limit
  10749. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10750. "Host: " +
  10751. std::string(HOST) + ":" +
  10752. std::to_string(PORT) +
  10753. "\r\n"
  10754. "Connection: close\r\n"
  10755. "\r\n";
  10756. // Add 12MB payload (exceeds 10MB limit)
  10757. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  10758. request_without_content_length += large_payload;
  10759. std::string response;
  10760. bool result = send_request(10, request_without_content_length, &response);
  10761. if (!result) {
  10762. // Server should close connection due to payload limit
  10763. SUCCEED() << "Server rejected 12MB request without Content-Length "
  10764. "(connection closed)";
  10765. } else {
  10766. // Check for error response
  10767. if (response.length() <= 10) {
  10768. SUCCEED()
  10769. << "Server closed connection for 12MB request exceeding 10MB limit";
  10770. } else {
  10771. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10772. response.find("Payload Too Large") != std::string::npos ||
  10773. response.find("400") != std::string::npos);
  10774. }
  10775. }
  10776. }
  10777. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10778. // `payload_max_length` is not enforced on decompressed body in ContentReader
  10779. // path.
  10780. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  10781. Server svr;
  10782. const size_t LIMIT = 64 * 1024; // 64KB
  10783. svr.set_payload_max_length(LIMIT);
  10784. size_t total = 0;
  10785. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10786. const ContentReader &content_reader) {
  10787. content_reader([&](const char * /*data*/, size_t len) {
  10788. total += len;
  10789. return true;
  10790. });
  10791. res.status = 200;
  10792. res.set_content("stream_ok", "text/plain");
  10793. });
  10794. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10795. auto se = detail::scope_exit([&] {
  10796. svr.stop();
  10797. thread.join();
  10798. ASSERT_FALSE(svr.is_running());
  10799. });
  10800. svr.wait_until_ready();
  10801. // Prepare 256KB raw data and gzip-compress it
  10802. std::string raw(256 * 1024, 'A');
  10803. std::string gz;
  10804. {
  10805. z_stream zs{};
  10806. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  10807. Z_DEFAULT_STRATEGY);
  10808. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  10809. zs.avail_in = static_cast<uInt>(raw.size());
  10810. char outbuf[4096];
  10811. int ret;
  10812. do {
  10813. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  10814. zs.avail_out = sizeof(outbuf);
  10815. ret = deflate(&zs, Z_FINISH);
  10816. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  10817. } while (ret != Z_STREAM_END);
  10818. deflateEnd(&zs);
  10819. }
  10820. Client cli(HOST, PORT);
  10821. cli.set_connection_timeout(std::chrono::seconds(5));
  10822. Headers headers = {{"Content-Encoding", "gzip"}};
  10823. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  10824. "application/octet-stream");
  10825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10826. // Server must reject oversized decompressed payloads with 413.
  10827. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10828. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10829. EXPECT_LE(total, LIMIT);
  10830. }
  10831. #ifndef CPPHTTPLIB_SSL_ENABLED
  10832. // For a request with neither Content-Length nor Transfer-Encoding, the
  10833. // non-SSL raw-socket fallback in read_content_core() used to hand the
  10834. // compressed wire bytes straight to the ContentReader without ever routing
  10835. // them through the decompressor, so payload_max_length_ only bounded the
  10836. // compressed size on the wire, not the decompressed size.
  10837. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  10838. Server svr;
  10839. const size_t LIMIT = 64 * 1024; // 64KB
  10840. svr.set_payload_max_length(LIMIT);
  10841. size_t total = 0;
  10842. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10843. const ContentReader &content_reader) {
  10844. content_reader([&](const char * /*data*/, size_t len) {
  10845. total += len;
  10846. return true;
  10847. });
  10848. res.status = 200;
  10849. res.set_content("stream_ok", "text/plain");
  10850. });
  10851. auto port = svr.bind_to_any_port(HOST);
  10852. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10853. auto se = detail::scope_exit([&] {
  10854. svr.stop();
  10855. thread.join();
  10856. ASSERT_FALSE(svr.is_running());
  10857. });
  10858. svr.wait_until_ready();
  10859. // Prepare 256KB raw data and gzip-compress it, same payload as the
  10860. // StreamingGzipDecompression test above.
  10861. std::string raw(256 * 1024, 'A');
  10862. std::string gz;
  10863. {
  10864. httplib::detail::gzip_compressor compressor;
  10865. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  10866. [&](const char *chunk, size_t len) {
  10867. gz.append(chunk, len);
  10868. return true;
  10869. });
  10870. ASSERT_TRUE(result);
  10871. }
  10872. // Send the gzip body over raw TCP with neither Content-Length nor
  10873. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  10874. // kicks in.
  10875. std::string req = "POST /stream HTTP/1.1\r\n"
  10876. "Host: " +
  10877. std::string(HOST) + ":" + std::to_string(port) +
  10878. "\r\n"
  10879. "Content-Encoding: gzip\r\n"
  10880. "Connection: close\r\n"
  10881. "\r\n" +
  10882. gz;
  10883. std::string response;
  10884. ASSERT_TRUE(send_request(5, req, &response, port));
  10885. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10886. EXPECT_LE(total, LIMIT);
  10887. }
  10888. #endif
  10889. #endif
  10890. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  10891. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  10892. // the payload must be passed through untouched instead of being rejected.
  10893. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  10894. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10895. Server svr;
  10896. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  10897. res.set_content(body, "image/jpeg");
  10898. res.set_header("Content-Encoding", "UTF-8");
  10899. });
  10900. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  10901. res.set_content(body, "image/jpeg");
  10902. res.set_header("Content-Encoding", "identity");
  10903. });
  10904. svr.Post("/echo", [](const Request &req, Response &res) {
  10905. res.set_content(req.body, "image/jpeg");
  10906. });
  10907. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10908. auto se = detail::scope_exit([&] {
  10909. svr.stop();
  10910. t.join();
  10911. ASSERT_FALSE(svr.is_running());
  10912. });
  10913. svr.wait_until_ready();
  10914. Client cli(HOST, PORT);
  10915. {
  10916. auto res = cli.Get("/image");
  10917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10918. EXPECT_EQ(StatusCode::OK_200, res->status);
  10919. EXPECT_EQ(body, res->body);
  10920. }
  10921. {
  10922. auto res = cli.Get("/identity");
  10923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10924. EXPECT_EQ(StatusCode::OK_200, res->status);
  10925. EXPECT_EQ(body, res->body);
  10926. }
  10927. {
  10928. // The same applies to a request body reaching the server.
  10929. Headers headers = {{"Content-Encoding", "UTF-8"}};
  10930. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  10931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10932. EXPECT_EQ(StatusCode::OK_200, res->status);
  10933. EXPECT_EQ(body, res->body);
  10934. }
  10935. }
  10936. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  10937. // gzip-encoded response even when the build has no zlib support.
  10938. static const char GZIPPED_HELLO_WORLD[] = {
  10939. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  10940. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  10941. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  10942. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  10943. // A content coding is a whole token, not something the field value merely
  10944. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  10945. // as "fibre" look like Brotli, and turned a multi-coding value like
  10946. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  10947. // it was never meant to see.
  10948. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  10949. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10950. Server svr;
  10951. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  10952. res.set_content(body, "image/jpeg");
  10953. res.set_header("Content-Encoding", "fibre");
  10954. });
  10955. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  10956. res.set_content(body, "image/jpeg");
  10957. res.set_header("Content-Encoding", "gzip, br");
  10958. });
  10959. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  10960. res.set_content(body, "image/jpeg");
  10961. res.set_header("Content-Encoding", "x-zstd-ish");
  10962. });
  10963. auto port = svr.bind_to_any_port(HOST);
  10964. thread t = thread([&]() { svr.listen_after_bind(); });
  10965. auto se = detail::scope_exit([&] {
  10966. svr.stop();
  10967. t.join();
  10968. ASSERT_FALSE(svr.is_running());
  10969. });
  10970. svr.wait_until_ready();
  10971. Client cli(HOST, port);
  10972. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  10973. auto res = cli.Get(path);
  10974. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10975. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10976. // Not a coding we recognize, so the payload comes back untouched
  10977. EXPECT_EQ(body, res->body) << path;
  10978. }
  10979. }
  10980. // A content coding cpp-httplib recognizes but was not built with must be
  10981. // reported as such. Handing the still-compressed payload back to the caller
  10982. // would silently corrupt it.
  10983. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  10984. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10985. Server svr;
  10986. // "image/jpeg" keeps the server from applying a content coding of its own,
  10987. // so the hand-crafted Content-Encoding below survives.
  10988. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  10989. res.set_content(gzipped, "image/jpeg");
  10990. res.set_header("Content-Encoding", "gzip");
  10991. });
  10992. // Content codings are case-insensitive (RFC 9110 8.4.1).
  10993. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  10994. res.set_content(gzipped, "image/jpeg");
  10995. res.set_header("Content-Encoding", "GZIP");
  10996. });
  10997. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10998. auto se = detail::scope_exit([&] {
  10999. svr.stop();
  11000. t.join();
  11001. ASSERT_FALSE(svr.is_running());
  11002. });
  11003. svr.wait_until_ready();
  11004. Client cli(HOST, PORT);
  11005. {
  11006. auto res = cli.Get("/gzipped");
  11007. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11009. EXPECT_EQ("Hello World!", res->body);
  11010. #else
  11011. ASSERT_FALSE(res);
  11012. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11013. #endif
  11014. }
  11015. {
  11016. // open_stream() must behave the same way.
  11017. auto handle = cli.open_stream("GET", "/gzipped");
  11018. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11019. ASSERT_TRUE(handle.is_valid());
  11020. std::string received;
  11021. char buf[256];
  11022. ssize_t n;
  11023. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11024. received.append(buf, static_cast<size_t>(n));
  11025. }
  11026. EXPECT_EQ("Hello World!", received);
  11027. #else
  11028. EXPECT_FALSE(handle.is_valid());
  11029. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11030. #endif
  11031. }
  11032. {
  11033. // A differently-cased coding must not be mistaken for an unknown one, or
  11034. // the body would be handed back still compressed.
  11035. auto res = cli.Get("/gzipped-uppercase");
  11036. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11038. EXPECT_EQ("Hello World!", res->body);
  11039. #else
  11040. ASSERT_FALSE(res);
  11041. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11042. #endif
  11043. }
  11044. }
  11045. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11046. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11047. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11048. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11049. // body a second time and appending a second Content-Encoding field line, so
  11050. // clients that decode one coding per listed value handed back raw gzip bytes.
  11051. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11052. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11053. Server svr;
  11054. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11055. // keeps the server from applying a coding of its own.
  11056. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11057. res.set_content(gzipped, "text/plain");
  11058. res.set_header("Content-Encoding", "gzip");
  11059. });
  11060. auto port = svr.bind_to_any_port(HOST);
  11061. thread t = thread([&]() { svr.listen_after_bind(); });
  11062. auto se = detail::scope_exit([&] {
  11063. svr.stop();
  11064. t.join();
  11065. ASSERT_FALSE(svr.is_running());
  11066. });
  11067. svr.wait_until_ready();
  11068. Client cli(HOST, port);
  11069. Headers headers = {{"Accept-Encoding", "gzip"}};
  11070. auto res = cli.Get("/pre-gzipped", headers);
  11071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11072. EXPECT_EQ(StatusCode::OK_200, res->status);
  11073. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11074. EXPECT_EQ("Hello World!", res->body);
  11075. }
  11076. // A chunked provider settles its coding where the headers are written and
  11077. // reuses it at write time. Both ends of that have to hold: a handler's own
  11078. // Content-Encoding suppresses the coding, and a response without one is still
  11079. // compressed as it always was.
  11080. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11081. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11082. const std::string plain = "Hello World! Hello World! Hello World!";
  11083. Server svr;
  11084. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11085. res.set_header("Content-Encoding", "gzip");
  11086. res.set_chunked_content_provider(
  11087. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11088. sink.write(gzipped.data(), gzipped.size());
  11089. sink.done();
  11090. return true;
  11091. });
  11092. });
  11093. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11094. res.set_chunked_content_provider(
  11095. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11096. sink.write(plain.data(), plain.size());
  11097. sink.done();
  11098. return true;
  11099. });
  11100. });
  11101. auto port = svr.bind_to_any_port(HOST);
  11102. thread t = thread([&]() { svr.listen_after_bind(); });
  11103. auto se = detail::scope_exit([&] {
  11104. svr.stop();
  11105. t.join();
  11106. ASSERT_FALSE(svr.is_running());
  11107. });
  11108. svr.wait_until_ready();
  11109. Client cli(HOST, port);
  11110. Headers headers = {{"Accept-Encoding", "gzip"}};
  11111. {
  11112. auto res = cli.Get("/pre-gzipped", headers);
  11113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11114. EXPECT_EQ(StatusCode::OK_200, res->status);
  11115. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11116. EXPECT_EQ("Hello World!", res->body);
  11117. }
  11118. {
  11119. auto res = cli.Get("/negotiated", headers);
  11120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11121. EXPECT_EQ(StatusCode::OK_200, res->status);
  11122. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11123. EXPECT_EQ(plain, res->body);
  11124. }
  11125. }
  11126. #endif
  11127. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11128. // the same message as the comma-joined one, so both have to be read the same
  11129. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11130. // single gzip coding, and a body the sender says was encoded twice was handed
  11131. // back after one pass, still compressed but presented as decoded.
  11132. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11133. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11134. Server svr;
  11135. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11136. res.set_content(body, "image/jpeg");
  11137. res.headers.emplace("Content-Encoding", "gzip");
  11138. res.headers.emplace("Content-Encoding", "gzip");
  11139. });
  11140. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11141. res.set_content(body, "image/jpeg");
  11142. res.set_header("Content-Encoding", "gzip, gzip");
  11143. });
  11144. auto port = svr.bind_to_any_port(HOST);
  11145. thread t = thread([&]() { svr.listen_after_bind(); });
  11146. auto se = detail::scope_exit([&] {
  11147. svr.stop();
  11148. t.join();
  11149. ASSERT_FALSE(svr.is_running());
  11150. });
  11151. svr.wait_until_ready();
  11152. Client cli(HOST, port);
  11153. // Two codings is not something cpp-httplib decodes, so both representations
  11154. // take the pass-through path rather than one of them being gunzipped once.
  11155. for (const char *path : {"/split", "/joined"}) {
  11156. auto res = cli.Get(path);
  11157. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11158. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11159. EXPECT_EQ(body, res->body) << path;
  11160. }
  11161. }
  11162. // Regression test for DoS vulnerability: a malicious server sending a response
  11163. // without Content-Length header must not cause unbounded memory consumption on
  11164. // the client side. The client should stop reading after a reasonable limit,
  11165. // similar to the server-side set_payload_max_length protection.
  11166. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11167. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11168. #ifndef _WIN32
  11169. signal(SIGPIPE, SIG_IGN);
  11170. #endif
  11171. auto server_thread = std::thread([] {
  11172. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11173. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11174. default_socket_options(srv);
  11175. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11176. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11177. sockaddr_in addr{};
  11178. addr.sin_family = AF_INET;
  11179. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11180. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11181. int opt = 1;
  11182. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11183. #ifdef _WIN32
  11184. reinterpret_cast<const char *>(&opt),
  11185. #else
  11186. &opt,
  11187. #endif
  11188. sizeof(opt));
  11189. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11190. ::listen(srv, 1);
  11191. sockaddr_in cli_addr{};
  11192. socklen_t cli_len = sizeof(cli_addr);
  11193. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11194. if (cli != INVALID_SOCKET) {
  11195. char buf[4096];
  11196. ::recv(cli, buf, sizeof(buf), 0);
  11197. // Malicious response: no Content-Length, no chunked encoding
  11198. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11199. "Connection: close\r\n"
  11200. "\r\n";
  11201. ::send(cli,
  11202. #ifdef _WIN32
  11203. static_cast<const char *>(response_header.c_str()),
  11204. static_cast<int>(response_header.size()),
  11205. #else
  11206. response_header.c_str(), response_header.size(),
  11207. #endif
  11208. 0);
  11209. // Send 10MB of data
  11210. std::string chunk(64 * 1024, 'A');
  11211. size_t total_sent = 0;
  11212. while (total_sent < MALICIOUS_DATA_SIZE) {
  11213. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11214. auto sent = ::send(cli,
  11215. #ifdef _WIN32
  11216. static_cast<const char *>(chunk.c_str()),
  11217. static_cast<int>(to_send),
  11218. #else
  11219. chunk.c_str(), to_send,
  11220. #endif
  11221. 0);
  11222. if (sent <= 0) break;
  11223. total_sent += static_cast<size_t>(sent);
  11224. }
  11225. detail::close_socket(cli);
  11226. }
  11227. detail::close_socket(srv);
  11228. });
  11229. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11230. size_t total_read = 0;
  11231. {
  11232. Client cli("127.0.0.1", PORT + 2);
  11233. cli.set_read_timeout(5, 0);
  11234. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11235. auto stream = cli.open_stream("GET", "/malicious");
  11236. ASSERT_TRUE(stream.is_valid());
  11237. char buffer[64 * 1024];
  11238. ssize_t n;
  11239. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11240. total_read += static_cast<size_t>(n);
  11241. }
  11242. } // StreamHandle and Client destroyed here, closing the socket
  11243. server_thread.join();
  11244. // With set_payload_max_length, the client must stop reading before consuming
  11245. // all 10MB. The read loop should be cut off at or near the configured limit.
  11246. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11247. << "Client read " << total_read << " bytes, exceeding the configured "
  11248. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11249. }
  11250. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11251. // the entire response body without truncation.
  11252. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11253. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11254. #ifndef _WIN32
  11255. signal(SIGPIPE, SIG_IGN);
  11256. #endif
  11257. auto server_thread = std::thread([] {
  11258. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11259. default_socket_options(srv);
  11260. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11261. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11262. sockaddr_in addr{};
  11263. addr.sin_family = AF_INET;
  11264. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11265. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11266. int opt = 1;
  11267. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11268. #ifdef _WIN32
  11269. reinterpret_cast<const char *>(&opt),
  11270. #else
  11271. &opt,
  11272. #endif
  11273. sizeof(opt));
  11274. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11275. ::listen(srv, 1);
  11276. sockaddr_in cli_addr{};
  11277. socklen_t cli_len = sizeof(cli_addr);
  11278. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11279. if (cli != INVALID_SOCKET) {
  11280. char buf[4096];
  11281. ::recv(cli, buf, sizeof(buf), 0);
  11282. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11283. "Connection: close\r\n"
  11284. "\r\n";
  11285. ::send(cli,
  11286. #ifdef _WIN32
  11287. static_cast<const char *>(response_header.c_str()),
  11288. static_cast<int>(response_header.size()),
  11289. #else
  11290. response_header.c_str(), response_header.size(),
  11291. #endif
  11292. 0);
  11293. std::string chunk(64 * 1024, 'A');
  11294. size_t total_sent = 0;
  11295. while (total_sent < DATA_SIZE) {
  11296. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11297. auto sent = ::send(cli,
  11298. #ifdef _WIN32
  11299. static_cast<const char *>(chunk.c_str()),
  11300. static_cast<int>(to_send),
  11301. #else
  11302. chunk.c_str(), to_send,
  11303. #endif
  11304. 0);
  11305. if (sent <= 0) break;
  11306. total_sent += static_cast<size_t>(sent);
  11307. }
  11308. #ifdef _WIN32
  11309. ::shutdown(cli, SD_SEND);
  11310. #else
  11311. ::shutdown(cli, SHUT_WR);
  11312. #endif
  11313. // Drain until the client closes its end, ensuring all data is delivered
  11314. char drain[1024];
  11315. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11316. detail::close_socket(cli);
  11317. }
  11318. detail::close_socket(srv);
  11319. });
  11320. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11321. size_t total_read = 0;
  11322. {
  11323. Client cli("127.0.0.1", PORT + 2);
  11324. cli.set_read_timeout(5, 0);
  11325. cli.set_payload_max_length(0); // 0 means no limit
  11326. auto stream = cli.open_stream("GET", "/data");
  11327. ASSERT_TRUE(stream.is_valid());
  11328. char buffer[64 * 1024];
  11329. ssize_t n;
  11330. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11331. total_read += static_cast<size_t>(n);
  11332. }
  11333. }
  11334. server_thread.join();
  11335. EXPECT_EQ(total_read, DATA_SIZE)
  11336. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11337. << " bytes without truncation, but only read " << total_read << " bytes.";
  11338. }
  11339. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11340. // enormous Content-Length must not cause the client to pre-allocate a huge
  11341. // response body buffer. The reservation is capped at payload_max_length_, and
  11342. // the read itself fails when the body exceeds the limit.
  11343. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11344. #ifndef _WIN32
  11345. signal(SIGPIPE, SIG_IGN);
  11346. #endif
  11347. auto server_thread = std::thread([] {
  11348. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11349. default_socket_options(srv);
  11350. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11351. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11352. sockaddr_in addr{};
  11353. addr.sin_family = AF_INET;
  11354. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11355. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11356. int opt = 1;
  11357. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11358. #ifdef _WIN32
  11359. reinterpret_cast<const char *>(&opt),
  11360. #else
  11361. &opt,
  11362. #endif
  11363. sizeof(opt));
  11364. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11365. ::listen(srv, 1);
  11366. sockaddr_in cli_addr{};
  11367. socklen_t cli_len = sizeof(cli_addr);
  11368. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11369. if (cli != INVALID_SOCKET) {
  11370. char buf[4096];
  11371. ::recv(cli, buf, sizeof(buf), 0);
  11372. // Malicious response: claim a 20GB body but send only a tiny payload.
  11373. std::string response = "HTTP/1.1 200 OK\r\n"
  11374. "Content-Length: 20000000000\r\n"
  11375. "\r\n"
  11376. "abc";
  11377. ::send(cli,
  11378. #ifdef _WIN32
  11379. static_cast<const char *>(response.c_str()),
  11380. static_cast<int>(response.size()),
  11381. #else
  11382. response.c_str(), response.size(),
  11383. #endif
  11384. 0);
  11385. detail::close_socket(cli);
  11386. }
  11387. detail::close_socket(srv);
  11388. });
  11389. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11390. {
  11391. Client cli("127.0.0.1", PORT + 2);
  11392. cli.set_read_timeout(5, 0);
  11393. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11394. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11395. // (server claims more bytes than payload_max_length permits), but it must
  11396. // not exhaust memory before getting there.
  11397. auto res = cli.Get("/malicious");
  11398. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11399. }
  11400. server_thread.join();
  11401. }
  11402. // Verify that content_receiver bypasses the default payload_max_length,
  11403. // allowing streaming downloads larger than 100MB without requiring an explicit
  11404. // set_payload_max_length call.
  11405. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11406. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11407. #ifndef _WIN32
  11408. signal(SIGPIPE, SIG_IGN);
  11409. #endif
  11410. auto server_thread = std::thread([] {
  11411. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11412. default_socket_options(srv);
  11413. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11414. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11415. sockaddr_in addr{};
  11416. addr.sin_family = AF_INET;
  11417. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11418. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11419. int opt = 1;
  11420. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11421. #ifdef _WIN32
  11422. reinterpret_cast<const char *>(&opt),
  11423. #else
  11424. &opt,
  11425. #endif
  11426. sizeof(opt));
  11427. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11428. ::listen(srv, 1);
  11429. sockaddr_in cli_addr{};
  11430. socklen_t cli_len = sizeof(cli_addr);
  11431. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11432. if (cli != INVALID_SOCKET) {
  11433. char buf[4096];
  11434. ::recv(cli, buf, sizeof(buf), 0);
  11435. // Response with Content-Length larger than default 100MB limit
  11436. auto content_length = std::to_string(DATA_SIZE);
  11437. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11438. "Content-Length: " +
  11439. content_length +
  11440. "\r\n"
  11441. "Connection: close\r\n"
  11442. "\r\n";
  11443. ::send(cli,
  11444. #ifdef _WIN32
  11445. static_cast<const char *>(response_header.c_str()),
  11446. static_cast<int>(response_header.size()),
  11447. #else
  11448. response_header.c_str(), response_header.size(),
  11449. #endif
  11450. 0);
  11451. std::string chunk(64 * 1024, 'A');
  11452. size_t total_sent = 0;
  11453. while (total_sent < DATA_SIZE) {
  11454. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11455. auto sent = ::send(cli,
  11456. #ifdef _WIN32
  11457. static_cast<const char *>(chunk.c_str()),
  11458. static_cast<int>(to_send),
  11459. #else
  11460. chunk.c_str(), to_send,
  11461. #endif
  11462. 0);
  11463. if (sent <= 0) break;
  11464. total_sent += static_cast<size_t>(sent);
  11465. }
  11466. detail::close_socket(cli);
  11467. }
  11468. detail::close_socket(srv);
  11469. });
  11470. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11471. size_t total_received = 0;
  11472. {
  11473. Client cli("127.0.0.1", PORT + 2);
  11474. cli.set_read_timeout(10, 0);
  11475. // Do NOT call set_payload_max_length — use the default 100MB limit
  11476. auto res =
  11477. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11478. total_received += data_length;
  11479. return true;
  11480. });
  11481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11482. EXPECT_EQ(StatusCode::OK_200, res->status);
  11483. }
  11484. server_thread.join();
  11485. EXPECT_EQ(total_received, DATA_SIZE)
  11486. << "With content_receiver, the client should read all " << DATA_SIZE
  11487. << " bytes despite the default 100MB payload_max_length, but only read "
  11488. << total_received << " bytes.";
  11489. }
  11490. // Verify that an explicit set_payload_max_length smaller than the response is
  11491. // enforced even when a content_receiver is used.
  11492. TEST(ClientVulnerabilityTest,
  11493. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11494. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11495. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11496. #ifndef _WIN32
  11497. signal(SIGPIPE, SIG_IGN);
  11498. #endif
  11499. auto server_thread = std::thread([] {
  11500. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11501. default_socket_options(srv);
  11502. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11503. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11504. sockaddr_in addr{};
  11505. addr.sin_family = AF_INET;
  11506. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11507. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11508. int opt = 1;
  11509. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11510. #ifdef _WIN32
  11511. reinterpret_cast<const char *>(&opt),
  11512. #else
  11513. &opt,
  11514. #endif
  11515. sizeof(opt));
  11516. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11517. ::listen(srv, 1);
  11518. sockaddr_in cli_addr{};
  11519. socklen_t cli_len = sizeof(cli_addr);
  11520. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11521. if (cli != INVALID_SOCKET) {
  11522. char buf[4096];
  11523. ::recv(cli, buf, sizeof(buf), 0);
  11524. auto content_length = std::to_string(DATA_SIZE);
  11525. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11526. "Content-Length: " +
  11527. content_length +
  11528. "\r\n"
  11529. "Connection: close\r\n"
  11530. "\r\n";
  11531. ::send(cli,
  11532. #ifdef _WIN32
  11533. static_cast<const char *>(response_header.c_str()),
  11534. static_cast<int>(response_header.size()),
  11535. #else
  11536. response_header.c_str(), response_header.size(),
  11537. #endif
  11538. 0);
  11539. std::string chunk(64 * 1024, 'A');
  11540. size_t total_sent = 0;
  11541. while (total_sent < DATA_SIZE) {
  11542. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11543. auto sent = ::send(cli,
  11544. #ifdef _WIN32
  11545. static_cast<const char *>(chunk.c_str()),
  11546. static_cast<int>(to_send),
  11547. #else
  11548. chunk.c_str(), to_send,
  11549. #endif
  11550. 0);
  11551. if (sent <= 0) break;
  11552. total_sent += static_cast<size_t>(sent);
  11553. }
  11554. detail::close_socket(cli);
  11555. }
  11556. detail::close_socket(srv);
  11557. });
  11558. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11559. size_t total_received = 0;
  11560. {
  11561. Client cli("127.0.0.1", PORT + 2);
  11562. cli.set_read_timeout(10, 0);
  11563. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11564. auto res =
  11565. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11566. total_received += data_length;
  11567. return true;
  11568. });
  11569. // Should fail because 200MB exceeds the explicit 150MB limit
  11570. EXPECT_FALSE(res);
  11571. }
  11572. server_thread.join();
  11573. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11574. << "Client with content_receiver should respect the explicit "
  11575. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11576. << total_received << " bytes.";
  11577. }
  11578. // Verify that an explicit set_payload_max_length larger than the response
  11579. // allows the content_receiver to read all data successfully.
  11580. TEST(ClientVulnerabilityTest,
  11581. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11582. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11583. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11584. #ifndef _WIN32
  11585. signal(SIGPIPE, SIG_IGN);
  11586. #endif
  11587. auto server_thread = std::thread([] {
  11588. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11589. default_socket_options(srv);
  11590. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11591. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11592. sockaddr_in addr{};
  11593. addr.sin_family = AF_INET;
  11594. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11595. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11596. int opt = 1;
  11597. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11598. #ifdef _WIN32
  11599. reinterpret_cast<const char *>(&opt),
  11600. #else
  11601. &opt,
  11602. #endif
  11603. sizeof(opt));
  11604. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11605. ::listen(srv, 1);
  11606. sockaddr_in cli_addr{};
  11607. socklen_t cli_len = sizeof(cli_addr);
  11608. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11609. if (cli != INVALID_SOCKET) {
  11610. char buf[4096];
  11611. ::recv(cli, buf, sizeof(buf), 0);
  11612. auto content_length = std::to_string(DATA_SIZE);
  11613. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11614. "Content-Length: " +
  11615. content_length +
  11616. "\r\n"
  11617. "Connection: close\r\n"
  11618. "\r\n";
  11619. ::send(cli,
  11620. #ifdef _WIN32
  11621. static_cast<const char *>(response_header.c_str()),
  11622. static_cast<int>(response_header.size()),
  11623. #else
  11624. response_header.c_str(), response_header.size(),
  11625. #endif
  11626. 0);
  11627. std::string chunk(64 * 1024, 'A');
  11628. size_t total_sent = 0;
  11629. while (total_sent < DATA_SIZE) {
  11630. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11631. auto sent = ::send(cli,
  11632. #ifdef _WIN32
  11633. static_cast<const char *>(chunk.c_str()),
  11634. static_cast<int>(to_send),
  11635. #else
  11636. chunk.c_str(), to_send,
  11637. #endif
  11638. 0);
  11639. if (sent <= 0) break;
  11640. total_sent += static_cast<size_t>(sent);
  11641. }
  11642. #ifdef _WIN32
  11643. ::shutdown(cli, SD_SEND);
  11644. #else
  11645. ::shutdown(cli, SHUT_WR);
  11646. #endif
  11647. char drain[1024];
  11648. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11649. detail::close_socket(cli);
  11650. }
  11651. detail::close_socket(srv);
  11652. });
  11653. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11654. size_t total_received = 0;
  11655. {
  11656. Client cli("127.0.0.1", PORT + 2);
  11657. cli.set_read_timeout(10, 0);
  11658. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  11659. auto res =
  11660. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11661. total_received += data_length;
  11662. return true;
  11663. });
  11664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11665. EXPECT_EQ(StatusCode::OK_200, res->status);
  11666. }
  11667. server_thread.join();
  11668. EXPECT_EQ(total_received, DATA_SIZE)
  11669. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  11670. << " bytes (larger than " << DATA_SIZE
  11671. << " bytes response), content_receiver should read all data, but only "
  11672. "read "
  11673. << total_received << " bytes.";
  11674. }
  11675. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  11676. // Regression test for "zip bomb" attack on the client side: a malicious server
  11677. // sends a small gzip-compressed response that decompresses to a huge payload.
  11678. // The client must enforce payload_max_length on the decompressed size.
  11679. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  11680. constexpr size_t DECOMPRESSED_SIZE =
  11681. 10 * 1024 * 1024; // 10MB after decompression
  11682. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11683. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  11684. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  11685. std::string compressed;
  11686. {
  11687. httplib::detail::gzip_compressor compressor;
  11688. bool ok =
  11689. compressor.compress(uncompressed.data(), uncompressed.size(),
  11690. /*last=*/true, [&](const char *buf, size_t len) {
  11691. compressed.append(buf, len);
  11692. return true;
  11693. });
  11694. ASSERT_TRUE(ok);
  11695. }
  11696. // Sanity: compressed data should be much smaller than the decompressed size
  11697. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  11698. #ifndef _WIN32
  11699. signal(SIGPIPE, SIG_IGN);
  11700. #endif
  11701. // Set up the listening socket in the main thread so the server is guaranteed
  11702. // to be ready before the client connects (eliminates race condition).
  11703. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11704. default_socket_options(srv);
  11705. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11706. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11707. sockaddr_in addr{};
  11708. addr.sin_family = AF_INET;
  11709. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  11710. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11711. int opt = 1;
  11712. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11713. #ifdef _WIN32
  11714. reinterpret_cast<const char *>(&opt),
  11715. #else
  11716. &opt,
  11717. #endif
  11718. sizeof(opt));
  11719. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11720. ASSERT_EQ(0, ::listen(srv, 1));
  11721. auto server_thread = std::thread([&compressed, srv] {
  11722. sockaddr_in cli_addr{};
  11723. socklen_t cli_len = sizeof(cli_addr);
  11724. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11725. if (cli != INVALID_SOCKET) {
  11726. // Read the full HTTP request (until \r\n\r\n)
  11727. char buf[4096];
  11728. size_t total = 0;
  11729. while (total < sizeof(buf)) {
  11730. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  11731. if (n <= 0) break;
  11732. total += static_cast<size_t>(n);
  11733. // Check for end of headers
  11734. if (total >= 4) {
  11735. std::string req(buf, total);
  11736. if (req.find("\r\n\r\n") != std::string::npos) break;
  11737. }
  11738. }
  11739. // Malicious response: gzip-compressed body, no Content-Length
  11740. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11741. "Content-Encoding: gzip\r\n"
  11742. "Connection: close\r\n"
  11743. "\r\n";
  11744. ::send(cli,
  11745. #ifdef _WIN32
  11746. static_cast<const char *>(response_header.c_str()),
  11747. static_cast<int>(response_header.size()),
  11748. #else
  11749. response_header.c_str(), response_header.size(),
  11750. #endif
  11751. 0);
  11752. // Send the compressed payload (small on the wire, huge when decompressed)
  11753. size_t total_sent = 0;
  11754. while (total_sent < compressed.size()) {
  11755. auto to_send = std::min(compressed.size() - total_sent,
  11756. static_cast<size_t>(64 * 1024));
  11757. auto sent =
  11758. ::send(cli,
  11759. #ifdef _WIN32
  11760. static_cast<const char *>(compressed.c_str() + total_sent),
  11761. static_cast<int>(to_send),
  11762. #else
  11763. compressed.c_str() + total_sent, to_send,
  11764. #endif
  11765. 0);
  11766. if (sent <= 0) break;
  11767. total_sent += static_cast<size_t>(sent);
  11768. }
  11769. detail::close_socket(cli);
  11770. }
  11771. });
  11772. auto se = detail::scope_exit([&] {
  11773. detail::close_socket(srv);
  11774. server_thread.join();
  11775. });
  11776. size_t total_decompressed = 0;
  11777. {
  11778. Client cli("127.0.0.1", PORT + 3);
  11779. cli.set_read_timeout(5, 0);
  11780. cli.set_decompress(true);
  11781. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11782. auto stream = cli.open_stream("GET", "/zipbomb");
  11783. ASSERT_TRUE(stream.is_valid());
  11784. char buffer[64 * 1024];
  11785. ssize_t n;
  11786. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11787. total_decompressed += static_cast<size_t>(n);
  11788. }
  11789. }
  11790. // The decompressed size must be capped by payload_max_length. Without
  11791. // protection, the client would decompress the full 10MB from a tiny
  11792. // compressed payload, enabling a zip bomb DoS attack.
  11793. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  11794. << "Client decompressed " << total_decompressed
  11795. << " bytes from a gzip response. The decompressed size should be "
  11796. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  11797. }
  11798. #endif
  11799. TEST(HostAndPortPropertiesTest, NoSSL) {
  11800. httplib::Client cli("www.google.com", 1234);
  11801. ASSERT_EQ("www.google.com", cli.host());
  11802. ASSERT_EQ(1234, cli.port());
  11803. }
  11804. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  11805. httplib::Client cli("www.google.com:1234");
  11806. ASSERT_EQ("www.google.com", cli.host());
  11807. ASSERT_EQ(1234, cli.port());
  11808. }
  11809. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  11810. // Port number that overflows int — should not crash, client becomes invalid
  11811. httplib::Client cli("http://www.google.com:99999999999999999999");
  11812. ASSERT_FALSE(cli.is_valid());
  11813. }
  11814. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  11815. // Port 99999 exceeds valid range (1-65535) — should not crash
  11816. httplib::Client cli("http://www.google.com:99999");
  11817. ASSERT_FALSE(cli.is_valid());
  11818. }
  11819. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  11820. httplib::Client cli("http://www.google.com:80abc");
  11821. ASSERT_FALSE(cli.is_valid());
  11822. }
  11823. #ifdef CPPHTTPLIB_SSL_ENABLED
  11824. TEST(HostAndPortPropertiesTest, SSL) {
  11825. httplib::SSLClient cli("www.google.com");
  11826. ASSERT_EQ("www.google.com", cli.host());
  11827. ASSERT_EQ(443, cli.port());
  11828. }
  11829. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  11830. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  11831. std::string cert;
  11832. read_file(CA_CERT_FILE, cert);
  11833. httplib::SSLClient httplib_client("www.google.com");
  11834. // Load CA store first time
  11835. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11836. // Load CA store second time (update)
  11837. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11838. // Verify client is still valid and can make connections
  11839. httplib_client.enable_server_certificate_verification(true);
  11840. auto res = httplib_client.Get("/");
  11841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11842. // Google may return 200 or 301 depending on various factors
  11843. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  11844. res->status == StatusCode::MovedPermanently_301);
  11845. }
  11846. TEST(SSLClientTest, ServerNameIndication_Online) {
  11847. auto host = "httpbingo.org";
  11848. auto path = std::string{"/get"};
  11849. SSLClient cli(host, 443);
  11850. auto res = cli.Get(path);
  11851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11852. ASSERT_EQ(StatusCode::OK_200, res->status);
  11853. }
  11854. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  11855. // Use a site that will cause SSL verification failure due to self-signed cert
  11856. SSLClient cli("self-signed.badssl.com", 443);
  11857. cli.enable_server_certificate_verification(true);
  11858. auto res = cli.Get("/");
  11859. ASSERT_TRUE(!res);
  11860. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11861. // Verify backend error is captured for SSLServerVerification
  11862. // This occurs when certificate verification fails
  11863. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  11864. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  11865. EXPECT_NE(0UL, res.ssl_backend_error());
  11866. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11867. // For OpenSSL, ssl_error is 0 for verification errors
  11868. EXPECT_EQ(0, res.ssl_error());
  11869. #if !defined(_WIN32) || \
  11870. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11871. // On non-Windows or when Windows Schannel is disabled, the error comes
  11872. // from OpenSSL's verification
  11873. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  11874. res.ssl_backend_error());
  11875. #endif
  11876. #endif
  11877. }
  11878. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  11879. // Use a site where hostname doesn't match the certificate
  11880. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  11881. SSLClient cli("wrong.host.badssl.com", 443);
  11882. cli.enable_server_certificate_verification(true);
  11883. cli.enable_server_hostname_verification(true);
  11884. auto res = cli.Get("/");
  11885. ASSERT_TRUE(!res);
  11886. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  11887. // Verify backend error is captured for hostname verification failure
  11888. EXPECT_NE(0UL, res.ssl_backend_error());
  11889. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11890. // For OpenSSL, ssl_error is 0 for verification errors
  11891. EXPECT_EQ(0, res.ssl_error());
  11892. #if !defined(_WIN32) || \
  11893. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11894. // On non-Windows or when Windows Schannel is disabled, the error comes
  11895. // from OpenSSL's hostname verification
  11896. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  11897. res.ssl_backend_error());
  11898. #endif
  11899. #endif
  11900. }
  11901. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  11902. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11903. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  11904. SSLClient cli("www.google.com", 443);
  11905. cli.enable_server_certificate_verification(true);
  11906. auto res = cli.Get("/");
  11907. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11908. }
  11909. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  11910. SSLClient cli("www.google.com", 443);
  11911. cli.enable_server_certificate_verification(true);
  11912. cli.enable_windows_certificate_verification(false);
  11913. auto res = cli.Get("/");
  11914. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11915. }
  11916. // The server sends an intermediate cross-signed by a root Windows trusts,
  11917. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  11918. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  11919. SSLClient cli("accounts.spotify.com", 443);
  11920. auto res = cli.Get("/");
  11921. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  11922. << " ssl_backend_error=" << res.ssl_backend_error();
  11923. }
  11924. // Windows, not the backend, decides on the chain: the error carries a
  11925. // CryptoAPI trust status, which no backend error for a self-signed
  11926. // certificate has.
  11927. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  11928. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11929. ASSERT_TRUE(svr.is_valid());
  11930. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11931. auto se = detail::scope_exit([&] {
  11932. svr.stop();
  11933. t.join();
  11934. ASSERT_FALSE(svr.is_running());
  11935. });
  11936. svr.wait_until_ready();
  11937. SSLClient cli("127.0.0.1", PORT);
  11938. cli.set_connection_timeout(30);
  11939. auto res = cli.Get("/");
  11940. ASSERT_FALSE(res);
  11941. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11942. EXPECT_NE(0u, res.ssl_backend_error() & CERT_TRUST_IS_UNTRUSTED_ROOT)
  11943. << "ssl_backend_error=" << res.ssl_backend_error();
  11944. }
  11945. #endif
  11946. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  11947. Client cli("https://google.com");
  11948. auto res = cli.Get("/");
  11949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11950. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11951. }
  11952. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  11953. SSLClient cli("google.com");
  11954. cli.set_ca_cert_path(CA_CERT_FILE);
  11955. auto res = cli.Get("/");
  11956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11957. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11958. }
  11959. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  11960. SSLClient cli("google.com");
  11961. cli.enable_server_certificate_verification(true);
  11962. cli.set_ca_cert_path("hello");
  11963. auto res = cli.Get("/");
  11964. ASSERT_TRUE(!res);
  11965. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  11966. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  11967. // should be set
  11968. EXPECT_EQ(0, res.ssl_error());
  11969. // Verify backend error is captured for SSLLoadingCerts
  11970. // This error occurs when loading CA certificates fails
  11971. EXPECT_NE(0UL, res.ssl_backend_error());
  11972. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11973. // OpenSSL specific error codes:
  11974. // > openssl errstr 0x80000002
  11975. // error:80000002:system library::No such file or directory
  11976. // > openssl errstr 0xA000126
  11977. // error:0A000126:SSL routines::unexpected eof while reading
  11978. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  11979. res.ssl_backend_error() == 0xA000126);
  11980. #endif
  11981. }
  11982. TEST(SSLClientTest, ServerCertificateVerification4) {
  11983. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11984. ASSERT_TRUE(svr.is_valid());
  11985. svr.Get("/test", [&](const Request &, Response &res) {
  11986. res.set_content("test", "text/plain");
  11987. svr.stop();
  11988. ASSERT_TRUE(true);
  11989. });
  11990. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11991. auto se = detail::scope_exit([&] {
  11992. t.join();
  11993. ASSERT_FALSE(svr.is_running());
  11994. });
  11995. svr.wait_until_ready();
  11996. SSLClient cli("127.0.0.1", PORT);
  11997. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11998. cli.enable_server_certificate_verification(true);
  11999. cli.set_connection_timeout(30);
  12000. auto res = cli.Get("/test");
  12001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12002. ASSERT_EQ(StatusCode::OK_200, res->status);
  12003. }
  12004. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12005. std::string cert;
  12006. read_file(CA_CERT_FILE, cert);
  12007. SSLClient cli("google.com");
  12008. cli.load_ca_cert_store(cert.data(), cert.size());
  12009. const auto res = cli.Get("/");
  12010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12011. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12012. }
  12013. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12014. // clang-format off
  12015. static constexpr char cert[] =
  12016. "GlobalSign Root CA\n"
  12017. "==================\n"
  12018. "-----BEGIN CERTIFICATE-----\n"
  12019. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12020. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12021. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12022. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12023. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12024. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12025. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12026. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12027. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12028. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12029. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12030. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12031. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12032. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12033. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12034. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12035. "-----END CERTIFICATE-----\n";
  12036. // clang-format on
  12037. SSLClient cli("google.com");
  12038. cli.load_ca_cert_store(cert, sizeof(cert));
  12039. const auto res = cli.Get("/");
  12040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12041. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12042. }
  12043. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12044. SSLClient cli("www.youtube.com");
  12045. cli.set_ca_cert_path(CA_CERT_FILE);
  12046. cli.enable_server_certificate_verification(true);
  12047. cli.set_follow_location(true);
  12048. auto res = cli.Get("/");
  12049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12050. ASSERT_EQ(StatusCode::OK_200, res->status);
  12051. }
  12052. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12053. SSLClient cli("wWw.YouTube.Com");
  12054. cli.set_ca_cert_path(CA_CERT_FILE);
  12055. cli.enable_server_certificate_verification(true);
  12056. cli.enable_server_hostname_verification(true);
  12057. cli.set_follow_location(true);
  12058. auto res = cli.Get("/");
  12059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12060. ASSERT_EQ(StatusCode::OK_200, res->status);
  12061. }
  12062. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12063. SSLClient cli("gOoGlE.COm");
  12064. cli.enable_server_certificate_verification(true);
  12065. cli.enable_server_hostname_verification(true);
  12066. cli.set_follow_location(true);
  12067. auto res = cli.Get("/");
  12068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12069. ASSERT_EQ(StatusCode::OK_200, res->status);
  12070. }
  12071. TEST(SSLClientTest, Issue2004_Online) {
  12072. Client client("https://google.com");
  12073. client.set_follow_location(true);
  12074. auto res = client.Get("/");
  12075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12076. ASSERT_EQ(StatusCode::OK_200, res->status);
  12077. auto body = res->body;
  12078. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12079. }
  12080. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12081. // Create SSLClient with invalid cert/key to make is_valid() return false
  12082. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12083. "nonexistent_key.pem");
  12084. // is_valid() should be false due to cert loading failure
  12085. ASSERT_FALSE(cli.is_valid());
  12086. auto res = cli.Get("/");
  12087. ASSERT_FALSE(res);
  12088. EXPECT_EQ(Error::SSLConnection, res.error());
  12089. }
  12090. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12091. // Test for Issue #2251: SSL error not properly reported when client cert
  12092. // and key paths are swapped or mismatched
  12093. // This simulates the scenario where user accidentally swaps the cert and key
  12094. // files
  12095. // Using client cert file as private key and vice versa (completely wrong)
  12096. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12097. // Should fail validation due to cert/key mismatch
  12098. ASSERT_FALSE(cli.is_valid());
  12099. // Attempt to make a request should fail with proper error
  12100. auto res = cli.Get("/");
  12101. ASSERT_FALSE(res);
  12102. EXPECT_EQ(Error::SSLConnection, res.error());
  12103. // SSL error should be recorded in the Result object (this is the key fix for
  12104. // Issue #2251)
  12105. auto backend_error = res.ssl_backend_error();
  12106. EXPECT_NE(0u, backend_error);
  12107. }
  12108. // Tests cert/key mismatch detection at the TLS context level
  12109. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12110. // Test that using mismatched cert/key causes connection failure.
  12111. // We verify this at the SSLClient level rather than through internal
  12112. // TLS API functions.
  12113. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12114. cli.enable_server_certificate_verification(false);
  12115. cli.set_connection_timeout(2);
  12116. // The mismatch should cause a connection or handshake error
  12117. auto res = cli.Get("/test");
  12118. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12119. // Either way, the request should fail
  12120. EXPECT_FALSE(res);
  12121. }
  12122. #endif
  12123. #if 0
  12124. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12125. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12126. ASSERT_TRUE(cli != nullptr);
  12127. cli->set_address_family(AF_INET6);
  12128. cli->set_interface("en0");
  12129. auto res = cli->Get("/get");
  12130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12131. ASSERT_EQ(StatusCode::OK_200, res->status);
  12132. }
  12133. #endif
  12134. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12135. #ifdef CPPHTTPLIB_SSL_ENABLED
  12136. void ClientCertPresent(
  12137. const std::string &client_cert_file,
  12138. const std::string &client_private_key_file,
  12139. const std::string &client_encrypted_private_key_pass = std::string()) {
  12140. using namespace httplib::tls;
  12141. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12142. CLIENT_CA_CERT_DIR);
  12143. ASSERT_TRUE(svr.is_valid());
  12144. svr.Get("/test", [&](const Request &req, Response &res) {
  12145. res.set_content("test", "text/plain");
  12146. auto cert = req.peer_cert();
  12147. ASSERT_TRUE(static_cast<bool>(cert));
  12148. std::string common_name = cert.subject_cn();
  12149. EXPECT_EQ("Common Name", common_name);
  12150. });
  12151. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12152. auto se = detail::scope_exit([&] {
  12153. svr.stop();
  12154. t.join();
  12155. ASSERT_FALSE(svr.is_running());
  12156. });
  12157. svr.wait_until_ready();
  12158. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12159. client_encrypted_private_key_pass);
  12160. cli.enable_server_certificate_verification(false);
  12161. cli.set_connection_timeout(30);
  12162. auto res = cli.Get("/test");
  12163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12164. ASSERT_EQ(StatusCode::OK_200, res->status);
  12165. }
  12166. TEST(SSLClientServerTest, ClientCertPresent) {
  12167. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12168. }
  12169. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12170. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12171. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12172. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12173. }
  12174. // PEM memory-based constructor tests (works with all TLS backends)
  12175. void PemMemoryClientCertPresent(
  12176. const std::string &client_cert_file,
  12177. const std::string &client_private_key_file,
  12178. const std::string &client_encrypted_private_key_pass = std::string()) {
  12179. // Read PEM files into memory
  12180. std::string server_cert_pem, server_key_pem;
  12181. std::string client_ca_pem;
  12182. std::string client_cert_pem, client_key_pem;
  12183. read_file(SERVER_CERT_FILE, server_cert_pem);
  12184. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12185. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12186. read_file(client_cert_file, client_cert_pem);
  12187. read_file(client_private_key_file, client_key_pem);
  12188. // Create server with PEM memory
  12189. SSLServer::PemMemory server_pem = {
  12190. server_cert_pem.c_str(),
  12191. server_cert_pem.size(),
  12192. server_key_pem.c_str(),
  12193. server_key_pem.size(),
  12194. client_ca_pem.c_str(),
  12195. client_ca_pem.size(),
  12196. nullptr // no password for server key
  12197. };
  12198. SSLServer svr(server_pem);
  12199. ASSERT_TRUE(svr.is_valid());
  12200. svr.Get("/test", [&](const Request &, Response &res) {
  12201. res.set_content("test", "text/plain");
  12202. });
  12203. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12204. auto se = detail::scope_exit([&] {
  12205. svr.stop();
  12206. t.join();
  12207. ASSERT_FALSE(svr.is_running());
  12208. });
  12209. svr.wait_until_ready();
  12210. // Create client with PEM memory
  12211. const char *password = client_encrypted_private_key_pass.empty()
  12212. ? nullptr
  12213. : client_encrypted_private_key_pass.c_str();
  12214. SSLClient::PemMemory client_pem = {
  12215. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12216. client_key_pem.size(), password};
  12217. SSLClient cli(HOST, PORT, client_pem);
  12218. cli.enable_server_certificate_verification(false);
  12219. cli.set_connection_timeout(30);
  12220. auto res = cli.Get("/test");
  12221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12222. ASSERT_EQ(StatusCode::OK_200, res->status);
  12223. }
  12224. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12225. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12226. }
  12227. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12228. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12229. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12230. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12231. }
  12232. TEST(SSLClientServerTest, ClientCertMissing) {
  12233. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12234. CLIENT_CA_CERT_DIR);
  12235. ASSERT_TRUE(svr.is_valid());
  12236. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12237. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12238. auto se = detail::scope_exit([&] {
  12239. svr.stop();
  12240. t.join();
  12241. ASSERT_FALSE(svr.is_running());
  12242. });
  12243. svr.wait_until_ready();
  12244. SSLClient cli(HOST, PORT);
  12245. cli.set_connection_timeout(30);
  12246. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12247. // the chain check on Windows, so the result does not depend on the order.
  12248. cli.enable_server_hostname_verification(false);
  12249. auto res = cli.Get("/test");
  12250. ASSERT_TRUE(!res);
  12251. // When client cert is missing and server requires it, connection fails
  12252. // Error type depends on backend implementation
  12253. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12254. res.error() == Error::SSLConnection);
  12255. // Verify backend error is captured
  12256. // Note: This test may have different error codes depending on the exact
  12257. // verification failure
  12258. EXPECT_NE(0UL, res.ssl_backend_error());
  12259. }
  12260. TEST(SSLClientServerTest, TrustDirOptional) {
  12261. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12262. ASSERT_TRUE(svr.is_valid());
  12263. svr.Get("/test", [&](const Request &, Response &res) {
  12264. res.set_content("test", "text/plain");
  12265. });
  12266. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12267. auto se = detail::scope_exit([&] {
  12268. svr.stop();
  12269. t.join();
  12270. ASSERT_FALSE(svr.is_running());
  12271. });
  12272. svr.wait_until_ready();
  12273. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12274. cli.enable_server_certificate_verification(false);
  12275. cli.set_connection_timeout(30);
  12276. auto res = cli.Get("/test");
  12277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12278. ASSERT_EQ(StatusCode::OK_200, res->status);
  12279. }
  12280. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12281. class NoListenSSLServer : public SSLServer {
  12282. public:
  12283. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12284. const char *client_ca_cert_file_path,
  12285. const char *client_ca_cert_dir_path = nullptr)
  12286. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12287. client_ca_cert_dir_path),
  12288. stop_(false) {}
  12289. std::atomic_bool stop_;
  12290. private:
  12291. bool process_and_close_socket(socket_t /*sock*/) override {
  12292. // Don't create SSL context
  12293. while (!stop_.load()) {
  12294. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12295. }
  12296. return true;
  12297. }
  12298. };
  12299. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12300. CLIENT_CA_CERT_FILE);
  12301. ASSERT_TRUE(svr.is_valid());
  12302. svr.Get("/test", [&](const Request &, Response &res) {
  12303. res.set_content("test", "text/plain");
  12304. });
  12305. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12306. auto se = detail::scope_exit([&] {
  12307. svr.stop_ = true;
  12308. svr.stop();
  12309. t.join();
  12310. ASSERT_FALSE(svr.is_running());
  12311. });
  12312. svr.wait_until_ready();
  12313. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12314. cli.enable_server_certificate_verification(false);
  12315. cli.set_connection_timeout(1);
  12316. auto res = cli.Get("/test");
  12317. ASSERT_TRUE(!res);
  12318. EXPECT_EQ(Error::SSLConnection, res.error());
  12319. // Timeout results in WantRead error code (maps to backend-specific value)
  12320. EXPECT_NE(0, res.ssl_error());
  12321. }
  12322. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12323. // Test SSLServer with client certificate verification using the standard
  12324. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12325. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12326. CLIENT_CA_CERT_DIR);
  12327. ASSERT_TRUE(svr.is_valid());
  12328. svr.Get("/test", [&](const Request &req, Response &res) {
  12329. res.set_content("test", "text/plain");
  12330. auto cert = req.peer_cert();
  12331. ASSERT_TRUE(static_cast<bool>(cert));
  12332. auto common_name = cert.subject_cn();
  12333. EXPECT_EQ("Common Name", common_name);
  12334. });
  12335. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12336. auto se = detail::scope_exit([&] {
  12337. svr.stop();
  12338. t.join();
  12339. ASSERT_FALSE(svr.is_running());
  12340. });
  12341. svr.wait_until_ready();
  12342. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12343. cli.enable_server_certificate_verification(false);
  12344. cli.set_connection_timeout(30);
  12345. auto res = cli.Get("/test");
  12346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12347. ASSERT_EQ(StatusCode::OK_200, res->status);
  12348. }
  12349. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12350. // Verifies that wildcard matching and exact matching work consistently
  12351. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12352. using namespace httplib::tls;
  12353. // We need a running server to test against
  12354. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12355. ASSERT_TRUE(svr.is_valid());
  12356. svr.Get("/test", [](const Request &, Response &res) {
  12357. res.set_content("ok", "text/plain");
  12358. });
  12359. thread t([&]() { svr.listen(HOST, PORT); });
  12360. auto se = detail::scope_exit([&] {
  12361. svr.stop();
  12362. t.join();
  12363. });
  12364. svr.wait_until_ready();
  12365. bool verify_callback_called = false;
  12366. bool verify_result_wrong = false;
  12367. SSLClient cli(HOST, PORT);
  12368. cli.enable_server_certificate_verification(true);
  12369. cli.set_ca_cert_path(CA_CERT_FILE);
  12370. cli.set_connection_timeout(5);
  12371. // Note: Test certificate has CN="Common Name", not "localhost"
  12372. bool verify_result_cn = false;
  12373. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12374. verify_callback_called = true;
  12375. if (!ctx.cert) return false;
  12376. // Test 1: "Common Name" should match (our test server cert CN)
  12377. verify_result_cn = ctx.check_hostname("Common Name");
  12378. // Test 2: wrong hostname should not match
  12379. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12380. return true; // Accept for the purpose of this test
  12381. });
  12382. auto res = cli.Get("/test");
  12383. // The request may succeed or fail depending on cert configuration
  12384. // but the callback should have been called
  12385. ASSERT_TRUE(verify_callback_called)
  12386. << "Verify callback should have been called";
  12387. // CN="Common Name" should match our test certificate
  12388. //
  12389. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12390. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12391. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12392. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12393. // <openssl/base.h>, which is included transitively when
  12394. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12395. #if defined(OPENSSL_IS_BORINGSSL)
  12396. EXPECT_FALSE(verify_result_cn)
  12397. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12398. #else
  12399. EXPECT_TRUE(verify_result_cn)
  12400. << "verify_hostname should match 'Common Name' (certificate CN)";
  12401. #endif
  12402. // Wrong hostname should not match
  12403. EXPECT_FALSE(verify_result_wrong)
  12404. << "verify_hostname should not match 'wronghost.example.com'";
  12405. }
  12406. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12407. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12408. // X509_check_ip behavior and must hold for every backend.
  12409. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12410. using namespace httplib::tls;
  12411. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12412. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12413. ASSERT_TRUE(svr.is_valid());
  12414. svr.Get("/test", [](const Request &, Response &res) {
  12415. res.set_content("ok", "text/plain");
  12416. });
  12417. thread t([&]() { svr.listen(HOST, PORT); });
  12418. auto se = detail::scope_exit([&] {
  12419. svr.stop();
  12420. t.join();
  12421. });
  12422. svr.wait_until_ready();
  12423. bool verify_callback_called = false;
  12424. bool ip_matched_via_cn = true;
  12425. SSLClient cli(HOST, PORT);
  12426. cli.enable_server_certificate_verification(true);
  12427. cli.set_ca_cert_path(CA_CERT_FILE);
  12428. cli.set_connection_timeout(5);
  12429. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12430. verify_callback_called = true;
  12431. if (!ctx.cert) return false;
  12432. // The IP appears only in the CN, so it must NOT be accepted.
  12433. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12434. return true; // Accept for the purpose of this test
  12435. });
  12436. cli.Get("/test");
  12437. ASSERT_TRUE(verify_callback_called)
  12438. << "Verify callback should have been called";
  12439. EXPECT_FALSE(ip_matched_via_cn)
  12440. << "An IP host must not be authenticated via the certificate CN";
  12441. }
  12442. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12443. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12444. using namespace httplib::tls;
  12445. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12446. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12447. ASSERT_TRUE(svr.is_valid());
  12448. svr.Get("/test", [](const Request &, Response &res) {
  12449. res.set_content("ok", "text/plain");
  12450. });
  12451. thread t([&]() { svr.listen(HOST, PORT); });
  12452. auto se = detail::scope_exit([&] {
  12453. svr.stop();
  12454. t.join();
  12455. });
  12456. svr.wait_until_ready();
  12457. bool verify_callback_called = false;
  12458. bool san_matched = false;
  12459. bool wrong_ipv6_matched = true;
  12460. bool cn_ipv6_matched = true;
  12461. SSLClient cli(HOST, PORT);
  12462. cli.enable_server_certificate_verification(true);
  12463. cli.set_ca_cert_path(CA_CERT_FILE);
  12464. cli.set_connection_timeout(5);
  12465. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12466. verify_callback_called = true;
  12467. if (!ctx.cert) return false;
  12468. // Matches the IPv6 iPAddress SAN.
  12469. san_matched = ctx.check_hostname("2001:db8::1");
  12470. // A different IPv6 address must not match.
  12471. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12472. // "::1" lives only in the CN, so it must not be accepted.
  12473. cn_ipv6_matched = ctx.check_hostname("::1");
  12474. return true; // Accept for the purpose of this test
  12475. });
  12476. cli.Get("/test");
  12477. ASSERT_TRUE(verify_callback_called)
  12478. << "Verify callback should have been called";
  12479. EXPECT_TRUE(san_matched)
  12480. << "verify_hostname should match an IPv6 iPAddress SAN";
  12481. EXPECT_FALSE(wrong_ipv6_matched)
  12482. << "verify_hostname should not match a non-matching IPv6 address";
  12483. EXPECT_FALSE(cn_ipv6_matched)
  12484. << "An IPv6 host must not be authenticated via the certificate CN";
  12485. }
  12486. #endif
  12487. // mbedTLS-specific callback constructor test
  12488. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  12489. #ifdef CPPHTTPLIB_SSL_ENABLED
  12490. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  12491. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12492. ASSERT_TRUE(svr.is_valid());
  12493. // Set up a handler to verify client certificate is present
  12494. bool client_cert_verified = false;
  12495. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12496. // Verify that client certificate was provided
  12497. client_cert_verified = true;
  12498. res.set_content("success", "text/plain");
  12499. });
  12500. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12501. auto se = detail::scope_exit([&] {
  12502. svr.stop();
  12503. t.join();
  12504. ASSERT_FALSE(svr.is_running());
  12505. });
  12506. svr.wait_until_ready();
  12507. // Client with certificate
  12508. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12509. cli.enable_server_certificate_verification(false);
  12510. cli.set_connection_timeout(30);
  12511. auto res = cli.Get("/test");
  12512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12513. ASSERT_EQ(StatusCode::OK_200, res->status);
  12514. ASSERT_TRUE(client_cert_verified);
  12515. EXPECT_EQ("success", res->body);
  12516. }
  12517. #endif
  12518. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  12519. // backends
  12520. #ifdef CPPHTTPLIB_SSL_ENABLED
  12521. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  12522. using namespace httplib::tls;
  12523. // Test that when client CA cert file is provided,
  12524. // the server properly requests and validates client certificates
  12525. // Create a server with client authentication
  12526. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12527. ASSERT_TRUE(svr.is_valid());
  12528. bool handler_called = false;
  12529. svr.Get("/test", [&](const Request &req, Response &res) {
  12530. handler_called = true;
  12531. // Verify that a client certificate was provided
  12532. auto cert = req.peer_cert();
  12533. ASSERT_TRUE(static_cast<bool>(cert));
  12534. // Get the issuer name
  12535. std::string issuer_str = cert.issuer_name();
  12536. ASSERT_FALSE(issuer_str.empty());
  12537. // The client certificate should be issued by our test CA
  12538. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  12539. res.set_content("authenticated", "text/plain");
  12540. });
  12541. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12542. auto se = detail::scope_exit([&] {
  12543. svr.stop();
  12544. t.join();
  12545. ASSERT_FALSE(svr.is_running());
  12546. });
  12547. svr.wait_until_ready();
  12548. // Connect with a client certificate issued by the CA
  12549. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12550. cli.enable_server_certificate_verification(false);
  12551. cli.set_connection_timeout(30);
  12552. auto res = cli.Get("/test");
  12553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12554. ASSERT_EQ(StatusCode::OK_200, res->status);
  12555. ASSERT_TRUE(handler_called);
  12556. EXPECT_EQ("authenticated", res->body);
  12557. }
  12558. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12559. using namespace httplib::tls;
  12560. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12561. ASSERT_TRUE(svr.is_valid());
  12562. svr.Get("/test", [](const Request &, Response &res) {
  12563. res.set_content("ok", "text/plain");
  12564. });
  12565. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12566. auto se = detail::scope_exit([&] {
  12567. svr.stop();
  12568. t.join();
  12569. });
  12570. svr.wait_until_ready();
  12571. SSLClient cli(HOST, PORT);
  12572. cli.enable_server_certificate_verification(false);
  12573. cli.set_connection_timeout(30);
  12574. bool cert_checked = false;
  12575. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12576. if (ctx.cert) {
  12577. auto sans = ctx.sans();
  12578. // Test certificate may or may not have SANs - just verify the API
  12579. // works If SANs exist, verify the types are valid
  12580. for (const auto &san : sans) {
  12581. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  12582. san.type == SanType::EMAIL || san.type == SanType::URI ||
  12583. san.type == SanType::OTHER);
  12584. EXPECT_FALSE(san.value.empty());
  12585. }
  12586. cert_checked = true;
  12587. }
  12588. return true;
  12589. });
  12590. auto res = cli.Get("/test");
  12591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12592. EXPECT_TRUE(cert_checked);
  12593. }
  12594. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  12595. using namespace httplib::tls;
  12596. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12597. ASSERT_TRUE(svr.is_valid());
  12598. svr.Get("/test", [](const Request &, Response &res) {
  12599. res.set_content("ok", "text/plain");
  12600. });
  12601. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12602. auto se = detail::scope_exit([&] {
  12603. svr.stop();
  12604. t.join();
  12605. });
  12606. svr.wait_until_ready();
  12607. SSLClient cli(HOST, PORT);
  12608. cli.enable_server_certificate_verification(false);
  12609. cli.set_connection_timeout(30);
  12610. bool validity_checked = false;
  12611. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12612. if (ctx.cert) {
  12613. time_t not_before = 0, not_after = 0;
  12614. bool result = ctx.validity(not_before, not_after);
  12615. EXPECT_TRUE(result);
  12616. // Verify that not_before < now < not_after for a valid cert
  12617. time_t now = time(nullptr);
  12618. EXPECT_LT(not_before, now);
  12619. EXPECT_GT(not_after, now);
  12620. validity_checked = true;
  12621. }
  12622. return true;
  12623. });
  12624. auto res = cli.Get("/test");
  12625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12626. EXPECT_TRUE(validity_checked);
  12627. }
  12628. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  12629. using namespace httplib::tls;
  12630. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12631. ASSERT_TRUE(svr.is_valid());
  12632. svr.Get("/test", [](const Request &, Response &res) {
  12633. res.set_content("ok", "text/plain");
  12634. });
  12635. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12636. auto se = detail::scope_exit([&] {
  12637. svr.stop();
  12638. t.join();
  12639. });
  12640. svr.wait_until_ready();
  12641. SSLClient cli(HOST, PORT);
  12642. cli.enable_server_certificate_verification(false);
  12643. cli.set_connection_timeout(30);
  12644. bool serial_checked = false;
  12645. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12646. if (ctx.cert) {
  12647. std::string serial = ctx.serial();
  12648. EXPECT_FALSE(serial.empty());
  12649. // Serial should be a hex string
  12650. for (char c : serial) {
  12651. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  12652. (c >= 'a' && c <= 'f'));
  12653. }
  12654. serial_checked = true;
  12655. }
  12656. return true;
  12657. });
  12658. auto res = cli.Get("/test");
  12659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12660. EXPECT_TRUE(serial_checked);
  12661. }
  12662. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  12663. // Test 1: Valid CA file - no error should be recorded
  12664. {
  12665. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12666. CLIENT_CA_CERT_FILE);
  12667. ASSERT_TRUE(svr.is_valid());
  12668. // With valid setup, last_ssl_error should be 0
  12669. EXPECT_EQ(0, svr.ssl_last_error());
  12670. }
  12671. // Test 2: Invalid CA file content
  12672. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  12673. {
  12674. // Create a temporary file with completely invalid content
  12675. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  12676. {
  12677. std::ofstream ofs(temp_invalid_ca);
  12678. ofs << "This is not a certificate file at all\n";
  12679. ofs << "Just plain text content\n";
  12680. }
  12681. // Create server with invalid CA file
  12682. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  12683. // Clean up temporary file
  12684. std::remove(temp_invalid_ca);
  12685. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  12686. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  12687. // Note: SSL_CTX_load_verify_locations typically fails first,
  12688. // but our error handling code path is still exercised
  12689. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  12690. }
  12691. }
  12692. TEST(VerifyCallbackTest, VerifyContextFields) {
  12693. using namespace httplib::tls;
  12694. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12695. ASSERT_TRUE(svr.is_valid());
  12696. svr.Get("/test", [](const Request &, Response &res) {
  12697. res.set_content("ok", "text/plain");
  12698. });
  12699. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12700. auto se = detail::scope_exit([&] {
  12701. svr.stop();
  12702. t.join();
  12703. });
  12704. svr.wait_until_ready();
  12705. SSLClient cli(HOST, PORT);
  12706. cli.enable_server_certificate_verification(false);
  12707. cli.set_connection_timeout(30);
  12708. int callback_count = 0;
  12709. bool saw_leaf_cert = false;
  12710. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12711. if (ctx.cert) {
  12712. callback_count++;
  12713. // We should see at least one certificate (the leaf)
  12714. std::string cn = ctx.subject_cn();
  12715. if (!cn.empty()) { saw_leaf_cert = true; }
  12716. // Verify context fields are populated
  12717. EXPECT_NE(ctx.session, nullptr);
  12718. EXPECT_GE(ctx.depth, 0);
  12719. }
  12720. return true;
  12721. });
  12722. auto res = cli.Get("/test");
  12723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12724. EXPECT_GT(callback_count, 0);
  12725. EXPECT_TRUE(saw_leaf_cert);
  12726. }
  12727. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  12728. using httplib::tls::TlsError;
  12729. // Test that verify_error_to_string returns empty for success
  12730. std::string success_str = TlsError::verify_error_to_string(0);
  12731. EXPECT_TRUE(success_str.empty());
  12732. // Test that verify_error_to_string returns non-empty for error codes
  12733. // Using a common error code (certificate expired)
  12734. std::string error_str =
  12735. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  12736. EXPECT_FALSE(error_str.empty());
  12737. }
  12738. TEST(SessionVerifierTest, CertificateAccepted) {
  12739. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12740. ASSERT_TRUE(svr.is_valid());
  12741. svr.Get("/test", [](const Request &, Response &res) {
  12742. res.set_content("ok", "text/plain");
  12743. });
  12744. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12745. auto se = detail::scope_exit([&] {
  12746. svr.stop();
  12747. t.join();
  12748. });
  12749. svr.wait_until_ready();
  12750. SSLClient cli(HOST, PORT);
  12751. cli.enable_server_certificate_verification(false);
  12752. cli.set_connection_timeout(30);
  12753. bool callback_called = false;
  12754. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12755. EXPECT_NE(session, nullptr);
  12756. callback_called = true;
  12757. return SSLVerifierResponse::CertificateAccepted;
  12758. });
  12759. auto res = cli.Get("/test");
  12760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12761. EXPECT_EQ(200, res->status);
  12762. EXPECT_TRUE(callback_called);
  12763. }
  12764. TEST(SessionVerifierTest, CertificateRejected) {
  12765. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12766. ASSERT_TRUE(svr.is_valid());
  12767. svr.Get("/test", [](const Request &, Response &res) {
  12768. res.set_content("ok", "text/plain");
  12769. });
  12770. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12771. auto se = detail::scope_exit([&] {
  12772. svr.stop();
  12773. t.join();
  12774. });
  12775. svr.wait_until_ready();
  12776. SSLClient cli(HOST, PORT);
  12777. cli.enable_server_certificate_verification(false);
  12778. cli.set_connection_timeout(30);
  12779. bool callback_called = false;
  12780. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12781. EXPECT_NE(session, nullptr);
  12782. callback_called = true;
  12783. return SSLVerifierResponse::CertificateRejected;
  12784. });
  12785. auto res = cli.Get("/test");
  12786. EXPECT_FALSE(res);
  12787. EXPECT_TRUE(callback_called);
  12788. }
  12789. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  12790. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12791. ASSERT_TRUE(svr.is_valid());
  12792. svr.Get("/test", [](const Request &, Response &res) {
  12793. res.set_content("ok", "text/plain");
  12794. });
  12795. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12796. auto se = detail::scope_exit([&] {
  12797. svr.stop();
  12798. t.join();
  12799. });
  12800. svr.wait_until_ready();
  12801. // NoDecisionMade with verification disabled should succeed (no default check)
  12802. SSLClient cli(HOST, PORT);
  12803. cli.enable_server_certificate_verification(false);
  12804. cli.set_connection_timeout(30);
  12805. bool callback_called = false;
  12806. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12807. EXPECT_NE(session, nullptr);
  12808. callback_called = true;
  12809. return SSLVerifierResponse::NoDecisionMade;
  12810. });
  12811. auto res = cli.Get("/test");
  12812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12813. EXPECT_EQ(200, res->status);
  12814. EXPECT_TRUE(callback_called);
  12815. }
  12816. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  12817. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12818. ASSERT_TRUE(svr.is_valid());
  12819. svr.Get("/test", [](const Request &, Response &res) {
  12820. res.set_content("ok", "text/plain");
  12821. });
  12822. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12823. auto se = detail::scope_exit([&] {
  12824. svr.stop();
  12825. t.join();
  12826. });
  12827. svr.wait_until_ready();
  12828. // NoDecisionMade with verification enabled should fail (self-signed cert).
  12829. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  12830. // so we only check that the request fails, not whether the callback was
  12831. // called.
  12832. SSLClient cli(HOST, PORT);
  12833. cli.enable_server_certificate_verification(true);
  12834. cli.set_connection_timeout(30);
  12835. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12836. EXPECT_NE(session, nullptr);
  12837. return SSLVerifierResponse::NoDecisionMade;
  12838. });
  12839. auto res = cli.Get("/test");
  12840. EXPECT_FALSE(res);
  12841. }
  12842. TEST(SSLClientServerTest, ClientCAListFromPem) {
  12843. // Test SSL server using PemMemory constructor with client CA certificates
  12844. // Read PEM files
  12845. std::string server_cert_pem, server_key_pem, client_ca_pem;
  12846. read_file(SERVER_CERT_FILE, server_cert_pem);
  12847. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12848. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12849. // Create SSLServer with PemMemory constructor including client CA
  12850. SSLServer::PemMemory server_pem = {
  12851. server_cert_pem.c_str(),
  12852. server_cert_pem.size(),
  12853. server_key_pem.c_str(),
  12854. server_key_pem.size(),
  12855. client_ca_pem.c_str(),
  12856. client_ca_pem.size(),
  12857. nullptr // no password for server key
  12858. };
  12859. SSLServer svr(server_pem);
  12860. ASSERT_TRUE(svr.is_valid());
  12861. // No SSL error should be recorded for valid setup
  12862. EXPECT_EQ(0, svr.ssl_last_error());
  12863. // Set up server endpoints
  12864. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  12865. res.set_content("ok", "text/plain");
  12866. });
  12867. // Start server in a thread
  12868. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  12869. svr.wait_until_ready();
  12870. // Connect with client certificate (using constructor with paths)
  12871. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12872. cli.enable_server_certificate_verification(false);
  12873. auto res = cli.Get("/test-pem-ca");
  12874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12875. EXPECT_EQ(200, res->status);
  12876. EXPECT_EQ("ok", res->body);
  12877. svr.stop();
  12878. server_thread.join();
  12879. }
  12880. #endif
  12881. #ifdef _WIN32
  12882. TEST(CleanupTest, WSACleanup) {
  12883. int ret = WSACleanup();
  12884. ASSERT_EQ(0, ret);
  12885. }
  12886. #endif
  12887. #ifndef CPPHTTPLIB_SSL_ENABLED
  12888. TEST(NoSSLSupport, SimpleInterface) {
  12889. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  12890. }
  12891. #endif
  12892. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12893. TEST(InvalidScheme, SimpleInterface) {
  12894. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  12895. }
  12896. #endif
  12897. TEST(NoScheme, SimpleInterface) {
  12898. Client cli("yahoo.com:80");
  12899. ASSERT_TRUE(cli.is_valid());
  12900. }
  12901. TEST(SendAPI, SimpleInterface_Online) {
  12902. Client cli("http://yahoo.com");
  12903. Request req;
  12904. req.method = "GET";
  12905. req.path = "/";
  12906. auto res = cli.send(req);
  12907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12908. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12909. }
  12910. TEST(SendAPI, WithParamsInRequest) {
  12911. Server svr;
  12912. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  12913. EXPECT_TRUE(req.has_param("test"));
  12914. EXPECT_EQ("test_value", req.get_param_value("test"));
  12915. });
  12916. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12917. auto se = detail::scope_exit([&] {
  12918. svr.stop();
  12919. t.join();
  12920. ASSERT_FALSE(svr.is_running());
  12921. });
  12922. svr.wait_until_ready();
  12923. Client cli(HOST, PORT);
  12924. {
  12925. Request req;
  12926. req.method = "GET";
  12927. req.path = "/";
  12928. req.params.emplace("test", "test_value");
  12929. auto res = cli.send(req);
  12930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12931. }
  12932. {
  12933. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  12934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12935. }
  12936. }
  12937. TEST(ClientImplMethods, GetSocketTest) {
  12938. httplib::Server svr;
  12939. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  12940. res.status = StatusCode::OK_200;
  12941. });
  12942. auto port = svr.bind_to_any_port("127.0.0.1");
  12943. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12944. auto se = detail::scope_exit([&] {
  12945. svr.stop();
  12946. thread.join();
  12947. ASSERT_FALSE(svr.is_running());
  12948. });
  12949. svr.wait_until_ready();
  12950. {
  12951. httplib::Client cli("127.0.0.1", port);
  12952. cli.set_keep_alive(true);
  12953. // Use the behavior of cpp-httplib of opening the connection
  12954. // only when the first request happens. If that changes,
  12955. // this test would be obsolete.
  12956. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  12957. // This also implicitly tests the server. But other tests would fail much
  12958. // earlier than this one to be considered.
  12959. auto res = cli.Get("/");
  12960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12961. EXPECT_EQ(StatusCode::OK_200, res->status);
  12962. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  12963. }
  12964. }
  12965. #ifdef CPPHTTPLIB_SSL_ENABLED
  12966. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  12967. Client cli("http://yahoo.com");
  12968. auto res = cli.Get("/");
  12969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12970. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12971. cli.set_follow_location(true);
  12972. res = cli.Get("/");
  12973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12974. EXPECT_EQ(StatusCode::OK_200, res->status);
  12975. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12976. }
  12977. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  12978. Client cli("https://yahoo.com");
  12979. auto res = cli.Get("/");
  12980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12981. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12982. cli.set_follow_location(true);
  12983. res = cli.Get("/");
  12984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12985. EXPECT_EQ(StatusCode::OK_200, res->status);
  12986. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12987. }
  12988. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  12989. Client cli("https://yahoo.com");
  12990. auto res = cli.Get("/");
  12991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12992. ASSERT_FALSE(!res);
  12993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12994. ASSERT_FALSE(res == nullptr);
  12995. ASSERT_TRUE(res != nullptr);
  12996. EXPECT_EQ(Error::Success, res.error());
  12997. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  12998. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  12999. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13000. cli.set_follow_location(true);
  13001. res = cli.Get("/");
  13002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13003. EXPECT_EQ(Error::Success, res.error());
  13004. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13005. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13006. EXPECT_EQ(StatusCode::OK_200, res->status);
  13007. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13008. }
  13009. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13010. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13011. Client cli("https://cdnjs.cloudflare.com");
  13012. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13013. Headers{{"Accept-Encoding", "br"}});
  13014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13015. EXPECT_EQ(StatusCode::OK_200, res->status);
  13016. EXPECT_EQ(287630U, res->body.size());
  13017. EXPECT_EQ("application/javascript; charset=utf-8",
  13018. res->get_header_value("Content-Type"));
  13019. }
  13020. #endif
  13021. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13022. #undef REDIR_HOST // Silence compiler warning
  13023. #define REDIR_HOST "https://httpbingo.org"
  13024. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13025. Client cli(REDIR_HOST);
  13026. cli.set_follow_location(true);
  13027. auto res =
  13028. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13030. EXPECT_EQ(StatusCode::OK_200, res->status);
  13031. }
  13032. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13033. Client cli(REDIR_HOST);
  13034. cli.set_follow_location(true);
  13035. Params params;
  13036. params.emplace("url", "http://example.com");
  13037. params.emplace("status_code", "302");
  13038. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13040. EXPECT_EQ(StatusCode::OK_200, res->status);
  13041. }
  13042. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13043. Client cli(REDIR_HOST);
  13044. cli.set_follow_location(true);
  13045. Params params;
  13046. params.emplace("url", "http://example.com");
  13047. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13049. EXPECT_EQ(StatusCode::OK_200, res->status);
  13050. }
  13051. TEST(HttpToHttpsRedirectTest, CertFile) {
  13052. auto ssl_port = PORT + 1;
  13053. Server svr;
  13054. ASSERT_TRUE(svr.is_valid());
  13055. svr.Get("/index", [&](const Request &, Response &res) {
  13056. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13057. "/index");
  13058. svr.stop();
  13059. });
  13060. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13061. ASSERT_TRUE(ssl_svr.is_valid());
  13062. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13063. res.set_content("test", "text/plain");
  13064. ssl_svr.stop();
  13065. });
  13066. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13067. thread t2 =
  13068. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13069. auto se = detail::scope_exit([&] {
  13070. t2.join();
  13071. t.join();
  13072. ASSERT_FALSE(svr.is_running());
  13073. });
  13074. svr.wait_until_ready();
  13075. ssl_svr.wait_until_ready();
  13076. Client cli("127.0.0.1", PORT);
  13077. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13078. cli.enable_server_certificate_verification(true);
  13079. cli.set_follow_location(true);
  13080. cli.set_connection_timeout(30);
  13081. auto res = cli.Get("/index");
  13082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13083. ASSERT_EQ(StatusCode::OK_200, res->status);
  13084. }
  13085. TEST(SSLClientRedirectTest, CertFile) {
  13086. auto ssl_port = PORT + 1;
  13087. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13088. ASSERT_TRUE(ssl_svr1.is_valid());
  13089. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13090. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13091. "/index");
  13092. ssl_svr1.stop();
  13093. });
  13094. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13095. ASSERT_TRUE(ssl_svr2.is_valid());
  13096. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13097. res.set_content("test", "text/plain");
  13098. ssl_svr2.stop();
  13099. });
  13100. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13101. thread t2 =
  13102. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13103. auto se = detail::scope_exit([&] {
  13104. t2.join();
  13105. t.join();
  13106. ASSERT_FALSE(ssl_svr1.is_running());
  13107. });
  13108. ssl_svr1.wait_until_ready();
  13109. ssl_svr2.wait_until_ready();
  13110. SSLClient cli("127.0.0.1", PORT);
  13111. std::string cert;
  13112. read_file(SERVER_CERT2_FILE, cert);
  13113. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13114. cli.enable_server_certificate_verification(true);
  13115. cli.set_follow_location(true);
  13116. cli.set_connection_timeout(30);
  13117. auto res = cli.Get("/index");
  13118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13119. ASSERT_EQ(StatusCode::OK_200, res->status);
  13120. }
  13121. #endif
  13122. #ifdef CPPHTTPLIB_SSL_ENABLED
  13123. // Test that set_ca_cert_store() skips system certs (consistent with
  13124. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13125. // should be trusted - system certs should NOT be loaded.
  13126. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  13127. // Load a specific cert that is NOT a system CA cert
  13128. std::string cert;
  13129. read_file(SERVER_CERT2_FILE, cert);
  13130. SSLClient cli("google.com");
  13131. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13132. cli.enable_server_certificate_verification(true);
  13133. // This should FAIL because:
  13134. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  13135. // 2. System certs should NOT be loaded when custom store is set
  13136. // If system certs WERE loaded, this would succeed
  13137. auto res = cli.Get("/");
  13138. ASSERT_FALSE(res);
  13139. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13140. }
  13141. // Same as above, but through the native store handle path. Regression test:
  13142. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  13143. // merged system certs into the user-provided store.
  13144. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  13145. std::string cert;
  13146. read_file(SERVER_CERT2_FILE, cert);
  13147. SSLClient cli("google.com");
  13148. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13149. cli.enable_server_certificate_verification(true);
  13150. auto res = cli.Get("/");
  13151. ASSERT_FALSE(res);
  13152. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13153. }
  13154. // A custom store set via the native handle must still verify a server whose
  13155. // cert it does contain.
  13156. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  13157. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13158. ASSERT_TRUE(svr.is_valid());
  13159. svr.Get("/test", [&](const Request &, Response &res) {
  13160. res.set_content("test", "text/plain");
  13161. });
  13162. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13163. auto se = detail::scope_exit([&] {
  13164. svr.stop();
  13165. t.join();
  13166. ASSERT_FALSE(svr.is_running());
  13167. });
  13168. svr.wait_until_ready();
  13169. SSLClient cli("127.0.0.1", PORT);
  13170. std::string cert;
  13171. read_file(SERVER_CERT2_FILE, cert);
  13172. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13173. cli.enable_server_certificate_verification(true);
  13174. cli.set_connection_timeout(30);
  13175. auto res = cli.Get("/test");
  13176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13177. ASSERT_EQ(StatusCode::OK_200, res->status);
  13178. }
  13179. // CA certs loaded through the universal Client must be transferred to the
  13180. // client created internally for following an HTTPS redirect. Regression test:
  13181. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  13182. // the CA data for redirect transfer.
  13183. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  13184. auto ssl_port = PORT + 1;
  13185. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13186. ASSERT_TRUE(ssl_svr1.is_valid());
  13187. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13188. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13189. "/index");
  13190. });
  13191. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13192. ASSERT_TRUE(ssl_svr2.is_valid());
  13193. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13194. res.set_content("test", "text/plain");
  13195. });
  13196. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13197. thread t2 =
  13198. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13199. auto se = detail::scope_exit([&] {
  13200. ssl_svr2.stop();
  13201. ssl_svr1.stop();
  13202. t2.join();
  13203. t.join();
  13204. ASSERT_FALSE(ssl_svr1.is_running());
  13205. });
  13206. ssl_svr1.wait_until_ready();
  13207. ssl_svr2.wait_until_ready();
  13208. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13209. std::string cert;
  13210. read_file(SERVER_CERT2_FILE, cert);
  13211. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13212. cli.enable_server_certificate_verification(true);
  13213. cli.set_follow_location(true);
  13214. cli.set_connection_timeout(30);
  13215. auto res = cli.Get("/index");
  13216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13217. ASSERT_EQ(StatusCode::OK_200, res->status);
  13218. }
  13219. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  13220. // so a host signed by a system CA verifies even though a custom CA is set
  13221. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  13222. std::string cert;
  13223. read_file(SERVER_CERT2_FILE, cert);
  13224. SSLClient cli("google.com");
  13225. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13226. cli.enable_system_ca(true);
  13227. cli.enable_server_certificate_verification(true);
  13228. auto res = cli.Get("/");
  13229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13230. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13231. }
  13232. // The custom CA remains effective when combined with the system CA
  13233. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  13234. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13235. ASSERT_TRUE(svr.is_valid());
  13236. svr.Get("/test", [&](const Request &, Response &res) {
  13237. res.set_content("test", "text/plain");
  13238. });
  13239. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13240. auto se = detail::scope_exit([&] {
  13241. svr.stop();
  13242. t.join();
  13243. ASSERT_FALSE(svr.is_running());
  13244. });
  13245. svr.wait_until_ready();
  13246. SSLClient cli("127.0.0.1", PORT);
  13247. std::string cert;
  13248. read_file(SERVER_CERT2_FILE, cert);
  13249. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13250. cli.enable_system_ca(true);
  13251. cli.enable_server_certificate_verification(true);
  13252. cli.set_connection_timeout(30);
  13253. auto res = cli.Get("/test");
  13254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13255. ASSERT_EQ(StatusCode::OK_200, res->status);
  13256. }
  13257. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  13258. // skip chain verification entirely (only the certificate identity was
  13259. // checked), so a server presenting an untrusted certificate with a matching
  13260. // IP SAN was accepted. The chain must be validated for IP hosts too.
  13261. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  13262. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13263. ASSERT_TRUE(svr.is_valid());
  13264. svr.Get("/test", [&](const Request &, Response &res) {
  13265. res.set_content("test", "text/plain");
  13266. });
  13267. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13268. auto se = detail::scope_exit([&] {
  13269. svr.stop();
  13270. t.join();
  13271. ASSERT_FALSE(svr.is_running());
  13272. });
  13273. svr.wait_until_ready();
  13274. SSLClient cli("127.0.0.1", PORT);
  13275. std::string cert;
  13276. // A trusted CA that did not sign the server certificate. The server cert
  13277. // (cert2) carries the matching IP SAN, so only chain validation can reject
  13278. // this connection.
  13279. read_file(CLIENT_CA_CERT_FILE, cert);
  13280. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13281. cli.enable_server_certificate_verification(true);
  13282. cli.set_connection_timeout(30);
  13283. auto res = cli.Get("/test");
  13284. ASSERT_FALSE(res);
  13285. }
  13286. // enable_system_ca(false) prevents system CA loading entirely
  13287. TEST(SSLClientTest, DisableSystemCa_Online) {
  13288. SSLClient cli("google.com");
  13289. cli.enable_system_ca(false);
  13290. cli.enable_server_certificate_verification(true);
  13291. auto res = cli.Get("/");
  13292. ASSERT_FALSE(res);
  13293. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  13294. // itself when the CA chain is empty
  13295. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13296. res.error() == Error::SSLConnection);
  13297. }
  13298. // The universal Client forwards enable_system_ca()
  13299. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  13300. std::string cert;
  13301. read_file(SERVER_CERT2_FILE, cert);
  13302. Client cli("https://google.com");
  13303. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13304. cli.enable_system_ca(true);
  13305. cli.enable_server_certificate_verification(true);
  13306. auto res = cli.Get("/");
  13307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13308. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13309. }
  13310. // The system CA policy must carry over to the client created internally for
  13311. // following a cross-host HTTPS redirect
  13312. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  13313. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13314. ASSERT_TRUE(svr.is_valid());
  13315. svr.Get("/index", [&](const Request &, Response &res) {
  13316. res.set_redirect("https://www.google.com/");
  13317. });
  13318. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13319. auto se = detail::scope_exit([&] {
  13320. svr.stop();
  13321. t.join();
  13322. ASSERT_FALSE(svr.is_running());
  13323. });
  13324. svr.wait_until_ready();
  13325. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13326. std::string cert;
  13327. read_file(SERVER_CERT2_FILE, cert);
  13328. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13329. cli.enable_system_ca(true);
  13330. cli.enable_server_certificate_verification(true);
  13331. cli.set_follow_location(true);
  13332. cli.set_connection_timeout(30);
  13333. // Receiving any response proves the redirect client completed the TLS
  13334. // handshake with a system-CA-signed host
  13335. auto res = cli.Get("/index");
  13336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13337. }
  13338. TEST(MultipartFormDataTest, LargeData) {
  13339. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13340. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  13341. const ContentReader &content_reader) {
  13342. if (req.is_multipart_form_data()) {
  13343. std::vector<FormData> items;
  13344. content_reader(
  13345. [&](const FormData &file) {
  13346. items.push_back(file);
  13347. return true;
  13348. },
  13349. [&](const char *data, size_t data_length) {
  13350. items.back().content.append(data, data_length);
  13351. return true;
  13352. });
  13353. EXPECT_TRUE(std::string(items[0].name) == "document");
  13354. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13355. EXPECT_TRUE(items[0].filename == "2MB_data");
  13356. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13357. EXPECT_TRUE(items[1].name == "hello");
  13358. EXPECT_TRUE(items[1].content == "world");
  13359. EXPECT_TRUE(items[1].filename == "");
  13360. EXPECT_TRUE(items[1].content_type == "");
  13361. } else {
  13362. std::string body;
  13363. content_reader([&](const char *data, size_t data_length) {
  13364. body.append(data, data_length);
  13365. return true;
  13366. });
  13367. }
  13368. });
  13369. auto port = svr.bind_to_any_port(HOST);
  13370. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13371. auto se = detail::scope_exit([&] {
  13372. svr.stop();
  13373. t.join();
  13374. ASSERT_FALSE(svr.is_running());
  13375. });
  13376. svr.wait_until_ready();
  13377. {
  13378. std::string data(1024 * 1024 * 2, '.');
  13379. std::stringstream buffer;
  13380. buffer << data;
  13381. SSLClient cli(HOST, port);
  13382. cli.enable_server_certificate_verification(false);
  13383. UploadFormDataItems items{
  13384. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13385. {"hello", "world", "", ""},
  13386. };
  13387. auto res = cli.Post("/post", items);
  13388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13389. ASSERT_EQ(StatusCode::OK_200, res->status);
  13390. }
  13391. }
  13392. TEST(MultipartFormDataTest, DataProviderItems) {
  13393. std::random_device seed_gen;
  13394. std::mt19937 random(seed_gen());
  13395. std::string rand1;
  13396. rand1.resize(1000);
  13397. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  13398. std::string rand2;
  13399. rand2.resize(3000);
  13400. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  13401. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13402. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  13403. const ContentReader &content_reader) {
  13404. ASSERT_FALSE(req.is_multipart_form_data());
  13405. std::string body;
  13406. content_reader([&](const char *data, size_t data_length) {
  13407. body.append(data, data_length);
  13408. return true;
  13409. });
  13410. EXPECT_EQ(body, "");
  13411. });
  13412. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  13413. const ContentReader &content_reader) {
  13414. ASSERT_TRUE(req.is_multipart_form_data());
  13415. std::vector<FormData> items;
  13416. content_reader(
  13417. [&](const FormData &file) {
  13418. items.push_back(file);
  13419. return true;
  13420. },
  13421. [&](const char *data, size_t data_length) {
  13422. items.back().content.append(data, data_length);
  13423. return true;
  13424. });
  13425. ASSERT_TRUE(items.size() == 2);
  13426. EXPECT_EQ(std::string(items[0].name), "name1");
  13427. EXPECT_EQ(items[0].content, "Testing123");
  13428. EXPECT_EQ(items[0].filename, "filename1");
  13429. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13430. EXPECT_EQ(items[1].name, "name2");
  13431. EXPECT_EQ(items[1].content, "Testing456");
  13432. EXPECT_EQ(items[1].filename, "");
  13433. EXPECT_EQ(items[1].content_type, "");
  13434. });
  13435. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  13436. const ContentReader &content_reader) {
  13437. ASSERT_TRUE(req.is_multipart_form_data());
  13438. std::vector<FormData> items;
  13439. content_reader(
  13440. [&](const FormData &file) {
  13441. items.push_back(file);
  13442. return true;
  13443. },
  13444. [&](const char *data, size_t data_length) {
  13445. items.back().content.append(data, data_length);
  13446. return true;
  13447. });
  13448. ASSERT_TRUE(items.size() == 2);
  13449. EXPECT_EQ(items[0].name, "name3");
  13450. EXPECT_EQ(items[0].content, rand1);
  13451. EXPECT_EQ(items[0].filename, "filename3");
  13452. EXPECT_EQ(items[0].content_type, "");
  13453. EXPECT_EQ(items[1].name, "name4");
  13454. EXPECT_EQ(items[1].content, rand2);
  13455. EXPECT_EQ(items[1].filename, "filename4");
  13456. EXPECT_EQ(items[1].content_type, "");
  13457. });
  13458. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  13459. const ContentReader &content_reader) {
  13460. ASSERT_TRUE(req.is_multipart_form_data());
  13461. std::vector<FormData> items;
  13462. content_reader(
  13463. [&](const FormData &file) {
  13464. items.push_back(file);
  13465. return true;
  13466. },
  13467. [&](const char *data, size_t data_length) {
  13468. items.back().content.append(data, data_length);
  13469. return true;
  13470. });
  13471. ASSERT_TRUE(items.size() == 4);
  13472. EXPECT_EQ(std::string(items[0].name), "name1");
  13473. EXPECT_EQ(items[0].content, "Testing123");
  13474. EXPECT_EQ(items[0].filename, "filename1");
  13475. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13476. EXPECT_EQ(items[1].name, "name2");
  13477. EXPECT_EQ(items[1].content, "Testing456");
  13478. EXPECT_EQ(items[1].filename, "");
  13479. EXPECT_EQ(items[1].content_type, "");
  13480. EXPECT_EQ(items[2].name, "name3");
  13481. EXPECT_EQ(items[2].content, rand1);
  13482. EXPECT_EQ(items[2].filename, "filename3");
  13483. EXPECT_EQ(items[2].content_type, "");
  13484. EXPECT_EQ(items[3].name, "name4");
  13485. EXPECT_EQ(items[3].content, rand2);
  13486. EXPECT_EQ(items[3].filename, "filename4");
  13487. EXPECT_EQ(items[3].content_type, "");
  13488. });
  13489. auto port = svr.bind_to_any_port("localhost");
  13490. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13491. auto se = detail::scope_exit([&] {
  13492. svr.stop();
  13493. t.join();
  13494. ASSERT_FALSE(svr.is_running());
  13495. });
  13496. svr.wait_until_ready();
  13497. {
  13498. SSLClient cli("localhost", port);
  13499. cli.enable_server_certificate_verification(false);
  13500. UploadFormDataItems items{
  13501. {"name1", "Testing123", "filename1", "application/octet-stream"},
  13502. {"name2", "Testing456", "", ""}, // not a file
  13503. };
  13504. {
  13505. auto res = cli.Post("/post-none", {}, {}, {});
  13506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13507. ASSERT_EQ(StatusCode::OK_200, res->status);
  13508. }
  13509. FormDataProviderItems providers;
  13510. {
  13511. auto res =
  13512. cli.Post("/post-items", {}, items, providers); // empty providers
  13513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13514. ASSERT_EQ(StatusCode::OK_200, res->status);
  13515. }
  13516. providers.push_back({"name3",
  13517. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13518. // test the offset is given correctly at each step
  13519. if (!offset)
  13520. sink.os.write(rand1.data(), 30);
  13521. else if (offset == 30)
  13522. sink.os.write(rand1.data() + 30, 300);
  13523. else if (offset == 330)
  13524. sink.os.write(rand1.data() + 330, 670);
  13525. else if (offset == rand1.size())
  13526. sink.done();
  13527. return true;
  13528. },
  13529. "filename3",
  13530. {}});
  13531. providers.push_back({"name4",
  13532. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13533. // test the offset is given correctly at each step
  13534. if (!offset)
  13535. sink.os.write(rand2.data(), 2000);
  13536. else if (offset == 2000)
  13537. sink.os.write(rand2.data() + 2000, 1);
  13538. else if (offset == 2001)
  13539. sink.os.write(rand2.data() + 2001, 999);
  13540. else if (offset == rand2.size())
  13541. sink.done();
  13542. return true;
  13543. },
  13544. "filename4",
  13545. {}});
  13546. {
  13547. auto res = cli.Post("/post-providers", {}, {}, providers);
  13548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13549. ASSERT_EQ(StatusCode::OK_200, res->status);
  13550. }
  13551. {
  13552. auto res = cli.Post("/post-both", {}, items, providers);
  13553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13554. ASSERT_EQ(StatusCode::OK_200, res->status);
  13555. }
  13556. }
  13557. }
  13558. TEST(MultipartFormDataTest, BadHeader) {
  13559. Server svr;
  13560. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13561. res.set_content("ok", "text/plain");
  13562. });
  13563. thread t = thread([&] { svr.listen(HOST, PORT); });
  13564. auto se = detail::scope_exit([&] {
  13565. svr.stop();
  13566. t.join();
  13567. ASSERT_FALSE(svr.is_running());
  13568. });
  13569. svr.wait_until_ready();
  13570. const std::string body =
  13571. "This is the preamble. It is to be ignored, though it\r\n"
  13572. "is a handy place for composition agents to include an\r\n"
  13573. "explanatory note to non-MIME conformant readers.\r\n"
  13574. "\r\n"
  13575. "\r\n"
  13576. "--simple boundary\r\n"
  13577. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13578. ": BAD...\r\n"
  13579. "\r\n"
  13580. "value1\r\n"
  13581. "--simple boundary\r\n"
  13582. "Content-Disposition: form-data; name=\"field2\"; "
  13583. "filename=\"example.txt\"\r\n"
  13584. "\r\n"
  13585. "value2\r\n"
  13586. "--simple boundary--\r\n"
  13587. "This is the epilogue. It is also to be ignored.\r\n";
  13588. std::string content_type =
  13589. R"(multipart/form-data; boundary="simple boundary")";
  13590. Client cli(HOST, PORT);
  13591. auto res = cli.Post("/post", body, content_type.c_str());
  13592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13593. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13594. }
  13595. TEST(MultipartFormDataTest, WithPreamble) {
  13596. Server svr;
  13597. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13598. res.set_content("ok", "text/plain");
  13599. });
  13600. thread t = thread([&] { svr.listen(HOST, PORT); });
  13601. auto se = detail::scope_exit([&] {
  13602. svr.stop();
  13603. t.join();
  13604. ASSERT_FALSE(svr.is_running());
  13605. });
  13606. svr.wait_until_ready();
  13607. const std::string body =
  13608. "This is the preamble. It is to be ignored, though it\r\n"
  13609. "is a handy place for composition agents to include an\r\n"
  13610. "explanatory note to non-MIME conformant readers.\r\n"
  13611. "\r\n"
  13612. "\r\n"
  13613. "--simple boundary\r\n"
  13614. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13615. "\r\n"
  13616. "value1\r\n"
  13617. "--simple boundary\r\n"
  13618. "Content-Disposition: form-data; name=\"field2\"; "
  13619. "filename=\"example.txt\"\r\n"
  13620. "\r\n"
  13621. "value2\r\n"
  13622. "--simple boundary--\r\n"
  13623. "This is the epilogue. It is also to be ignored.\r\n";
  13624. std::string content_type =
  13625. R"(multipart/form-data; boundary="simple boundary")";
  13626. Client cli(HOST, PORT);
  13627. auto res = cli.Post("/post", body, content_type.c_str());
  13628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13629. EXPECT_EQ(StatusCode::OK_200, res->status);
  13630. }
  13631. TEST(MultipartFormDataTest, PostCustomBoundary) {
  13632. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13633. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  13634. const ContentReader &content_reader) {
  13635. if (req.is_multipart_form_data()) {
  13636. std::vector<FormData> items;
  13637. content_reader(
  13638. [&](const FormData &file) {
  13639. items.push_back(file);
  13640. return true;
  13641. },
  13642. [&](const char *data, size_t data_length) {
  13643. items.back().content.append(data, data_length);
  13644. return true;
  13645. });
  13646. EXPECT_TRUE(std::string(items[0].name) == "document");
  13647. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13648. EXPECT_TRUE(items[0].filename == "2MB_data");
  13649. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13650. EXPECT_TRUE(items[1].name == "hello");
  13651. EXPECT_TRUE(items[1].content == "world");
  13652. EXPECT_TRUE(items[1].filename == "");
  13653. EXPECT_TRUE(items[1].content_type == "");
  13654. } else {
  13655. std::string body;
  13656. content_reader([&](const char *data, size_t data_length) {
  13657. body.append(data, data_length);
  13658. return true;
  13659. });
  13660. }
  13661. });
  13662. auto port = svr.bind_to_any_port("localhost");
  13663. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13664. auto se = detail::scope_exit([&] {
  13665. svr.stop();
  13666. t.join();
  13667. ASSERT_FALSE(svr.is_running());
  13668. });
  13669. svr.wait_until_ready();
  13670. {
  13671. std::string data(1024 * 1024 * 2, '.');
  13672. std::stringstream buffer;
  13673. buffer << data;
  13674. SSLClient cli("localhost", port);
  13675. cli.enable_server_certificate_verification(false);
  13676. UploadFormDataItems items{
  13677. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13678. {"hello", "world", "", ""},
  13679. };
  13680. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  13681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13682. ASSERT_EQ(StatusCode::OK_200, res->status);
  13683. }
  13684. }
  13685. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  13686. std::string data(1024 * 1024 * 2, '&');
  13687. std::stringstream buffer;
  13688. buffer << data;
  13689. Client cli("https://localhost:8080");
  13690. UploadFormDataItems items{
  13691. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13692. {"hello", "world", "", ""},
  13693. };
  13694. for (const char &c : " \t\r\n") {
  13695. auto res =
  13696. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  13697. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13698. ASSERT_FALSE(res);
  13699. }
  13700. }
  13701. TEST(MultipartFormDataTest, PutFormData) {
  13702. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13703. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  13704. const ContentReader &content_reader) {
  13705. if (req.is_multipart_form_data()) {
  13706. std::vector<FormData> items;
  13707. content_reader(
  13708. [&](const FormData &file) {
  13709. items.push_back(file);
  13710. return true;
  13711. },
  13712. [&](const char *data, size_t data_length) {
  13713. items.back().content.append(data, data_length);
  13714. return true;
  13715. });
  13716. EXPECT_TRUE(std::string(items[0].name) == "document");
  13717. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13718. EXPECT_TRUE(items[0].filename == "2MB_data");
  13719. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13720. EXPECT_TRUE(items[1].name == "hello");
  13721. EXPECT_TRUE(items[1].content == "world");
  13722. EXPECT_TRUE(items[1].filename == "");
  13723. EXPECT_TRUE(items[1].content_type == "");
  13724. } else {
  13725. std::string body;
  13726. content_reader([&](const char *data, size_t data_length) {
  13727. body.append(data, data_length);
  13728. return true;
  13729. });
  13730. }
  13731. });
  13732. auto port = svr.bind_to_any_port("localhost");
  13733. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13734. auto se = detail::scope_exit([&] {
  13735. svr.stop();
  13736. t.join();
  13737. ASSERT_FALSE(svr.is_running());
  13738. });
  13739. svr.wait_until_ready();
  13740. {
  13741. std::string data(1024 * 1024 * 2, '&');
  13742. std::stringstream buffer;
  13743. buffer << data;
  13744. SSLClient cli("localhost", port);
  13745. cli.enable_server_certificate_verification(false);
  13746. UploadFormDataItems items{
  13747. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13748. {"hello", "world", "", ""},
  13749. };
  13750. auto res = cli.Put("/put", items);
  13751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13752. ASSERT_EQ(StatusCode::OK_200, res->status);
  13753. }
  13754. }
  13755. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  13756. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13757. svr.Put("/put_customboundary",
  13758. [&](const Request &req, const Response & /*res*/,
  13759. const ContentReader &content_reader) {
  13760. if (req.is_multipart_form_data()) {
  13761. std::vector<FormData> items;
  13762. content_reader(
  13763. [&](const FormData &file) {
  13764. items.push_back(file);
  13765. return true;
  13766. },
  13767. [&](const char *data, size_t data_length) {
  13768. items.back().content.append(data, data_length);
  13769. return true;
  13770. });
  13771. EXPECT_TRUE(std::string(items[0].name) == "document");
  13772. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13773. EXPECT_TRUE(items[0].filename == "2MB_data");
  13774. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13775. EXPECT_TRUE(items[1].name == "hello");
  13776. EXPECT_TRUE(items[1].content == "world");
  13777. EXPECT_TRUE(items[1].filename == "");
  13778. EXPECT_TRUE(items[1].content_type == "");
  13779. } else {
  13780. std::string body;
  13781. content_reader([&](const char *data, size_t data_length) {
  13782. body.append(data, data_length);
  13783. return true;
  13784. });
  13785. }
  13786. });
  13787. auto port = svr.bind_to_any_port("localhost");
  13788. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13789. auto se = detail::scope_exit([&] {
  13790. svr.stop();
  13791. t.join();
  13792. ASSERT_FALSE(svr.is_running());
  13793. });
  13794. svr.wait_until_ready();
  13795. {
  13796. std::string data(1024 * 1024 * 2, '&');
  13797. std::stringstream buffer;
  13798. buffer << data;
  13799. SSLClient cli("localhost", port);
  13800. cli.enable_server_certificate_verification(false);
  13801. UploadFormDataItems items{
  13802. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13803. {"hello", "world", "", ""},
  13804. };
  13805. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  13806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13807. ASSERT_EQ(StatusCode::OK_200, res->status);
  13808. }
  13809. }
  13810. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  13811. std::string data(1024 * 1024 * 2, '&');
  13812. std::stringstream buffer;
  13813. buffer << data;
  13814. Client cli("https://localhost:8080");
  13815. cli.enable_server_certificate_verification(false);
  13816. UploadFormDataItems items{
  13817. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13818. {"hello", "world", "", ""},
  13819. };
  13820. for (const char &c : " \t\r\n") {
  13821. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  13822. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13823. ASSERT_FALSE(res);
  13824. }
  13825. }
  13826. TEST(MultipartFormDataTest, AlternateFilename) {
  13827. auto handled = false;
  13828. Server svr;
  13829. svr.Post("/test", [&](const Request &req, Response &res) {
  13830. ASSERT_EQ(2u, req.form.files.size());
  13831. ASSERT_EQ(1u, req.form.fields.size());
  13832. // Test files
  13833. const auto &file1 = req.form.get_file("file1");
  13834. ASSERT_EQ("file1", file1.name);
  13835. ASSERT_EQ("A.txt", file1.filename);
  13836. ASSERT_EQ("text/plain", file1.content_type);
  13837. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  13838. const auto &file2 = req.form.get_file("file2");
  13839. ASSERT_EQ("file2", file2.name);
  13840. ASSERT_EQ("a.html", file2.filename);
  13841. ASSERT_EQ("text/html", file2.content_type);
  13842. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  13843. file2.content);
  13844. // Test text field
  13845. const auto &text = req.form.get_field("text");
  13846. ASSERT_EQ("text default", text);
  13847. res.set_content("ok", "text/plain");
  13848. handled = true;
  13849. });
  13850. thread t = thread([&] { svr.listen(HOST, PORT); });
  13851. auto se = detail::scope_exit([&] {
  13852. svr.stop();
  13853. t.join();
  13854. ASSERT_FALSE(svr.is_running());
  13855. ASSERT_TRUE(handled);
  13856. });
  13857. svr.wait_until_ready();
  13858. auto req = "POST /test HTTP/1.1\r\n"
  13859. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13860. "Content-Length: 399\r\n"
  13861. "\r\n"
  13862. "----------\r\n"
  13863. "Content-Disposition: form-data; name=\"text\"\r\n"
  13864. "\r\n"
  13865. "text default\r\n"
  13866. "----------\r\n"
  13867. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  13868. "filename=\"a.txt\"; name=\"file1\"\r\n"
  13869. "Content-Type: text/plain\r\n"
  13870. "\r\n"
  13871. "Content of a.txt.\r\n"
  13872. "\r\n"
  13873. "----------\r\n"
  13874. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  13875. "\"a.html\"\r\n"
  13876. "Content-Type: text/html\r\n"
  13877. "\r\n"
  13878. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  13879. "\r\n"
  13880. "------------\r\n";
  13881. ASSERT_TRUE(send_request(1, req));
  13882. }
  13883. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  13884. auto handled = false;
  13885. Server svr;
  13886. svr.Post("/test", [&](const Request &req, Response &res) {
  13887. // Case-insensitive "utf-8''" prefix with a long value
  13888. const auto &file = req.form.get_file("file1");
  13889. ASSERT_EQ("file1", file.name);
  13890. // 8000 chars exercises both the Content-Disposition parser and the
  13891. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  13892. // Prior to the fix, std::regex_match on this header would cause O(N)
  13893. // stack recursion in libstdc++, leading to SIGSEGV.
  13894. std::string expected_filename(8000, 'A');
  13895. ASSERT_EQ(expected_filename, file.filename);
  13896. res.set_content("ok", "text/plain");
  13897. handled = true;
  13898. });
  13899. thread t = thread([&] { svr.listen(HOST, PORT); });
  13900. auto se = detail::scope_exit([&] {
  13901. svr.stop();
  13902. t.join();
  13903. ASSERT_FALSE(svr.is_running());
  13904. ASSERT_TRUE(handled);
  13905. });
  13906. svr.wait_until_ready();
  13907. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  13908. // Regression test for GHSA-qq6v-r583-3h69
  13909. std::string long_filename(8000, 'A');
  13910. std::string body = "----------\r\n"
  13911. "Content-Disposition: form-data; name=\"file1\"; "
  13912. "filename*=\"Utf-8''" +
  13913. long_filename +
  13914. "\"\r\n"
  13915. "\r\n"
  13916. "hello\r\n"
  13917. "------------\r\n";
  13918. auto req = "POST /test HTTP/1.1\r\n"
  13919. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13920. "Content-Length: " +
  13921. std::to_string(body.size()) + "\r\n\r\n" + body;
  13922. ASSERT_TRUE(send_request(1, req));
  13923. }
  13924. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  13925. auto handled = false;
  13926. Server svr;
  13927. svr.Post("/test", [&](const Request &req, Response &) {
  13928. ASSERT_EQ(2u, req.form.fields.size());
  13929. const auto &text1 = req.form.get_field("text1");
  13930. ASSERT_EQ("text1", text1);
  13931. const auto &text2 = req.form.get_field("text2");
  13932. ASSERT_EQ("text2", text2);
  13933. handled = true;
  13934. });
  13935. thread t = thread([&] { svr.listen(HOST, PORT); });
  13936. auto se = detail::scope_exit([&] {
  13937. svr.stop();
  13938. t.join();
  13939. ASSERT_FALSE(svr.is_running());
  13940. ASSERT_TRUE(handled);
  13941. });
  13942. svr.wait_until_ready();
  13943. auto req = "POST /test HTTP/1.1\r\n"
  13944. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13945. "Content-Length: 146\r\n"
  13946. "\r\n----------\r\n"
  13947. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13948. "\r\n"
  13949. "text1"
  13950. "\r\n----------\r\n"
  13951. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13952. "\r\n"
  13953. "text2"
  13954. "\r\n------------";
  13955. std::string response;
  13956. ASSERT_TRUE(send_request(1, req, &response));
  13957. ASSERT_EQ("200", response.substr(9, 3));
  13958. }
  13959. TEST(MultipartFormDataTest, ContentLength) {
  13960. auto handled = false;
  13961. Server svr;
  13962. svr.Post("/test", [&](const Request &req, Response &) {
  13963. ASSERT_EQ(2u, req.form.fields.size());
  13964. const auto &text1 = req.form.get_field("text1");
  13965. ASSERT_EQ("text1", text1);
  13966. const auto &text2 = req.form.get_field("text2");
  13967. ASSERT_EQ("text2", text2);
  13968. handled = true;
  13969. });
  13970. thread t = thread([&] { svr.listen(HOST, PORT); });
  13971. auto se = detail::scope_exit([&] {
  13972. svr.stop();
  13973. t.join();
  13974. ASSERT_FALSE(svr.is_running());
  13975. ASSERT_TRUE(handled);
  13976. });
  13977. svr.wait_until_ready();
  13978. auto req = "POST /test HTTP/1.1\r\n"
  13979. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13980. "Content-Length: 167\r\n"
  13981. "\r\n----------\r\n"
  13982. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13983. "Content-Length: 5\r\n"
  13984. "\r\n"
  13985. "text1"
  13986. "\r\n----------\r\n"
  13987. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13988. "\r\n"
  13989. "text2"
  13990. "\r\n------------\r\n";
  13991. std::string response;
  13992. ASSERT_TRUE(send_request(1, req, &response));
  13993. ASSERT_EQ("200", response.substr(9, 3));
  13994. }
  13995. TEST(MultipartFormDataTest, AccessPartHeaders) {
  13996. auto handled = false;
  13997. Server svr;
  13998. svr.Post("/test", [&](const Request &req, Response &) {
  13999. ASSERT_EQ(2u, req.form.fields.size());
  14000. const auto &text1 = req.form.get_field("text1");
  14001. ASSERT_EQ("text1", text1);
  14002. // TODO: Add header access for text fields if needed
  14003. const auto &text2 = req.form.get_field("text2");
  14004. ASSERT_EQ("text2", text2);
  14005. // TODO: Header access for text fields needs to be implemented
  14006. // auto &headers = it->second.headers;
  14007. // ASSERT_EQ(3U, headers.size());
  14008. // auto custom_header = headers.find("x-whatever");
  14009. // ASSERT_TRUE(custom_header != headers.end());
  14010. // ASSERT_NE("customvalue", custom_header->second);
  14011. // ASSERT_EQ("CustomValue", custom_header->second);
  14012. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14013. handled = true;
  14014. });
  14015. thread t = thread([&] { svr.listen(HOST, PORT); });
  14016. auto se = detail::scope_exit([&] {
  14017. svr.stop();
  14018. t.join();
  14019. ASSERT_FALSE(svr.is_running());
  14020. ASSERT_TRUE(handled);
  14021. });
  14022. svr.wait_until_ready();
  14023. auto req = "POST /test HTTP/1.1\r\n"
  14024. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14025. "Content-Length: 232\r\n"
  14026. "\r\n----------\r\n"
  14027. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14028. "Content-Length: 5\r\n"
  14029. "X-Test: 1\r\n"
  14030. "\r\n"
  14031. "text1"
  14032. "\r\n----------\r\n"
  14033. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14034. "Content-Type: text/plain\r\n"
  14035. "X-Whatever: CustomValue\r\n"
  14036. "\r\n"
  14037. "text2"
  14038. "\r\n------------\r\n"
  14039. "That should be disregarded. Not even read";
  14040. std::string response;
  14041. ASSERT_TRUE(send_request(1, req, &response));
  14042. ASSERT_EQ("200", response.substr(9, 3));
  14043. }
  14044. TEST(MultipartFormDataTest, LargeHeader) {
  14045. auto handled = false;
  14046. Server svr;
  14047. svr.Post("/test", [&](const Request &req, Response &) {
  14048. ASSERT_EQ(1u, req.form.fields.size());
  14049. const auto &text = req.form.get_field("name1");
  14050. ASSERT_EQ("text1", text);
  14051. handled = true;
  14052. });
  14053. thread t = thread([&] { svr.listen(HOST, PORT); });
  14054. auto se = detail::scope_exit([&] {
  14055. svr.stop();
  14056. t.join();
  14057. ASSERT_FALSE(svr.is_running());
  14058. ASSERT_TRUE(handled);
  14059. });
  14060. svr.wait_until_ready();
  14061. auto boundary = std::string("cpp-httplib-multipart-data");
  14062. std::string content = "--" + boundary +
  14063. "\r\n"
  14064. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14065. "\r\n"
  14066. "text1\r\n"
  14067. "--" +
  14068. boundary + "--\r\n";
  14069. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14070. "Content-Type: multipart/form-data;boundary=" +
  14071. boundary +
  14072. "\r\n"
  14073. "Content-Length: " +
  14074. std::to_string(content.size()) +
  14075. "\r\n"
  14076. "Dummy-Header: ";
  14077. std::string header_suffix = "\r\n"
  14078. "\r\n";
  14079. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14080. size_t header_dummy_size =
  14081. read_buff_size -
  14082. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14083. auto header_dummy = std::string(header_dummy_size, '@');
  14084. auto req = header_prefix + header_dummy + header_suffix + content;
  14085. std::string response;
  14086. ASSERT_TRUE(send_request(1, req, &response));
  14087. ASSERT_EQ("200", response.substr(9, 3));
  14088. }
  14089. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14090. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14091. // (not chunked Transfer-Encoding) after the streaming refactor.
  14092. auto handled = false;
  14093. Server svr;
  14094. svr.Post("/upload", [&](const Request &req, Response &res) {
  14095. auto cl_it = req.headers.find("Content-Length");
  14096. EXPECT_TRUE(cl_it != req.headers.end());
  14097. auto te_it = req.headers.find("Transfer-Encoding");
  14098. EXPECT_TRUE(te_it == req.headers.end());
  14099. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  14100. res.set_content("ok", "text/plain");
  14101. handled = true;
  14102. });
  14103. auto port = svr.bind_to_any_port(HOST);
  14104. auto t = thread([&] { svr.listen_after_bind(); });
  14105. auto se = detail::scope_exit([&] {
  14106. svr.stop();
  14107. t.join();
  14108. ASSERT_FALSE(svr.is_running());
  14109. ASSERT_TRUE(handled);
  14110. });
  14111. svr.wait_until_ready();
  14112. UploadFormDataItems items = {
  14113. {"field1", "hello", "", "text/plain"},
  14114. {"file1", "world", "test.txt", "application/octet-stream"},
  14115. };
  14116. Client cli(HOST, port);
  14117. auto res = cli.Post("/upload", {}, items);
  14118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14119. EXPECT_EQ(StatusCode::OK_200, res->status);
  14120. }
  14121. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14122. // Verify that make_multipart_content_provider coalesces many small segments
  14123. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14124. constexpr size_t kItemCount = 1000;
  14125. UploadFormDataItems items;
  14126. items.reserve(kItemCount);
  14127. for (size_t i = 0; i < kItemCount; i++) {
  14128. items.push_back(
  14129. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14130. }
  14131. const std::string boundary = "----test-boundary";
  14132. auto content_length = detail::get_multipart_content_length(items, boundary);
  14133. auto provider = detail::make_multipart_content_provider(items, boundary);
  14134. // Drive the provider the same way write_content_with_progress does
  14135. size_t write_count = 0;
  14136. size_t total_bytes = 0;
  14137. DataSink sink;
  14138. size_t offset = 0;
  14139. sink.write = [&](const char *d, size_t l) -> bool {
  14140. (void)d;
  14141. write_count++;
  14142. total_bytes += l;
  14143. offset += l;
  14144. return true;
  14145. };
  14146. sink.is_writable = []() -> bool { return true; };
  14147. while (offset < content_length) {
  14148. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  14149. }
  14150. EXPECT_EQ(content_length, total_bytes);
  14151. // The total number of segments is 3 * kItemCount + 1 = 3001.
  14152. // With buffering into 64KB blocks, write_count should be much smaller.
  14153. auto segment_count = 3 * kItemCount + 1;
  14154. EXPECT_LT(write_count, segment_count / 10);
  14155. }
  14156. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  14157. // Integration test: send many UploadFormDataItems and verify the server
  14158. // receives all of them correctly (#2410).
  14159. constexpr size_t kItemCount = 500;
  14160. auto handled = false;
  14161. Server svr;
  14162. svr.Post("/upload", [&](const Request &req, Response &res) {
  14163. EXPECT_EQ(kItemCount, req.form.fields.size());
  14164. for (size_t i = 0; i < kItemCount; i++) {
  14165. auto key = "field" + std::to_string(i);
  14166. auto val = "value" + std::to_string(i);
  14167. auto it = req.form.fields.find(key);
  14168. if (it != req.form.fields.end()) {
  14169. EXPECT_EQ(val, it->second.content);
  14170. } else {
  14171. ADD_FAILURE() << "Missing field: " << key;
  14172. }
  14173. }
  14174. res.set_content("ok", "text/plain");
  14175. handled = true;
  14176. });
  14177. auto port = svr.bind_to_any_port(HOST);
  14178. auto t = thread([&] { svr.listen_after_bind(); });
  14179. auto se = detail::scope_exit([&] {
  14180. svr.stop();
  14181. t.join();
  14182. ASSERT_FALSE(svr.is_running());
  14183. ASSERT_TRUE(handled);
  14184. });
  14185. svr.wait_until_ready();
  14186. UploadFormDataItems items;
  14187. items.reserve(kItemCount);
  14188. for (size_t i = 0; i < kItemCount; i++) {
  14189. items.push_back(
  14190. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14191. }
  14192. Client cli(HOST, port);
  14193. auto res = cli.Post("/upload", items);
  14194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14195. EXPECT_EQ(StatusCode::OK_200, res->status);
  14196. }
  14197. TEST(MultipartFormDataTest, MakeFileProvider) {
  14198. // Verify make_file_provider sends a file's contents correctly.
  14199. const std::string file_content(4096, 'Z');
  14200. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  14201. {
  14202. std::ofstream ofs(tmp_path, std::ios::binary);
  14203. ofs.write(file_content.data(),
  14204. static_cast<std::streamsize>(file_content.size()));
  14205. }
  14206. auto handled = false;
  14207. Server svr;
  14208. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  14209. const ContentReader &content_reader) {
  14210. ASSERT_TRUE(req.is_multipart_form_data());
  14211. std::vector<FormData> items;
  14212. content_reader(
  14213. [&](const FormData &file) {
  14214. items.push_back(file);
  14215. return true;
  14216. },
  14217. [&](const char *data, size_t data_length) {
  14218. items.back().content.append(data, data_length);
  14219. return true;
  14220. });
  14221. ASSERT_EQ(1u, items.size());
  14222. EXPECT_EQ("myfile", items[0].name);
  14223. EXPECT_EQ("data.bin", items[0].filename);
  14224. EXPECT_EQ("application/octet-stream", items[0].content_type);
  14225. EXPECT_EQ(file_content, items[0].content);
  14226. handled = true;
  14227. });
  14228. auto port = svr.bind_to_any_port(HOST);
  14229. auto t = thread([&] { svr.listen_after_bind(); });
  14230. auto se = detail::scope_exit([&] {
  14231. svr.stop();
  14232. t.join();
  14233. ASSERT_FALSE(svr.is_running());
  14234. ASSERT_TRUE(handled);
  14235. std::remove(tmp_path.c_str());
  14236. });
  14237. svr.wait_until_ready();
  14238. FormDataProviderItems providers;
  14239. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  14240. "application/octet-stream"));
  14241. Client cli(HOST, port);
  14242. auto res = cli.Post("/upload", {}, {}, providers);
  14243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14244. EXPECT_EQ(StatusCode::OK_200, res->status);
  14245. }
  14246. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  14247. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  14248. // (100) headers is rejected with a 400 Bad Request response.
  14249. Server svr;
  14250. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14251. res.set_content("ok", "text/plain");
  14252. });
  14253. thread t = thread([&] { svr.listen(HOST, PORT); });
  14254. auto se = detail::scope_exit([&] {
  14255. svr.stop();
  14256. t.join();
  14257. ASSERT_FALSE(svr.is_running());
  14258. });
  14259. svr.wait_until_ready();
  14260. // Build a multipart part with 101 custom headers (exceeding
  14261. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  14262. std::stringstream body;
  14263. body << "--simpleboundary\r\n"
  14264. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  14265. for (int i = 0; i < 101; i++) {
  14266. body << "X-Custom-Header-" << i << ": value\r\n";
  14267. }
  14268. body << "\r\n"
  14269. << "value1\r\n"
  14270. << "--simpleboundary--\r\n";
  14271. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  14272. Client cli(HOST, PORT);
  14273. auto res = cli.Post("/post", body.str(), content_type.c_str());
  14274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14275. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14276. }
  14277. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  14278. // A body that never contains the declared boundary must not be accumulated
  14279. // while the parser waits for it. Buffering it would also make every read
  14280. // rescan everything seen so far, which is quadratic in the body size.
  14281. Server svr;
  14282. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14283. res.set_content("ok", "text/plain");
  14284. });
  14285. auto port = svr.bind_to_any_port(HOST);
  14286. thread t = thread([&] { svr.listen_after_bind(); });
  14287. auto se = detail::scope_exit([&] {
  14288. svr.stop();
  14289. t.join();
  14290. ASSERT_FALSE(svr.is_running());
  14291. });
  14292. svr.wait_until_ready();
  14293. Client cli(HOST, port);
  14294. cli.set_read_timeout(60, 0);
  14295. cli.set_write_timeout(60, 0);
  14296. // '-' is the worst case: it matches the first character of the boundary, so
  14297. // every position has to be checked against it.
  14298. auto post_dashes = [&](size_t size) {
  14299. const std::string body(size, '-');
  14300. auto start = std::chrono::steady_clock::now();
  14301. auto res =
  14302. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  14303. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  14304. std::chrono::steady_clock::now() - start)
  14305. .count();
  14306. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14307. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  14308. return ms;
  14309. };
  14310. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  14311. // Windows.
  14312. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  14313. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  14314. // Comparing the two sizes rather than checking an absolute duration keeps
  14315. // this meaningful across build types and CI load, both of which move the
  14316. // absolute numbers by more than an order of magnitude. Four times the bytes
  14317. // costs about four times the time when parsing is linear, and about sixteen
  14318. // times when the body is buffered and rescanned.
  14319. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  14320. EXPECT_LT(ms_16mb, ms_4mb * 10)
  14321. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  14322. << "ms, which suggests the body is being buffered and rescanned";
  14323. }
  14324. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  14325. // A boundary can only be followed by CRLF or by "--", so anything else is
  14326. // malformed no matter what comes next. The parser must say so right away
  14327. // instead of buffering the rest of the declared body.
  14328. Server svr;
  14329. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14330. res.set_content("ok", "text/plain");
  14331. });
  14332. auto port = svr.bind_to_any_port(HOST);
  14333. thread t = thread([&] { svr.listen_after_bind(); });
  14334. auto se = detail::scope_exit([&] {
  14335. svr.stop();
  14336. t.join();
  14337. ASSERT_FALSE(svr.is_running());
  14338. });
  14339. svr.wait_until_ready();
  14340. // Announce a 1 MB body but send only the malformed prefix. A parser that
  14341. // buffers instead of failing would still be waiting for the remaining bytes.
  14342. const std::string body = "--zzzz\r\n"
  14343. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14344. "\r\n"
  14345. "text1"
  14346. "\r\n--zzzzXX";
  14347. const std::string req = "POST /post HTTP/1.1\r\n"
  14348. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14349. "Content-Length: 1048576\r\n"
  14350. "\r\n" +
  14351. body;
  14352. std::string response;
  14353. ASSERT_TRUE(send_request(3, req, &response, port));
  14354. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  14355. EXPECT_EQ("400", response.substr(9, 3));
  14356. }
  14357. // Posts a multipart body split into two writes, so that the server sees the
  14358. // split at whatever offset the caller chose, and expects the single "text1"
  14359. // field to come through.
  14360. static void expect_split_multipart_ok(const std::string &body1,
  14361. const std::string &body2) {
  14362. auto handled = false;
  14363. Server svr;
  14364. svr.Post("/post", [&](const Request &req, Response &) {
  14365. EXPECT_EQ(1u, req.form.fields.size());
  14366. EXPECT_EQ("text1", req.form.get_field("text1"));
  14367. handled = true;
  14368. });
  14369. auto port = svr.bind_to_any_port(HOST);
  14370. thread t = thread([&] { svr.listen_after_bind(); });
  14371. auto se = detail::scope_exit([&] {
  14372. svr.stop();
  14373. t.join();
  14374. ASSERT_FALSE(svr.is_running());
  14375. ASSERT_TRUE(handled);
  14376. });
  14377. svr.wait_until_ready();
  14378. // "Connection: close" makes the server close once it has answered, so the
  14379. // response drain ends immediately instead of idling until the read timeout.
  14380. const std::string head =
  14381. "POST /post HTTP/1.1\r\n"
  14382. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14383. "Connection: close\r\n"
  14384. "Content-Length: " +
  14385. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  14386. std::string response;
  14387. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  14388. ASSERT_GE(response.size(), 12u) << "no response";
  14389. EXPECT_EQ("200", response.substr(9, 3));
  14390. }
  14391. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  14392. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  14393. // ignored, including when it does not arrive in the same read as the
  14394. // close-delimiter itself.
  14395. expect_split_multipart_ok("--zzzz\r\n"
  14396. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14397. "\r\n"
  14398. "text1"
  14399. "\r\n--zzzz--",
  14400. "\r\nthis epilogue must be ignored\r\n");
  14401. }
  14402. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  14403. // The initial boundary may be preceded by a preamble of any length and may
  14404. // straddle a read boundary. Discarding data while waiting for it must not
  14405. // throw away a partial boundary sitting at the end of the buffer.
  14406. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  14407. "zz\r\n"
  14408. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14409. "\r\n"
  14410. "text1"
  14411. "\r\n--zzzz--\r\n");
  14412. }
  14413. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  14414. // The received boundary was only checked for being non-empty, so it could be
  14415. // as long as a header is allowed to be. The parser scans the body for
  14416. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  14417. // costs a nearly full comparison at nearly every position, making the
  14418. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  14419. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  14420. Server svr;
  14421. svr.Post("/post", [](const Request &req, Response &res) {
  14422. EXPECT_EQ(1u, req.form.fields.size());
  14423. EXPECT_EQ("text1", req.form.get_field("text1"));
  14424. res.set_content("ok", "text/plain");
  14425. });
  14426. auto port = svr.bind_to_any_port(HOST);
  14427. thread t = thread([&] { svr.listen_after_bind(); });
  14428. auto se = detail::scope_exit([&] {
  14429. svr.stop();
  14430. t.join();
  14431. ASSERT_FALSE(svr.is_running());
  14432. });
  14433. svr.wait_until_ready();
  14434. Client cli(HOST, port);
  14435. auto post_with_boundary_of_length = [&](size_t len) {
  14436. const std::string boundary(len, 'a');
  14437. const std::string body =
  14438. "--" + boundary +
  14439. "\r\n"
  14440. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14441. "\r\n"
  14442. "text1"
  14443. "\r\n--" +
  14444. boundary + "--\r\n";
  14445. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  14446. };
  14447. auto res = post_with_boundary_of_length(70);
  14448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14449. EXPECT_EQ(StatusCode::OK_200, res->status);
  14450. res = post_with_boundary_of_length(71);
  14451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14452. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14453. }
  14454. TEST(MakeFileBodyTest, Basic) {
  14455. const std::string file_content(4096, 'Z');
  14456. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  14457. {
  14458. std::ofstream ofs(tmp_path, std::ios::binary);
  14459. ofs.write(file_content.data(),
  14460. static_cast<std::streamsize>(file_content.size()));
  14461. }
  14462. auto handled = false;
  14463. Server svr;
  14464. svr.Post("/upload", [&](const Request &req, Response &res) {
  14465. EXPECT_EQ(file_content, req.body);
  14466. handled = true;
  14467. res.status = StatusCode::OK_200;
  14468. });
  14469. auto port = svr.bind_to_any_port(HOST);
  14470. auto t = thread([&] { svr.listen_after_bind(); });
  14471. auto se = detail::scope_exit([&] {
  14472. svr.stop();
  14473. t.join();
  14474. ASSERT_FALSE(svr.is_running());
  14475. ASSERT_TRUE(handled);
  14476. std::remove(tmp_path.c_str());
  14477. });
  14478. svr.wait_until_ready();
  14479. auto fb = make_file_body(tmp_path);
  14480. ASSERT_GT(fb.first, 0u);
  14481. Client cli(HOST, port);
  14482. auto res =
  14483. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  14484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14485. EXPECT_EQ(StatusCode::OK_200, res->status);
  14486. }
  14487. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  14488. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  14489. {
  14490. std::ofstream ofs(path, std::ios::binary);
  14491. const std::string content(100, 'A');
  14492. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14493. }
  14494. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14495. auto body = make_file_body(path);
  14496. ASSERT_EQ(100u, body.first);
  14497. ASSERT_TRUE(static_cast<bool>(body.second));
  14498. // Rewritten shorter after its length was measured - and, on a server, after
  14499. // that length has already gone out as Content-Length.
  14500. {
  14501. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  14502. const std::string content(10, 'A');
  14503. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14504. }
  14505. std::string written;
  14506. DataSink sink;
  14507. sink.write = [&](const char *d, size_t l) {
  14508. written.append(d, l);
  14509. return true;
  14510. };
  14511. // The provider has to report failure. write_content_with_progress() advances
  14512. // its offset only by what was written, so a provider that returns true
  14513. // without completing the length it promised is called again straight away,
  14514. // and again.
  14515. EXPECT_FALSE(body.second(0, body.first, sink));
  14516. EXPECT_EQ(std::string(10, 'A'), written);
  14517. }
  14518. TEST(MakeFileBodyTest, WholeFileIsSent) {
  14519. const std::string path = "./httplib_test_make_file_body_whole.bin";
  14520. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  14521. {
  14522. std::ofstream ofs(path, std::ios::binary);
  14523. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14524. }
  14525. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14526. auto body = make_file_body(path);
  14527. ASSERT_EQ(content.size(), body.first);
  14528. ASSERT_TRUE(static_cast<bool>(body.second));
  14529. std::string written;
  14530. DataSink sink;
  14531. sink.write = [&](const char *d, size_t l) {
  14532. written.append(d, l);
  14533. return true;
  14534. };
  14535. EXPECT_TRUE(body.second(0, body.first, sink));
  14536. EXPECT_EQ(content, written);
  14537. }
  14538. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  14539. static constexpr unsigned int number_of_tasks{1000000};
  14540. std::atomic_uint count{0};
  14541. std::unique_ptr<TaskQueue> task_queue{
  14542. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  14543. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14544. auto queued = task_queue->enqueue(
  14545. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  14546. EXPECT_TRUE(queued);
  14547. }
  14548. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14549. task_queue->shutdown();
  14550. #else
  14551. EXPECT_NO_THROW(task_queue->shutdown());
  14552. #endif
  14553. EXPECT_EQ(number_of_tasks, count.load());
  14554. }
  14555. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  14556. static constexpr unsigned int number_of_tasks{1000000};
  14557. static constexpr unsigned int qlimit{2};
  14558. unsigned int queued_count{0};
  14559. std::atomic_uint count{0};
  14560. std::unique_ptr<TaskQueue> task_queue{
  14561. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  14562. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14563. if (task_queue->enqueue(
  14564. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  14565. queued_count++;
  14566. }
  14567. }
  14568. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14569. task_queue->shutdown();
  14570. #else
  14571. EXPECT_NO_THROW(task_queue->shutdown());
  14572. #endif
  14573. EXPECT_EQ(queued_count, count.load());
  14574. EXPECT_TRUE(queued_count <= number_of_tasks);
  14575. EXPECT_TRUE(queued_count >= qlimit);
  14576. }
  14577. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  14578. // Use a short idle timeout so a dynamic thread spawns, times out and
  14579. // exits during the test, and the pool keeps working afterwards.
  14580. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  14581. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  14582. /*idle_timeout_sec=*/1}};
  14583. std::atomic_uint count{0};
  14584. std::condition_variable cv;
  14585. std::mutex mtx;
  14586. bool release = false;
  14587. // Block the base thread so the second task spawns a dynamic thread.
  14588. EXPECT_TRUE(task_queue->enqueue([&] {
  14589. std::unique_lock<std::mutex> lock(mtx);
  14590. while (!release) {
  14591. cv.wait(lock);
  14592. }
  14593. count++;
  14594. }));
  14595. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14596. // Let the dynamic thread finish its task and exceed the idle timeout.
  14597. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  14598. {
  14599. std::unique_lock<std::mutex> lock(mtx);
  14600. release = true;
  14601. }
  14602. cv.notify_all();
  14603. // The pool must still accept and run tasks after the dynamic thread exited.
  14604. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14605. task_queue->shutdown();
  14606. EXPECT_EQ(3u, count.load());
  14607. }
  14608. TEST(TaskQueueTest, MaxQueuedRequests) {
  14609. static constexpr unsigned int qlimit{3};
  14610. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  14611. std::condition_variable sem_cv;
  14612. std::mutex sem_mtx;
  14613. int credits = 0;
  14614. bool queued;
  14615. /* Fill up the queue with tasks that will block until we give them credits to
  14616. * complete. */
  14617. for (unsigned int n = 0; n <= qlimit;) {
  14618. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  14619. std::unique_lock<std::mutex> lock(sem_mtx);
  14620. while (credits <= 0) {
  14621. sem_cv.wait(lock);
  14622. }
  14623. /* Consume the credit and signal the test code if they are all gone. */
  14624. if (--credits == 0) { sem_cv.notify_one(); }
  14625. });
  14626. if (n < qlimit) {
  14627. /* The first qlimit enqueues must succeed. */
  14628. EXPECT_TRUE(queued);
  14629. } else {
  14630. /* The last one will succeed only when the worker thread
  14631. * starts and dequeues the first blocking task. Although
  14632. * not necessary for the correctness of this test, we sleep for
  14633. * a short while to avoid busy waiting. */
  14634. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14635. }
  14636. if (queued) { n++; }
  14637. }
  14638. /* Further enqueues must fail since the queue is full. */
  14639. for (auto i = 0; i < 4; i++) {
  14640. queued = task_queue->enqueue([] {});
  14641. EXPECT_FALSE(queued);
  14642. }
  14643. /* Give the credits to allow the previous tasks to complete. */
  14644. {
  14645. std::unique_lock<std::mutex> lock(sem_mtx);
  14646. credits += qlimit + 1;
  14647. }
  14648. sem_cv.notify_all();
  14649. /* Wait for all the credits to be consumed. */
  14650. {
  14651. std::unique_lock<std::mutex> lock(sem_mtx);
  14652. while (credits > 0) {
  14653. sem_cv.wait(lock);
  14654. }
  14655. }
  14656. /* Check that we are able again to enqueue at least qlimit tasks. */
  14657. for (unsigned int i = 0; i < qlimit; i++) {
  14658. queued = task_queue->enqueue([] {});
  14659. EXPECT_TRUE(queued);
  14660. }
  14661. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14662. task_queue->shutdown();
  14663. #else
  14664. EXPECT_NO_THROW(task_queue->shutdown());
  14665. #endif
  14666. }
  14667. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  14668. Server svr;
  14669. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14670. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  14671. });
  14672. svr.Get("/hello", [](const Request &req, Response &res) {
  14673. res.set_content(req.get_param_value("key"), "text/plain");
  14674. });
  14675. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14676. auto se = detail::scope_exit([&] {
  14677. svr.stop();
  14678. thread.join();
  14679. ASSERT_FALSE(svr.is_running());
  14680. });
  14681. svr.wait_until_ready();
  14682. {
  14683. Client cli(HOST, PORT);
  14684. cli.set_follow_location(true);
  14685. auto res = cli.Get("/");
  14686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14687. EXPECT_EQ(StatusCode::OK_200, res->status);
  14688. EXPECT_EQ("val&key2=val2", res->body);
  14689. }
  14690. }
  14691. #endif
  14692. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  14693. Server svr;
  14694. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14695. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  14696. });
  14697. svr.Get("/hello", [](const Request &req, Response &res) {
  14698. res.set_content(req.get_param_value("key"), "text/plain");
  14699. });
  14700. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14701. auto se = detail::scope_exit([&] {
  14702. svr.stop();
  14703. thread.join();
  14704. ASSERT_FALSE(svr.is_running());
  14705. });
  14706. svr.wait_until_ready();
  14707. {
  14708. Client cli(HOST, PORT);
  14709. cli.set_follow_location(true);
  14710. auto res = cli.Get("/");
  14711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14712. EXPECT_EQ(StatusCode::OK_200, res->status);
  14713. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  14714. }
  14715. }
  14716. TEST(RedirectTest, RedirectWithPlusInPath) {
  14717. Server svr;
  14718. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14719. res.set_redirect("/a+b");
  14720. });
  14721. // Route pattern uses regex; escape + as \\+
  14722. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  14723. res.set_content(req.path, "text/plain");
  14724. });
  14725. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14726. auto se = detail::scope_exit([&] {
  14727. svr.stop();
  14728. thread.join();
  14729. ASSERT_FALSE(svr.is_running());
  14730. });
  14731. svr.wait_until_ready();
  14732. {
  14733. Client cli(HOST, PORT);
  14734. cli.set_follow_location(true);
  14735. auto res = cli.Get("/");
  14736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14737. EXPECT_EQ(StatusCode::OK_200, res->status);
  14738. EXPECT_EQ("/a+b", res->body);
  14739. }
  14740. }
  14741. TEST(RedirectTest, ResolveRelativeLocation) {
  14742. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  14743. const std::vector<std::pair<std::string, std::string>> cases = {
  14744. {"g", "/b/c/g"},
  14745. {"./g", "/b/c/g"},
  14746. {"g/", "/b/c/g/"},
  14747. {"?y", "/b/c/d;p?y"},
  14748. {"g?y", "/b/c/g?y"},
  14749. {"#s", "/b/c/d;p?q#s"},
  14750. {"g#s", "/b/c/g#s"},
  14751. {"g?y#s", "/b/c/g?y#s"},
  14752. {";x", "/b/c/;x"},
  14753. {"g;x", "/b/c/g;x"},
  14754. {".", "/b/c/"},
  14755. {"./", "/b/c/"},
  14756. {"..", "/b/"},
  14757. {"../", "/b/"},
  14758. {"../g", "/b/g"},
  14759. {"../..", "/"},
  14760. {"../../", "/"},
  14761. {"../../g", "/g"},
  14762. {"../../../g", "/g"},
  14763. {"g.", "/b/c/g."},
  14764. {".g", "/b/c/.g"},
  14765. {"g..", "/b/c/g.."},
  14766. {"..g", "/b/c/..g"},
  14767. {"./../g", "/b/g"},
  14768. {"./g/.", "/b/c/g/"},
  14769. {"g/./h", "/b/c/g/h"},
  14770. {"g/../h", "/b/c/h"},
  14771. {"g;x=1/./y", "/b/c/g;x=1/y"},
  14772. {"g;x=1/../y", "/b/c/y"},
  14773. {"g?y/./x", "/b/c/g?y/./x"},
  14774. {"g#s/../x", "/b/c/g#s/../x"},
  14775. // Not relative-path references, so left for parse_url.
  14776. {"/g", "/g"},
  14777. {"//g", "//g"},
  14778. {"http://g/x", "http://g/x"},
  14779. {"g:h", "g:h"},
  14780. };
  14781. for (const auto &c : cases) {
  14782. EXPECT_EQ(c.second,
  14783. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  14784. << c.first;
  14785. }
  14786. }
  14787. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  14788. Server svr;
  14789. svr.Get("/dir/page", [](const Request &req, Response &res) {
  14790. res.set_redirect(req.get_param_value("to"));
  14791. });
  14792. svr.Get("/dir/next", [](const Request &req, Response &res) {
  14793. res.set_content(req.target, "text/plain");
  14794. });
  14795. svr.Get("/other", [](const Request &req, Response &res) {
  14796. res.set_content(req.target, "text/plain");
  14797. });
  14798. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14799. auto se = detail::scope_exit([&] {
  14800. svr.stop();
  14801. thread.join();
  14802. ASSERT_FALSE(svr.is_running());
  14803. });
  14804. svr.wait_until_ready();
  14805. const std::vector<std::pair<std::string, std::string>> cases = {
  14806. {"next", "/dir/next"},
  14807. {"./next?x=1", "/dir/next?x=1"},
  14808. {"../other", "/other"},
  14809. };
  14810. for (const auto &c : cases) {
  14811. Client cli(HOST, PORT);
  14812. cli.set_follow_location(true);
  14813. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  14814. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  14815. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  14816. EXPECT_EQ(c.second, res->body) << c.first;
  14817. }
  14818. }
  14819. #ifdef CPPHTTPLIB_SSL_ENABLED
  14820. TEST(RedirectTest, Issue2185_Online) {
  14821. SSLClient client("github.com");
  14822. client.set_follow_location(true);
  14823. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  14824. "Coollab-Windows.zip");
  14825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14826. EXPECT_EQ(StatusCode::OK_200, res->status);
  14827. EXPECT_EQ(9920427U, res->body.size());
  14828. }
  14829. #endif
  14830. TEST(VulnerabilityTest, CRLFInjection) {
  14831. Server svr;
  14832. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  14833. res.set_content("Hello 1", "text/plain");
  14834. });
  14835. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  14836. res.set_content("Hello 2", "text/plain");
  14837. });
  14838. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  14839. res.set_content("Hello 3", "text/plain");
  14840. });
  14841. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  14842. res.set_content("Hello 4", "text/plain");
  14843. });
  14844. svr.set_logger([](const Request &req, const Response & /*res*/) {
  14845. for (const auto &x : req.headers) {
  14846. auto key = x.first;
  14847. EXPECT_STRNE("evil", key.c_str());
  14848. }
  14849. });
  14850. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14851. auto se = detail::scope_exit([&] {
  14852. svr.stop();
  14853. thread.join();
  14854. ASSERT_FALSE(svr.is_running());
  14855. });
  14856. svr.wait_until_ready();
  14857. {
  14858. Client cli(HOST, PORT);
  14859. cli.Post("/test1", "A=B",
  14860. "application/x-www-form-urlencoded\r\nevil: hello1");
  14861. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  14862. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  14863. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  14864. }
  14865. }
  14866. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  14867. auto server_thread = std::thread([] {
  14868. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14869. default_socket_options(srv);
  14870. sockaddr_in addr{};
  14871. addr.sin_family = AF_INET;
  14872. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14873. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14874. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  14875. ::listen(srv, 1);
  14876. sockaddr_in cli_addr{};
  14877. socklen_t cli_len = sizeof(cli_addr);
  14878. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14879. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  14880. std::string buf_all;
  14881. char buf[2048];
  14882. ssize_t n;
  14883. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  14884. buf_all.append(buf, static_cast<size_t>(n));
  14885. size_t pos;
  14886. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  14887. auto request_block = buf_all.substr(0, pos + 4); // include separator
  14888. auto e = request_block.find("\r\n");
  14889. if (e != std::string::npos) {
  14890. auto request_line = request_block.substr(0, e);
  14891. std::string msg =
  14892. "CRLF injection detected in request line: '" + request_line + "'";
  14893. EXPECT_FALSE(true) << msg;
  14894. }
  14895. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  14896. ::send(cli,
  14897. #ifdef _WIN32
  14898. static_cast<const char *>(resp.c_str()),
  14899. static_cast<int>(resp.size()),
  14900. #else
  14901. resp.c_str(), resp.size(),
  14902. #endif
  14903. 0);
  14904. buf_all.erase(0, pos + 4);
  14905. }
  14906. }
  14907. detail::close_socket(cli);
  14908. detail::close_socket(srv);
  14909. });
  14910. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14911. auto cli = Client("127.0.0.1", PORT + 1);
  14912. auto headers = Headers{
  14913. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  14914. {"Connection", "keep-alive"}};
  14915. auto res = cli.Get("/hi", headers);
  14916. EXPECT_FALSE(res);
  14917. EXPECT_EQ(Error::InvalidHeaders, res.error());
  14918. server_thread.join();
  14919. }
  14920. // A request rejected before any byte reaches the socket must fail right away
  14921. // instead of waiting for a response the server will never send.
  14922. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  14923. // The kernel completes the TCP handshake from the listen backlog, so the
  14924. // client connects, but nothing ever reads, responds or closes.
  14925. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14926. default_socket_options(srv);
  14927. sockaddr_in addr{};
  14928. addr.sin_family = AF_INET;
  14929. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14930. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14931. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14932. ASSERT_EQ(0, ::listen(srv, 8));
  14933. auto cli = Client("127.0.0.1", PORT + 1);
  14934. cli.set_read_timeout(10, 0);
  14935. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  14936. return std::chrono::duration_cast<std::chrono::milliseconds>(
  14937. std::chrono::steady_clock::now() - start)
  14938. .count();
  14939. };
  14940. {
  14941. Request req;
  14942. req.method = "GE T";
  14943. req.path = "/";
  14944. auto start = std::chrono::steady_clock::now();
  14945. auto res = cli.send(req);
  14946. EXPECT_FALSE(res);
  14947. EXPECT_EQ(Error::Write, res.error());
  14948. EXPECT_LT(elapsed_ms(start), 1000);
  14949. }
  14950. {
  14951. auto start = std::chrono::steady_clock::now();
  14952. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  14953. EXPECT_FALSE(res);
  14954. EXPECT_EQ(Error::InvalidHeaders, res.error());
  14955. EXPECT_LT(elapsed_ms(start), 1000);
  14956. }
  14957. EXPECT_FALSE(cli.is_socket_open());
  14958. detail::close_socket(srv);
  14959. }
  14960. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  14961. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14962. default_socket_options(srv);
  14963. sockaddr_in addr{};
  14964. addr.sin_family = AF_INET;
  14965. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14966. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14967. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14968. ASSERT_EQ(0, ::listen(srv, 1));
  14969. std::string received;
  14970. auto server_thread = std::thread([&] {
  14971. auto sock = ::accept(srv, nullptr, nullptr);
  14972. if (sock == INVALID_SOCKET) { return; }
  14973. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  14974. char buf[2048];
  14975. ssize_t n;
  14976. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  14977. received.append(buf, static_cast<size_t>(n));
  14978. }
  14979. detail::close_socket(sock);
  14980. });
  14981. {
  14982. auto cli = Client("127.0.0.1", PORT + 1);
  14983. // "Z" sorts after the default headers, so writing straight to the socket
  14984. // would have sent the request line and those headers before the rejection.
  14985. auto handle =
  14986. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  14987. EXPECT_FALSE(handle.is_valid());
  14988. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  14989. }
  14990. server_thread.join();
  14991. detail::close_socket(srv);
  14992. EXPECT_TRUE(received.empty()) << received;
  14993. }
  14994. TEST(PathParamsTest, StaticMatch) {
  14995. const auto pattern = "/users/all";
  14996. detail::PathParamsMatcher matcher(pattern);
  14997. Request request;
  14998. request.path = "/users/all";
  14999. ASSERT_TRUE(matcher.match(request));
  15000. std::unordered_map<std::string, std::string> expected_params = {};
  15001. EXPECT_EQ(request.path_params, expected_params);
  15002. }
  15003. TEST(PathParamsTest, StaticMismatch) {
  15004. const auto pattern = "/users/all";
  15005. detail::PathParamsMatcher matcher(pattern);
  15006. Request request;
  15007. request.path = "/users/1";
  15008. ASSERT_FALSE(matcher.match(request));
  15009. }
  15010. TEST(PathParamsTest, SingleParamInTheMiddle) {
  15011. const auto pattern = "/users/:id/subscriptions";
  15012. detail::PathParamsMatcher matcher(pattern);
  15013. Request request;
  15014. request.path = "/users/42/subscriptions";
  15015. ASSERT_TRUE(matcher.match(request));
  15016. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15017. EXPECT_EQ(request.path_params, expected_params);
  15018. }
  15019. TEST(PathParamsTest, SingleParamInTheEnd) {
  15020. const auto pattern = "/users/:id";
  15021. detail::PathParamsMatcher matcher(pattern);
  15022. Request request;
  15023. request.path = "/users/24";
  15024. ASSERT_TRUE(matcher.match(request));
  15025. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  15026. EXPECT_EQ(request.path_params, expected_params);
  15027. }
  15028. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  15029. const auto pattern = "/users/:id/";
  15030. detail::PathParamsMatcher matcher(pattern);
  15031. Request request;
  15032. request.path = "/users/42/";
  15033. ASSERT_TRUE(matcher.match(request));
  15034. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15035. EXPECT_EQ(request.path_params, expected_params);
  15036. }
  15037. TEST(PathParamsTest, EmptyParam) {
  15038. const auto pattern = "/users/:id/";
  15039. detail::PathParamsMatcher matcher(pattern);
  15040. Request request;
  15041. request.path = "/users//";
  15042. ASSERT_TRUE(matcher.match(request));
  15043. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  15044. EXPECT_EQ(request.path_params, expected_params);
  15045. }
  15046. TEST(PathParamsTest, FragmentMismatch) {
  15047. const auto pattern = "/users/:id/";
  15048. detail::PathParamsMatcher matcher(pattern);
  15049. Request request;
  15050. request.path = "/admins/24/";
  15051. ASSERT_FALSE(matcher.match(request));
  15052. }
  15053. TEST(PathParamsTest, ExtraFragments) {
  15054. const auto pattern = "/users/:id";
  15055. detail::PathParamsMatcher matcher(pattern);
  15056. Request request;
  15057. request.path = "/users/42/subscriptions";
  15058. ASSERT_FALSE(matcher.match(request));
  15059. }
  15060. TEST(PathParamsTest, MissingTrailingParam) {
  15061. const auto pattern = "/users/:id";
  15062. detail::PathParamsMatcher matcher(pattern);
  15063. Request request;
  15064. request.path = "/users";
  15065. ASSERT_FALSE(matcher.match(request));
  15066. }
  15067. TEST(PathParamsTest, MissingParamInTheMiddle) {
  15068. const auto pattern = "/users/:id/subscriptions";
  15069. detail::PathParamsMatcher matcher(pattern);
  15070. Request request;
  15071. request.path = "/users/subscriptions";
  15072. ASSERT_FALSE(matcher.match(request));
  15073. }
  15074. TEST(PathParamsTest, MultipleParams) {
  15075. const auto pattern = "/users/:userid/subscriptions/:subid";
  15076. detail::PathParamsMatcher matcher(pattern);
  15077. Request request;
  15078. request.path = "/users/42/subscriptions/2";
  15079. ASSERT_TRUE(matcher.match(request));
  15080. std::unordered_map<std::string, std::string> expected_params = {
  15081. {"userid", "42"}, {"subid", "2"}};
  15082. EXPECT_EQ(request.path_params, expected_params);
  15083. }
  15084. TEST(PathParamsTest, SequenceOfParams) {
  15085. const auto pattern = "/values/:x/:y/:z";
  15086. detail::PathParamsMatcher matcher(pattern);
  15087. Request request;
  15088. request.path = "/values/1/2/3";
  15089. ASSERT_TRUE(matcher.match(request));
  15090. std::unordered_map<std::string, std::string> expected_params = {
  15091. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  15092. EXPECT_EQ(request.path_params, expected_params);
  15093. }
  15094. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  15095. const auto pattern = "/prefix:suffix";
  15096. detail::PathParamsMatcher matcher(pattern);
  15097. Request request;
  15098. request.path = "/prefix:suffix";
  15099. ASSERT_TRUE(matcher.match(request));
  15100. const std::unordered_map<std::string, std::string> expected_params = {};
  15101. EXPECT_EQ(request.path_params, expected_params);
  15102. }
  15103. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  15104. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  15105. // calling thread's stack on a long enough path for a quantified pattern;
  15106. // RegexMatcher must refuse to run regex matching on paths beyond
  15107. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  15108. detail::RegexMatcher matcher("/files/(.*)");
  15109. Request within_limit;
  15110. within_limit.path = "/files/" + std::string(10, 'A');
  15111. EXPECT_TRUE(matcher.match(within_limit));
  15112. Request over_limit;
  15113. over_limit.path =
  15114. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  15115. EXPECT_FALSE(matcher.match(over_limit));
  15116. }
  15117. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  15118. Server svr;
  15119. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  15120. res.set_content("ok", "text/plain");
  15121. });
  15122. auto port = svr.bind_to_any_port(HOST);
  15123. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15124. auto se = detail::scope_exit([&] {
  15125. svr.stop();
  15126. thread.join();
  15127. ASSERT_FALSE(svr.is_running());
  15128. });
  15129. svr.wait_until_ready();
  15130. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  15131. // request URI limit; this used to be able to crash the process.
  15132. std::string path =
  15133. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  15134. std::string req = "GET " + path +
  15135. " HTTP/1.1\r\n"
  15136. "Host: " +
  15137. std::string(HOST) + ":" + std::to_string(port) +
  15138. "\r\n"
  15139. "Connection: close\r\n"
  15140. "\r\n";
  15141. std::string response;
  15142. ASSERT_TRUE(send_request(5, req, &response, port));
  15143. EXPECT_NE(std::string::npos, response.find("404"));
  15144. }
  15145. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  15146. Server svr;
  15147. auto handler = [](const Request & /*req*/, Response &res) {
  15148. res.set_content("hit", "text/plain");
  15149. };
  15150. // No regex metacharacter, so this one is compared literally
  15151. svr.Get("/literal/route", handler);
  15152. // '.' is a regex metacharacter, so this one must keep regex semantics
  15153. svr.Get("/a.c", handler);
  15154. auto port = svr.bind_to_any_port(HOST);
  15155. std::thread t([&]() { svr.listen_after_bind(); });
  15156. auto se = detail::scope_exit([&] {
  15157. svr.stop();
  15158. t.join();
  15159. ASSERT_FALSE(svr.is_running());
  15160. });
  15161. svr.wait_until_ready();
  15162. Client cli(HOST, port);
  15163. struct {
  15164. const char *path;
  15165. int status;
  15166. } cases[] = {
  15167. {"/literal/route", StatusCode::OK_200},
  15168. {"/literal/routes", StatusCode::NotFound_404},
  15169. {"/literal/rout", StatusCode::NotFound_404},
  15170. {"/abc", StatusCode::OK_200},
  15171. {"/a.c", StatusCode::OK_200},
  15172. };
  15173. for (const auto &x : cases) {
  15174. auto res = cli.Get(x.path);
  15175. ASSERT_TRUE(res) << x.path;
  15176. EXPECT_EQ(x.status, res->status) << x.path;
  15177. }
  15178. }
  15179. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  15180. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  15181. // from exhausting the stack, so it must only constrain routes that actually
  15182. // run a regular expression. A literal route is matched by comparison and
  15183. // stays usable at any length.
  15184. Server svr;
  15185. const std::string pattern =
  15186. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  15187. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  15188. res.set_content("hit", "text/plain");
  15189. });
  15190. auto port = svr.bind_to_any_port(HOST);
  15191. std::thread t([&]() { svr.listen_after_bind(); });
  15192. auto se = detail::scope_exit([&] {
  15193. svr.stop();
  15194. t.join();
  15195. ASSERT_FALSE(svr.is_running());
  15196. });
  15197. svr.wait_until_ready();
  15198. Client cli(HOST, port);
  15199. auto res = cli.Get(pattern);
  15200. ASSERT_TRUE(res);
  15201. EXPECT_EQ(StatusCode::OK_200, res->status);
  15202. }
  15203. TEST(ParseUrlTest, VariousPatterns) {
  15204. {
  15205. detail::UrlComponents uc;
  15206. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  15207. EXPECT_EQ("http", uc.scheme);
  15208. EXPECT_EQ("example.com", uc.host);
  15209. EXPECT_EQ("8080", uc.port);
  15210. EXPECT_EQ("/path", uc.path);
  15211. EXPECT_EQ("?q=1", uc.query);
  15212. }
  15213. {
  15214. detail::UrlComponents uc;
  15215. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  15216. EXPECT_EQ("https", uc.scheme);
  15217. EXPECT_EQ("example.com", uc.host);
  15218. EXPECT_TRUE(uc.port.empty());
  15219. EXPECT_EQ("/path", uc.path);
  15220. }
  15221. {
  15222. detail::UrlComponents uc;
  15223. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  15224. EXPECT_EQ("::1", uc.host);
  15225. EXPECT_EQ("8080", uc.port);
  15226. EXPECT_EQ("/path", uc.path);
  15227. }
  15228. {
  15229. detail::UrlComponents uc;
  15230. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  15231. }
  15232. {
  15233. // Bytes after the IPv6 literal must be a delimiter, not folded into
  15234. // the path while the connection still targets the bracketed host.
  15235. detail::UrlComponents uc;
  15236. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  15237. }
  15238. {
  15239. detail::UrlComponents uc;
  15240. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  15241. }
  15242. {
  15243. detail::UrlComponents uc;
  15244. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  15245. EXPECT_EQ("::1", uc.host);
  15246. EXPECT_TRUE(uc.port.empty());
  15247. EXPECT_EQ("/path", uc.path);
  15248. }
  15249. {
  15250. detail::UrlComponents uc;
  15251. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  15252. EXPECT_TRUE(uc.scheme.empty());
  15253. EXPECT_EQ("example.com", uc.host);
  15254. EXPECT_EQ("/path", uc.path);
  15255. EXPECT_EQ("?q=1", uc.query);
  15256. }
  15257. {
  15258. detail::UrlComponents uc;
  15259. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  15260. EXPECT_TRUE(uc.host.empty());
  15261. EXPECT_EQ("/path", uc.path);
  15262. EXPECT_EQ("?q=1", uc.query);
  15263. }
  15264. {
  15265. detail::UrlComponents uc;
  15266. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  15267. EXPECT_EQ("example.com", uc.host);
  15268. EXPECT_EQ("8080", uc.port);
  15269. }
  15270. {
  15271. // Unix socket path — must not be parsed as host
  15272. detail::UrlComponents uc;
  15273. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  15274. EXPECT_TRUE(uc.host.empty());
  15275. }
  15276. {
  15277. detail::UrlComponents uc;
  15278. ASSERT_TRUE(detail::parse_url("", uc));
  15279. EXPECT_TRUE(uc.host.empty());
  15280. EXPECT_TRUE(uc.path.empty());
  15281. }
  15282. {
  15283. detail::UrlComponents uc;
  15284. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  15285. }
  15286. {
  15287. detail::UrlComponents uc;
  15288. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  15289. }
  15290. {
  15291. // Accepted by parse_url; callers restrict to http/https
  15292. detail::UrlComponents uc;
  15293. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  15294. EXPECT_EQ("ftp", uc.scheme);
  15295. }
  15296. {
  15297. detail::UrlComponents uc;
  15298. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  15299. }
  15300. {
  15301. detail::UrlComponents uc;
  15302. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  15303. }
  15304. }
  15305. TEST(ParseUrlTest, FragmentHandling) {
  15306. {
  15307. detail::UrlComponents uc;
  15308. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  15309. EXPECT_EQ("/path", uc.path);
  15310. EXPECT_TRUE(uc.query.empty());
  15311. }
  15312. {
  15313. detail::UrlComponents uc;
  15314. ASSERT_TRUE(detail::parse_url("#frag", uc));
  15315. EXPECT_TRUE(uc.path.empty());
  15316. EXPECT_TRUE(uc.query.empty());
  15317. }
  15318. }
  15319. TEST(ParseUrlTest, UserinfoHandling) {
  15320. // Userinfo with @ but no colon — host includes @
  15321. detail::UrlComponents uc;
  15322. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  15323. EXPECT_EQ("user@host.com", uc.host);
  15324. EXPECT_EQ("/path", uc.path);
  15325. }
  15326. TEST(ParseUrlTest, IPv6EdgeCases) {
  15327. {
  15328. detail::UrlComponents uc;
  15329. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  15330. EXPECT_TRUE(uc.scheme.empty());
  15331. EXPECT_EQ("::1", uc.host);
  15332. EXPECT_EQ("8080", uc.port);
  15333. }
  15334. {
  15335. // Zone ID '%25' is not in [a-fA-F0-9:]
  15336. detail::UrlComponents uc;
  15337. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  15338. }
  15339. }
  15340. TEST(ParseUrlTest, SchemeEdgeCases) {
  15341. {
  15342. detail::UrlComponents uc;
  15343. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  15344. }
  15345. {
  15346. detail::UrlComponents uc;
  15347. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  15348. }
  15349. {
  15350. detail::UrlComponents uc;
  15351. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  15352. }
  15353. }
  15354. TEST(ParseUrlTest, PortEdgeCases) {
  15355. {
  15356. detail::UrlComponents uc;
  15357. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  15358. EXPECT_TRUE(uc.port.empty());
  15359. EXPECT_EQ("/path", uc.path);
  15360. }
  15361. {
  15362. // parse_url accepts any port string; validation is done by parse_port
  15363. detail::UrlComponents uc;
  15364. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  15365. EXPECT_EQ("abc", uc.port);
  15366. }
  15367. }
  15368. TEST(ParseUrlTest, WebSocketPatterns) {
  15369. {
  15370. detail::UrlComponents uc;
  15371. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  15372. EXPECT_EQ("ws", uc.scheme);
  15373. EXPECT_EQ("echo.example.com", uc.host);
  15374. EXPECT_EQ("8080", uc.port);
  15375. EXPECT_EQ("/ws", uc.path);
  15376. }
  15377. {
  15378. detail::UrlComponents uc;
  15379. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  15380. EXPECT_EQ("wss", uc.scheme);
  15381. EXPECT_EQ("echo.example.com", uc.host);
  15382. EXPECT_TRUE(uc.port.empty());
  15383. EXPECT_EQ("/ws", uc.path);
  15384. }
  15385. }
  15386. TEST(ParseUrlTest, QueryOnly) {
  15387. detail::UrlComponents uc;
  15388. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  15389. EXPECT_TRUE(uc.host.empty());
  15390. EXPECT_TRUE(uc.path.empty());
  15391. EXPECT_EQ("?q=1&r=2", uc.query);
  15392. }
  15393. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  15394. detail::UrlComponents uc;
  15395. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  15396. EXPECT_TRUE(uc.scheme.empty());
  15397. EXPECT_EQ("example.com", uc.host);
  15398. EXPECT_EQ("443", uc.port);
  15399. EXPECT_EQ("/path", uc.path);
  15400. }
  15401. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  15402. // If ipv6 regex working, regex match codepath is taken.
  15403. // else port will default to 80 in Client impl
  15404. int clientImplMagicPort = 80;
  15405. int port = 4321;
  15406. // above ports must be different to avoid false negative
  15407. EXPECT_NE(clientImplMagicPort, port);
  15408. std::string ipV6TestURL = "http://[ff06::c3]";
  15409. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  15410. CLIENT_PRIVATE_KEY_FILE);
  15411. EXPECT_EQ(cli.port(), port);
  15412. }
  15413. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  15414. auto file_path = "./www/dir/index.html";
  15415. auto dir_path = "./www/dir";
  15416. detail::FileStat stat_file(file_path);
  15417. EXPECT_TRUE(stat_file.is_file());
  15418. EXPECT_FALSE(stat_file.is_dir());
  15419. detail::FileStat stat_dir(dir_path);
  15420. EXPECT_FALSE(stat_dir.is_file());
  15421. EXPECT_TRUE(stat_dir.is_dir());
  15422. }
  15423. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  15424. // IPv4 with default HTTP port (80)
  15425. EXPECT_EQ("example.com",
  15426. detail::make_host_and_port_string("example.com", 80, false));
  15427. // IPv4 with default HTTPS port (443)
  15428. EXPECT_EQ("example.com",
  15429. detail::make_host_and_port_string("example.com", 443, true));
  15430. // IPv4 with non-default HTTP port
  15431. EXPECT_EQ("example.com:8080",
  15432. detail::make_host_and_port_string("example.com", 8080, false));
  15433. // IPv4 with non-default HTTPS port
  15434. EXPECT_EQ("example.com:8443",
  15435. detail::make_host_and_port_string("example.com", 8443, true));
  15436. // IPv6 with default HTTP port (80)
  15437. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  15438. // IPv6 with default HTTPS port (443)
  15439. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  15440. // IPv6 with non-default HTTP port
  15441. EXPECT_EQ("[::1]:8080",
  15442. detail::make_host_and_port_string("::1", 8080, false));
  15443. // IPv6 with non-default HTTPS port
  15444. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  15445. // IPv6 full address with default port
  15446. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  15447. detail::make_host_and_port_string(
  15448. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  15449. // IPv6 full address with non-default port
  15450. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  15451. detail::make_host_and_port_string(
  15452. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  15453. // IPv6 localhost with non-default port
  15454. EXPECT_EQ("[::1]:3000",
  15455. detail::make_host_and_port_string("::1", 3000, false));
  15456. // IPv6 with zone ID (link-local address) with default port
  15457. EXPECT_EQ("[fe80::1%eth0]",
  15458. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  15459. // IPv6 with zone ID (link-local address) with non-default port
  15460. EXPECT_EQ("[fe80::1%eth0]:8080",
  15461. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  15462. // Edge case: Port 443 with is_ssl=false (should add port)
  15463. EXPECT_EQ("example.com:443",
  15464. detail::make_host_and_port_string("example.com", 443, false));
  15465. // Edge case: Port 80 with is_ssl=true (should add port)
  15466. EXPECT_EQ("example.com:80",
  15467. detail::make_host_and_port_string("example.com", 80, true));
  15468. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  15469. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  15470. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  15471. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  15472. // Security fix: Already bracketed IPv6 should not get double brackets
  15473. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  15474. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  15475. EXPECT_EQ("[::1]:8080",
  15476. detail::make_host_and_port_string("[::1]", 8080, false));
  15477. EXPECT_EQ("[2001:db8::1]:8080",
  15478. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  15479. EXPECT_EQ("[fe80::1%eth0]",
  15480. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  15481. EXPECT_EQ("[fe80::1%eth0]:8080",
  15482. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  15483. // Edge case: Empty host (should return as-is)
  15484. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  15485. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  15486. // This is a known limitation but shouldn't crash
  15487. EXPECT_EQ("[host:name]",
  15488. detail::make_host_and_port_string("host:name", 80, false));
  15489. // Port number edge cases (no validation, but should not crash)
  15490. EXPECT_EQ("example.com:0",
  15491. detail::make_host_and_port_string("example.com", 0, false));
  15492. EXPECT_EQ("example.com:-1",
  15493. detail::make_host_and_port_string("example.com", -1, false));
  15494. EXPECT_EQ("example.com:65535",
  15495. detail::make_host_and_port_string("example.com", 65535, false));
  15496. EXPECT_EQ("example.com:65536",
  15497. detail::make_host_and_port_string("example.com", 65536, false));
  15498. }
  15499. #ifdef CPPHTTPLIB_SSL_ENABLED
  15500. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  15501. httplib::SSLClient cli("roblox.com", 443);
  15502. cli.set_follow_location(true);
  15503. auto res = cli.Get("/");
  15504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15505. EXPECT_EQ(StatusCode::OK_200, res->status);
  15506. }
  15507. #endif
  15508. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  15509. Server svr;
  15510. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15511. EXPECT_EQ(res.status, 400);
  15512. });
  15513. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15514. auto se = detail::scope_exit([&] {
  15515. svr.stop();
  15516. thread.join();
  15517. ASSERT_FALSE(svr.is_running());
  15518. });
  15519. svr.wait_until_ready();
  15520. Client cli(HOST, PORT);
  15521. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  15522. }
  15523. TEST(InvalidHeaderCharsTest, is_field_name) {
  15524. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  15525. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  15526. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  15527. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  15528. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  15529. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  15530. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  15531. EXPECT_FALSE(detail::fields::is_field_name(""));
  15532. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  15533. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  15534. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  15535. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  15536. }
  15537. TEST(InvalidHeaderCharsTest, is_field_value) {
  15538. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  15539. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  15540. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  15541. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  15542. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  15543. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  15544. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  15545. EXPECT_TRUE(detail::fields::is_field_value(""));
  15546. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  15547. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  15548. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  15549. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  15550. EXPECT_TRUE(detail::fields::is_field_value("0"));
  15551. }
  15552. TEST(InvalidHeaderCharsTest, OnServer) {
  15553. Server svr;
  15554. svr.Get("/test_name", [&](const Request &req, Response &res) {
  15555. std::string header = "Not Set";
  15556. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15557. res.set_header(header, "value");
  15558. res.set_content("Page Content Page Content", "text/plain");
  15559. });
  15560. svr.Get("/test_value", [&](const Request &req, Response &res) {
  15561. std::string header = "Not Set";
  15562. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15563. res.set_header("X-Test", header);
  15564. res.set_content("Page Content Page Content", "text/plain");
  15565. });
  15566. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15567. auto se = detail::scope_exit([&] {
  15568. svr.stop();
  15569. thread.join();
  15570. ASSERT_FALSE(svr.is_running());
  15571. });
  15572. svr.wait_until_ready();
  15573. Client cli(HOST, PORT);
  15574. {
  15575. auto res = cli.Get(
  15576. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15578. EXPECT_EQ("Page Content Page Content", res->body);
  15579. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15580. }
  15581. {
  15582. auto res = cli.Get(
  15583. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15585. EXPECT_EQ("Page Content Page Content", res->body);
  15586. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15587. }
  15588. }
  15589. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  15590. auto handled = false;
  15591. Server svr;
  15592. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15593. thread t = thread([&] { svr.listen(HOST, PORT); });
  15594. auto se = detail::scope_exit([&] {
  15595. svr.stop();
  15596. t.join();
  15597. ASSERT_FALSE(svr.is_running());
  15598. ASSERT_FALSE(handled);
  15599. });
  15600. svr.wait_until_ready();
  15601. auto req = "POST /test HTTP/1.1\r\n"
  15602. "Content-Length: x\r\n"
  15603. "\r\n";
  15604. std::string response;
  15605. ASSERT_TRUE(send_request(1, req, &response));
  15606. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15607. response.substr(0, response.find("\r\n")));
  15608. }
  15609. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  15610. // case-insensitive, and a server that receives a 100-continue expectation in
  15611. // an HTTP/1.0 request MUST ignore it.
  15612. static void probe_expect(int port, const std::string &req, bool *got_100) {
  15613. std::string response;
  15614. ASSERT_TRUE(send_request(1, req, &response, port));
  15615. *got_100 = response.find("100 Continue") != std::string::npos;
  15616. }
  15617. class ExpectTokenTest : public ::testing::Test {
  15618. protected:
  15619. void SetUp() override {
  15620. svr_.Post("/p", [](const Request &, Response &res) {
  15621. res.set_content("ok", "text/plain");
  15622. });
  15623. port_ = svr_.bind_to_any_port(HOST);
  15624. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15625. svr_.wait_until_ready();
  15626. }
  15627. void TearDown() override {
  15628. svr_.stop();
  15629. if (thread_.joinable()) { thread_.join(); }
  15630. }
  15631. std::string request(const char *version, const char *expect_value) const {
  15632. return std::string("POST /p ") + version +
  15633. "\r\n"
  15634. "Host: localhost\r\n"
  15635. "Content-Length: 2\r\n"
  15636. "Connection: close\r\n"
  15637. "Expect: " +
  15638. expect_value +
  15639. "\r\n"
  15640. "\r\n"
  15641. "hi";
  15642. }
  15643. Server svr_;
  15644. int port_ = 0;
  15645. thread thread_;
  15646. };
  15647. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  15648. bool got_100 = false;
  15649. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  15650. EXPECT_TRUE(got_100);
  15651. }
  15652. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  15653. bool got_100 = true;
  15654. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  15655. EXPECT_FALSE(got_100);
  15656. }
  15657. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  15658. bool got_100 = false;
  15659. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  15660. EXPECT_TRUE(got_100);
  15661. }
  15662. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  15663. bool got_100 = false;
  15664. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  15665. EXPECT_TRUE(got_100);
  15666. }
  15667. // `100 Continue` is sent only when the server starts reading the body, so a
  15668. // request rejected before that never invites the client to send it. The
  15669. // requests below carry the expectation but withhold the body, as a client
  15670. // waiting for `100 Continue` would.
  15671. // A POST that expects `100 Continue` and withholds its two-byte body.
  15672. static std::string expect_headers_only(const std::string &path) {
  15673. return "POST " + path +
  15674. " HTTP/1.1\r\n"
  15675. "Host: localhost\r\n"
  15676. "Content-Length: 2\r\n"
  15677. "Expect: 100-continue\r\n"
  15678. "\r\n";
  15679. }
  15680. class ExpectLazyContinueTest : public ::testing::Test {
  15681. protected:
  15682. void SetUp() override {
  15683. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  15684. if (req.path == "/pre-routing") {
  15685. res.status = StatusCode::Unauthorized_401;
  15686. return Server::HandlerResponse::Handled;
  15687. }
  15688. return Server::HandlerResponse::Unhandled;
  15689. });
  15690. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  15691. if (req.matched_route == "/pre-request") {
  15692. res.status = StatusCode::Forbidden_403;
  15693. return Server::HandlerResponse::Handled;
  15694. }
  15695. return Server::HandlerResponse::Unhandled;
  15696. });
  15697. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  15698. res.set_content("ok", "text/plain");
  15699. });
  15700. svr_.Post("/pre-request", [](const Request &, Response &res) {
  15701. res.set_content("ok", "text/plain");
  15702. });
  15703. svr_.Post("/reader-used", [](const Request &, Response &res,
  15704. const ContentReader &content_reader) {
  15705. std::string body;
  15706. content_reader([&](const char *data, size_t len) {
  15707. body.append(data, len);
  15708. return true;
  15709. });
  15710. res.set_content(body, "text/plain");
  15711. });
  15712. svr_.Post("/reader-unused",
  15713. [](const Request &, Response &res, const ContentReader &) {
  15714. res.set_content("ignored", "text/plain");
  15715. });
  15716. port_ = svr_.bind_to_any_port(HOST);
  15717. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15718. svr_.wait_until_ready();
  15719. }
  15720. void TearDown() override {
  15721. svr_.stop();
  15722. if (thread_.joinable()) { thread_.join(); }
  15723. }
  15724. // Sends `req` and reads until the server closes the connection. Returns
  15725. // false if the read had to wait for the client-side timeout instead.
  15726. bool send_until_closed(const std::string &req, std::string *resp) const {
  15727. auto start = std::chrono::steady_clock::now();
  15728. if (!send_request(3, req, resp, port_)) { return false; }
  15729. auto elapsed = std::chrono::steady_clock::now() - start;
  15730. return elapsed < std::chrono::seconds(2);
  15731. }
  15732. // The final response comes without `100 Continue`, and the server closes
  15733. // the connection since the body may or may not follow.
  15734. void expect_final_without_interim(const std::string &path,
  15735. const char *status_line) const {
  15736. std::string resp;
  15737. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  15738. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  15739. EXPECT_EQ(0u, resp.find(status_line));
  15740. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15741. }
  15742. Server svr_;
  15743. int port_ = 0;
  15744. thread thread_;
  15745. };
  15746. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  15747. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  15748. }
  15749. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  15750. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  15751. }
  15752. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  15753. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  15754. }
  15755. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  15756. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  15757. }
  15758. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  15759. // The body follows once `100 Continue` has had time to arrive.
  15760. auto req = expect_headers_only("/reader-used");
  15761. req.insert(req.size() - 2, "Connection: close\r\n");
  15762. std::string resp;
  15763. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  15764. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  15765. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  15766. EXPECT_NE(std::string::npos, resp.find("hi"));
  15767. }
  15768. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  15769. // Large enough for the client to add `Expect: 100-continue` itself.
  15770. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  15771. std::atomic<bool> body_sent{false};
  15772. Client cli(HOST, port_);
  15773. auto res = cli.Post(
  15774. "/pre-request", length,
  15775. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  15776. body_sent = true;
  15777. std::string chunk(len, 'x');
  15778. sink.write(chunk.data(), chunk.size());
  15779. return true;
  15780. },
  15781. "application/octet-stream");
  15782. ASSERT_TRUE(res);
  15783. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  15784. EXPECT_FALSE(body_sent);
  15785. }
  15786. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  15787. Server svr;
  15788. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  15789. return StatusCode::ExpectationFailed_417;
  15790. });
  15791. svr.Post("/p", [](const Request &, Response &res) {
  15792. res.set_content("ok", "text/plain");
  15793. });
  15794. auto port = svr.bind_to_any_port(HOST);
  15795. thread t = thread([&] { svr.listen_after_bind(); });
  15796. auto se = detail::scope_exit([&] {
  15797. svr.stop();
  15798. t.join();
  15799. });
  15800. svr.wait_until_ready();
  15801. std::string resp;
  15802. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  15803. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  15804. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15805. // Exactly one response: the route handler must not run after the 417.
  15806. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  15807. }
  15808. #ifndef _WIN32
  15809. TEST(Expect100ContinueTest, ServerClosesConnection) {
  15810. static constexpr char reject[] = "Unauthorized";
  15811. static constexpr char accept[] = "Upload accepted";
  15812. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  15813. Server svr;
  15814. svr.set_expect_100_continue_handler(
  15815. [](const Request & /*req*/, Response &res) {
  15816. res.status = StatusCode::Unauthorized_401;
  15817. res.set_content(reject, "text/plain");
  15818. return res.status;
  15819. });
  15820. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  15821. res.set_content(accept, "text/plain");
  15822. });
  15823. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15824. auto se = detail::scope_exit([&] {
  15825. svr.stop();
  15826. thread.join();
  15827. ASSERT_FALSE(svr.is_running());
  15828. });
  15829. svr.wait_until_ready();
  15830. {
  15831. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  15832. curl_easy_init(), &curl_easy_cleanup};
  15833. ASSERT_NE(curl, nullptr);
  15834. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  15835. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  15836. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  15837. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  15838. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  15839. &curl_slist_free_all};
  15840. ASSERT_NE(list, nullptr);
  15841. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  15842. struct read_data {
  15843. size_t read_size;
  15844. size_t total_size;
  15845. } data = {0, total_size};
  15846. using read_callback_t =
  15847. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15848. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  15849. void *userdata) -> size_t {
  15850. read_data *d = (read_data *)userdata;
  15851. if (!userdata || d->read_size >= d->total_size) { return 0; }
  15852. std::fill_n(ptr, size * nmemb, 'A');
  15853. d->read_size += size * nmemb;
  15854. return size * nmemb;
  15855. };
  15856. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  15857. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  15858. std::vector<char> buffer;
  15859. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  15860. using write_callback_t =
  15861. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15862. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  15863. void *userdata) -> size_t {
  15864. std::vector<char> *buf = (std::vector<char> *)userdata;
  15865. buf->reserve(buf->size() + size * nmemb + 1);
  15866. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  15867. return size * nmemb;
  15868. };
  15869. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  15870. {
  15871. const auto res = curl_easy_perform(curl.get());
  15872. ASSERT_EQ(res, CURLE_OK);
  15873. }
  15874. {
  15875. auto response_code = long{};
  15876. const auto res =
  15877. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  15878. ASSERT_EQ(res, CURLE_OK);
  15879. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  15880. }
  15881. {
  15882. auto dl = curl_off_t{};
  15883. const auto res =
  15884. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  15885. ASSERT_EQ(res, CURLE_OK);
  15886. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  15887. }
  15888. {
  15889. buffer.push_back('\0');
  15890. ASSERT_STRCASEEQ(buffer.data(), reject);
  15891. }
  15892. }
  15893. }
  15894. #endif
  15895. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  15896. // Regression test for #2458.
  15897. //
  15898. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  15899. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  15900. // ticket can make the client socket spuriously readable during the
  15901. // 100-continue wait. If the readiness is mistaken for an incoming response,
  15902. // the client withholds the body and then blocks reading a response that never
  15903. // comes, failing with `Failed to read connection`.
  15904. //
  15905. // A correct client (like curl) sends the body once no `100 Continue` arrives
  15906. // within the timeout. This raw OpenSSL server deliberately never sends
  15907. // `100 Continue`; the client must still deliver the body and receive 200.
  15908. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  15909. signal(SIGPIPE, SIG_IGN);
  15910. const auto port = PORT + 4;
  15911. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15912. ASSERT_NE(srv, INVALID_SOCKET);
  15913. int opt = 1;
  15914. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  15915. sockaddr_in addr{};
  15916. addr.sin_family = AF_INET;
  15917. addr.sin_port = htons(static_cast<uint16_t>(port));
  15918. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15919. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15920. ASSERT_EQ(0, ::listen(srv, 1));
  15921. std::atomic<size_t> server_body_bytes{0};
  15922. auto server_thread = std::thread([&] {
  15923. sockaddr_in cli_addr{};
  15924. socklen_t cli_len = sizeof(cli_addr);
  15925. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15926. if (cli == INVALID_SOCKET) { return; }
  15927. // Bound the lifetime of the server side so a buggy client (which never
  15928. // sends the body) cannot make this thread block forever on join.
  15929. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  15930. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  15931. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  15932. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  15933. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  15934. SSL *ssl = SSL_new(ctx);
  15935. SSL_set_fd(ssl, static_cast<int>(cli));
  15936. if (SSL_accept(ssl) > 0) {
  15937. // Read the request headers. Reading here also flushes the TLS 1.3
  15938. // session tickets to the client. Deliberately do NOT send
  15939. // `100 Continue`.
  15940. std::string buf;
  15941. char tmp[1024];
  15942. while (buf.find("\r\n\r\n") == std::string::npos) {
  15943. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15944. if (n <= 0) { break; }
  15945. buf.append(tmp, static_cast<size_t>(n));
  15946. }
  15947. // A correct client sends the body now; count what arrives.
  15948. auto pos = buf.find("\r\n\r\n");
  15949. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  15950. while (body < 4096) {
  15951. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15952. if (n <= 0) { break; }
  15953. body += static_cast<size_t>(n);
  15954. }
  15955. server_body_bytes = body;
  15956. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  15957. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  15958. SSL_shutdown(ssl);
  15959. }
  15960. SSL_free(ssl);
  15961. detail::close_socket(cli);
  15962. SSL_CTX_free(ctx);
  15963. });
  15964. auto se = detail::scope_exit([&] {
  15965. server_thread.join();
  15966. detail::close_socket(srv);
  15967. });
  15968. SSLClient cli("127.0.0.1", port);
  15969. cli.enable_server_certificate_verification(false);
  15970. cli.set_connection_timeout(5, 0);
  15971. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  15972. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  15973. std::string body(4096, 'A');
  15974. auto res = cli.Put("/api/test", body, "application/json");
  15975. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  15976. EXPECT_EQ(StatusCode::OK_200, res->status);
  15977. EXPECT_EQ(body.size(), server_body_bytes.load());
  15978. }
  15979. #endif
  15980. template <typename S, typename C>
  15981. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  15982. svr.Get("/stream", [&](const Request &, Response &res) {
  15983. auto data = new std::string("01234567890123456789");
  15984. res.set_content_provider(
  15985. data->size(), "text/plain",
  15986. [&, data](size_t offset, size_t length, DataSink &sink) {
  15987. const size_t DATA_CHUNK_SIZE = 4;
  15988. const auto &d = *data;
  15989. std::this_thread::sleep_for(std::chrono::seconds(1));
  15990. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  15991. return true;
  15992. },
  15993. [data](bool success) {
  15994. EXPECT_FALSE(success);
  15995. delete data;
  15996. });
  15997. });
  15998. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  15999. auto i = new size_t(0);
  16000. res.set_content_provider(
  16001. "text/plain",
  16002. [i](size_t, DataSink &sink) {
  16003. if (*i < 5) {
  16004. std::this_thread::sleep_for(std::chrono::seconds(1));
  16005. sink.write("abcd", 4);
  16006. (*i)++;
  16007. } else {
  16008. sink.done();
  16009. }
  16010. return true;
  16011. },
  16012. [i](bool success) {
  16013. EXPECT_FALSE(success);
  16014. delete i;
  16015. });
  16016. });
  16017. svr.Get("/chunked", [&](const Request &, Response &res) {
  16018. auto i = new size_t(0);
  16019. res.set_chunked_content_provider(
  16020. "text/plain",
  16021. [i](size_t, DataSink &sink) {
  16022. if (*i < 5) {
  16023. std::this_thread::sleep_for(std::chrono::seconds(1));
  16024. sink.os << "abcd";
  16025. (*i)++;
  16026. } else {
  16027. sink.done();
  16028. }
  16029. return true;
  16030. },
  16031. [i](bool success) {
  16032. EXPECT_FALSE(success);
  16033. delete i;
  16034. });
  16035. });
  16036. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16037. auto se = detail::scope_exit([&] {
  16038. svr.stop();
  16039. listen_thread.join();
  16040. ASSERT_FALSE(svr.is_running());
  16041. });
  16042. svr.wait_until_ready();
  16043. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  16044. {
  16045. auto start = std::chrono::steady_clock::now();
  16046. auto res = cli.Get("/stream");
  16047. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16048. std::chrono::steady_clock::now() - start)
  16049. .count();
  16050. ASSERT_FALSE(res);
  16051. EXPECT_EQ(Error::Read, res.error());
  16052. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16053. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16054. }
  16055. {
  16056. auto start = std::chrono::steady_clock::now();
  16057. auto res = cli.Get("/stream_without_length");
  16058. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16059. std::chrono::steady_clock::now() - start)
  16060. .count();
  16061. ASSERT_FALSE(res);
  16062. EXPECT_EQ(Error::Read, res.error());
  16063. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16064. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16065. }
  16066. {
  16067. auto start = std::chrono::steady_clock::now();
  16068. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  16069. EXPECT_EQ("abcd", string(data, data_length));
  16070. return true;
  16071. });
  16072. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16073. std::chrono::steady_clock::now() - start)
  16074. .count();
  16075. ASSERT_FALSE(res);
  16076. EXPECT_EQ(Error::Read, res.error());
  16077. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16078. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16079. }
  16080. }
  16081. TEST(MaxTimeoutTest, ContentStream) {
  16082. time_t timeout = 2000;
  16083. time_t threshold = 200;
  16084. Server svr;
  16085. Client cli("localhost", PORT);
  16086. max_timeout_test(svr, cli, timeout, threshold);
  16087. }
  16088. #ifdef CPPHTTPLIB_SSL_ENABLED
  16089. TEST(MaxTimeoutTest, ContentStreamSSL) {
  16090. time_t timeout = 2000;
  16091. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  16092. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16093. SSLClient cli("localhost", PORT);
  16094. cli.enable_server_certificate_verification(false);
  16095. max_timeout_test(svr, cli, timeout, threshold);
  16096. }
  16097. #endif
  16098. class EventDispatcher {
  16099. public:
  16100. EventDispatcher() {}
  16101. bool wait_event(DataSink *sink) {
  16102. unique_lock<mutex> lk(m_);
  16103. int id = id_;
  16104. // Wait with timeout to prevent hanging if client disconnects
  16105. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  16106. [&] { return cid_ == id; })) {
  16107. return false; // Timeout occurred
  16108. }
  16109. sink->write(message_.data(), message_.size());
  16110. return true;
  16111. }
  16112. void send_event(const string &message) {
  16113. lock_guard<mutex> lk(m_);
  16114. cid_ = id_++;
  16115. message_ = message;
  16116. cv_.notify_all();
  16117. }
  16118. private:
  16119. mutex m_;
  16120. condition_variable cv_;
  16121. atomic_int id_{0};
  16122. atomic_int cid_{-1};
  16123. string message_;
  16124. };
  16125. TEST(ClientInThreadTest, Issue2068) {
  16126. EventDispatcher ed;
  16127. Server svr;
  16128. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  16129. res.set_chunked_content_provider("text/event-stream",
  16130. [&](size_t /*offset*/, DataSink &sink) {
  16131. return ed.wait_event(&sink);
  16132. });
  16133. });
  16134. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  16135. svr.wait_until_ready();
  16136. thread event_thread([&] {
  16137. int id = 0;
  16138. while (svr.is_running()) {
  16139. this_thread::sleep_for(chrono::milliseconds(500));
  16140. std::stringstream ss;
  16141. ss << "data: " << id << "\n\n";
  16142. ed.send_event(ss.str());
  16143. id++;
  16144. }
  16145. });
  16146. auto se = detail::scope_exit([&] {
  16147. svr.stop();
  16148. listen_thread.join();
  16149. event_thread.join();
  16150. ASSERT_FALSE(svr.is_running());
  16151. });
  16152. {
  16153. auto client = detail::make_unique<Client>(HOST, PORT);
  16154. client->set_read_timeout(std::chrono::minutes(10));
  16155. std::atomic<bool> stop{false};
  16156. std::thread t([&] {
  16157. client->Get("/event1",
  16158. [&](const char *, size_t) -> bool { return !stop; });
  16159. });
  16160. std::this_thread::sleep_for(std::chrono::seconds(2));
  16161. stop = true;
  16162. client->stop();
  16163. t.join();
  16164. // Reset client after thread has finished
  16165. client.reset();
  16166. }
  16167. }
  16168. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  16169. auto handled = false;
  16170. Server svr;
  16171. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16172. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16173. auto se = detail::scope_exit([&] {
  16174. svr.stop();
  16175. t.join();
  16176. ASSERT_FALSE(svr.is_running());
  16177. ASSERT_FALSE(handled);
  16178. });
  16179. svr.wait_until_ready();
  16180. // Two Content-Length headers with different values — must be rejected
  16181. auto req = "POST /test HTTP/1.1\r\n"
  16182. "Content-Length: 5\r\n"
  16183. "Content-Length: 10\r\n"
  16184. "\r\n"
  16185. "hello";
  16186. std::string response;
  16187. ASSERT_TRUE(send_request(1, req, &response));
  16188. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16189. response.substr(0, response.find("\r\n")));
  16190. }
  16191. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  16192. auto handled = false;
  16193. Server svr;
  16194. svr.Post("/test", [&](const Request &, Response &res) {
  16195. handled = true;
  16196. res.set_content("ok", "text/plain");
  16197. });
  16198. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16199. auto se = detail::scope_exit([&] {
  16200. svr.stop();
  16201. t.join();
  16202. ASSERT_FALSE(svr.is_running());
  16203. ASSERT_TRUE(handled);
  16204. });
  16205. svr.wait_until_ready();
  16206. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  16207. auto req = "POST /test HTTP/1.1\r\n"
  16208. "Content-Length: 5\r\n"
  16209. "Content-Length: 5\r\n"
  16210. "\r\n"
  16211. "hello";
  16212. std::string response;
  16213. ASSERT_TRUE(send_request(1, req, &response));
  16214. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  16215. }
  16216. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  16217. Server svr;
  16218. svr.Get("/", [](const Request &req, Response &res) {
  16219. EXPECT_EQ(2U, req.trailers.size());
  16220. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  16221. // Denied
  16222. EXPECT_FALSE(req.has_trailer("Content-Length"));
  16223. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  16224. // Accepted
  16225. EXPECT_TRUE(req.has_trailer("X-Hello"));
  16226. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  16227. EXPECT_TRUE(req.has_trailer("X-World"));
  16228. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  16229. res.set_content("ok", "text/plain");
  16230. });
  16231. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16232. auto se = detail::scope_exit([&] {
  16233. svr.stop();
  16234. t.join();
  16235. ASSERT_FALSE(svr.is_running());
  16236. });
  16237. svr.wait_until_ready();
  16238. const std::string req = "GET / HTTP/1.1\r\n"
  16239. "Transfer-Encoding: chunked\r\n"
  16240. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  16241. "\r\n"
  16242. "0\r\n"
  16243. "Content-Length: 10\r\n"
  16244. "Host: internal.local\r\n"
  16245. "Content-Type: malicious/content\r\n"
  16246. "Cookie: any\r\n"
  16247. "Set-Cookie: any\r\n"
  16248. "X-Forwarded-For: attacker.com\r\n"
  16249. "X-Real-Ip: 1.1.1.1\r\n"
  16250. "X-Hello: hello\r\n"
  16251. "X-World: world\r\n"
  16252. "\r\n";
  16253. std::string res;
  16254. ASSERT_TRUE(send_request(1, req, &res));
  16255. }
  16256. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  16257. // several field lines, and the combined value is what has to be parsed. A
  16258. // Trailer field split across lines therefore declares every name it lists;
  16259. // reading only the first line silently drops the trailers the later lines
  16260. // declare. The prohibited-trailer filter still applies to every line.
  16261. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  16262. Server svr;
  16263. size_t observed_trailer_count = 0;
  16264. std::string observed_hello;
  16265. std::string observed_world;
  16266. bool observed_content_length = true;
  16267. svr.Get("/", [&](const Request &req, Response &res) {
  16268. observed_trailer_count = req.trailers.size();
  16269. observed_hello = req.get_trailer_value("X-Hello");
  16270. observed_world = req.get_trailer_value("X-World");
  16271. observed_content_length = req.has_trailer("Content-Length");
  16272. res.set_content("ok", "text/plain");
  16273. });
  16274. auto port = svr.bind_to_any_port(HOST);
  16275. thread t = thread([&]() { svr.listen_after_bind(); });
  16276. auto se = detail::scope_exit([&] {
  16277. svr.stop();
  16278. t.join();
  16279. ASSERT_FALSE(svr.is_running());
  16280. });
  16281. svr.wait_until_ready();
  16282. const std::string req = "GET / HTTP/1.1\r\n"
  16283. "Transfer-Encoding: chunked\r\n"
  16284. "Trailer: X-Hello\r\n"
  16285. "Trailer: X-World, Content-Length\r\n"
  16286. "\r\n"
  16287. "0\r\n"
  16288. "X-Hello: hello\r\n"
  16289. "X-World: world\r\n"
  16290. "Content-Length: 10\r\n"
  16291. "\r\n";
  16292. std::string res;
  16293. ASSERT_TRUE(send_request(1, req, &res, port));
  16294. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  16295. // Accepted: both field lines contribute to the declared set
  16296. EXPECT_EQ(2U, observed_trailer_count);
  16297. EXPECT_EQ(observed_hello, "hello");
  16298. EXPECT_EQ(observed_world, "world");
  16299. // Denied: a prohibited name stays prohibited on a later field line
  16300. EXPECT_FALSE(observed_content_length);
  16301. }
  16302. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  16303. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  16304. // unbounded run of fields that are never declared, because the counter would
  16305. // only advance for declared fields.
  16306. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  16307. Server svr;
  16308. bool handler_called = false;
  16309. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  16310. handler_called = true;
  16311. res.set_content("ok", "text/plain");
  16312. });
  16313. auto port = svr.bind_to_any_port(HOST);
  16314. thread t = thread([&]() { svr.listen_after_bind(); });
  16315. auto se = detail::scope_exit([&] {
  16316. svr.stop();
  16317. t.join();
  16318. ASSERT_FALSE(svr.is_running());
  16319. });
  16320. svr.wait_until_ready();
  16321. // Declare nothing, then send far more undeclared trailer fields than the
  16322. // header-count limit. Parsing must stop and reject the request rather than
  16323. // read every line.
  16324. std::string req = "GET / HTTP/1.1\r\n"
  16325. "Transfer-Encoding: chunked\r\n"
  16326. "\r\n"
  16327. "0\r\n";
  16328. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  16329. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  16330. }
  16331. req += "\r\n";
  16332. std::string res;
  16333. ASSERT_TRUE(send_request(1, req, &res, port));
  16334. // The request is rejected before the handler runs.
  16335. EXPECT_FALSE(handler_called);
  16336. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  16337. }
  16338. // The set of declared trailer names is capped so a peer cannot grow it without
  16339. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  16340. // declared past the cap is not honored, even if the field is actually sent.
  16341. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  16342. Server svr;
  16343. // One name inside the cap and one past it, so the test tracks the cap rather
  16344. // than a fixed count.
  16345. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  16346. const std::string within_cap_name = "X-T-0";
  16347. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  16348. bool observed_within_cap = false;
  16349. bool observed_past_cap = false;
  16350. svr.Get("/", [&](const Request &req, Response &res) {
  16351. observed_within_cap = req.has_trailer(within_cap_name);
  16352. observed_past_cap = req.has_trailer(past_cap_name);
  16353. res.set_content("ok", "text/plain");
  16354. });
  16355. auto port = svr.bind_to_any_port(HOST);
  16356. thread t = thread([&]() { svr.listen_after_bind(); });
  16357. auto se = detail::scope_exit([&] {
  16358. svr.stop();
  16359. t.join();
  16360. ASSERT_FALSE(svr.is_running());
  16361. });
  16362. svr.wait_until_ready();
  16363. // Declare more trailer names than the cap in a single Trailer field, then
  16364. // actually send the first (within the cap) and the last (past it).
  16365. std::string trailer_decl = "Trailer: ";
  16366. for (int i = 0; i < declared_count; i++) {
  16367. if (i != 0) { trailer_decl += ", "; }
  16368. trailer_decl += "X-T-" + std::to_string(i);
  16369. }
  16370. trailer_decl += "\r\n";
  16371. const std::string req = "GET / HTTP/1.1\r\n"
  16372. "Transfer-Encoding: chunked\r\n" +
  16373. trailer_decl +
  16374. "\r\n"
  16375. "0\r\n" +
  16376. within_cap_name + ": a\r\n" + past_cap_name +
  16377. ": b\r\n"
  16378. "\r\n";
  16379. std::string res;
  16380. ASSERT_TRUE(send_request(1, req, &res, port));
  16381. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  16382. // A name within the cap is honored; one declared past the cap is dropped.
  16383. EXPECT_TRUE(observed_within_cap);
  16384. EXPECT_FALSE(observed_past_cap);
  16385. }
  16386. // A direct client that is not listed in trusted_proxies must not be able to
  16387. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  16388. // the peer address on the actual TCP connection determines whether the
  16389. // header is honored.
  16390. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  16391. Server svr;
  16392. // Deliberately does NOT include the loopback address the test client
  16393. // actually connects from, so the direct connection is not a trusted proxy.
  16394. svr.set_trusted_proxies({"203.0.113.66"});
  16395. std::string observed_remote_addr;
  16396. svr.Get("/ip", [&](const Request &req, Response &res) {
  16397. observed_remote_addr = req.remote_addr;
  16398. res.set_content("ok", "text/plain");
  16399. });
  16400. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16401. auto se = detail::scope_exit([&] {
  16402. svr.stop();
  16403. t.join();
  16404. ASSERT_FALSE(svr.is_running());
  16405. });
  16406. svr.wait_until_ready();
  16407. Client cli(HOST, PORT);
  16408. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  16409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16410. EXPECT_EQ(StatusCode::OK_200, res->status);
  16411. // The connecting peer is not a trusted proxy, so the spoofed header must be
  16412. // ignored entirely and the real connection-level address retained.
  16413. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16414. observed_remote_addr == "127.0.0.1");
  16415. }
  16416. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  16417. Server svr;
  16418. std::string observed_remote_addr;
  16419. std::string observed_xff;
  16420. svr.Get("/ip", [&](const Request &req, Response &res) {
  16421. observed_remote_addr = req.remote_addr;
  16422. observed_xff = req.get_header_value("X-Forwarded-For");
  16423. res.set_content("ok", "text/plain");
  16424. });
  16425. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16426. auto se = detail::scope_exit([&] {
  16427. svr.stop();
  16428. t.join();
  16429. ASSERT_FALSE(svr.is_running());
  16430. });
  16431. svr.wait_until_ready();
  16432. Client cli(HOST, PORT);
  16433. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  16434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16435. EXPECT_EQ(StatusCode::OK_200, res->status);
  16436. EXPECT_EQ(observed_xff, "203.0.113.66");
  16437. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16438. observed_remote_addr == "127.0.0.1");
  16439. }
  16440. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  16441. Server svr;
  16442. svr.set_trusted_proxies({"203.0.113.66"});
  16443. std::string observed_remote_addr;
  16444. std::string observed_xff;
  16445. svr.Get("/ip", [&](const Request &req, Response &res) {
  16446. observed_remote_addr = req.remote_addr;
  16447. observed_xff = req.get_header_value("X-Forwarded-For");
  16448. res.set_content("ok", "text/plain");
  16449. });
  16450. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16451. auto se = detail::scope_exit([&] {
  16452. svr.stop();
  16453. t.join();
  16454. ASSERT_FALSE(svr.is_running());
  16455. });
  16456. svr.wait_until_ready();
  16457. Client cli(HOST, PORT);
  16458. auto res = cli.Get("/ip");
  16459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16460. EXPECT_EQ(StatusCode::OK_200, res->status);
  16461. EXPECT_EQ(observed_xff, "");
  16462. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16463. observed_remote_addr == "127.0.0.1");
  16464. }
  16465. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  16466. Server svr;
  16467. // Include the loopback address the test client actually connects from, so
  16468. // the direct connection itself is recognized as the trusted proxy hop.
  16469. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  16470. std::string observed_remote_addr;
  16471. std::string observed_xff;
  16472. svr.Get("/ip", [&](const Request &req, Response &res) {
  16473. observed_remote_addr = req.remote_addr;
  16474. observed_xff = req.get_header_value("X-Forwarded-For");
  16475. res.set_content("ok", "text/plain");
  16476. });
  16477. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16478. auto se = detail::scope_exit([&] {
  16479. svr.stop();
  16480. t.join();
  16481. ASSERT_FALSE(svr.is_running());
  16482. });
  16483. svr.wait_until_ready();
  16484. Client cli(HOST, PORT);
  16485. auto res = cli.Get(
  16486. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  16487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16488. EXPECT_EQ(StatusCode::OK_200, res->status);
  16489. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  16490. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16491. }
  16492. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  16493. Server svr;
  16494. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  16495. std::string observed_remote_addr;
  16496. std::string observed_xff;
  16497. svr.Get("/ip", [&](const Request &req, Response &res) {
  16498. observed_remote_addr = req.remote_addr;
  16499. observed_xff = req.get_header_value("X-Forwarded-For");
  16500. res.set_content("ok", "text/plain");
  16501. });
  16502. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16503. auto se = detail::scope_exit([&] {
  16504. svr.stop();
  16505. t.join();
  16506. ASSERT_FALSE(svr.is_running());
  16507. });
  16508. svr.wait_until_ready();
  16509. Client cli(HOST, PORT);
  16510. auto res = cli.Get(
  16511. "/ip",
  16512. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16514. EXPECT_EQ(StatusCode::OK_200, res->status);
  16515. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16516. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16517. }
  16518. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  16519. Server svr;
  16520. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16521. std::string observed_remote_addr;
  16522. std::string observed_xff;
  16523. svr.Get("/ip", [&](const Request &req, Response &res) {
  16524. observed_remote_addr = req.remote_addr;
  16525. observed_xff = req.get_header_value("X-Forwarded-For");
  16526. res.set_content("ok", "text/plain");
  16527. });
  16528. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16529. auto se = detail::scope_exit([&] {
  16530. svr.stop();
  16531. t.join();
  16532. ASSERT_FALSE(svr.is_running());
  16533. });
  16534. svr.wait_until_ready();
  16535. Client cli(HOST, PORT);
  16536. auto res = cli.Get(
  16537. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  16538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16539. EXPECT_EQ(StatusCode::OK_200, res->status);
  16540. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  16541. // by the closest hop) is used. The leftmost entry is fully client-controlled
  16542. // and must not be selected.
  16543. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  16544. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  16545. }
  16546. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  16547. Server svr;
  16548. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  16549. std::string observed_remote_addr;
  16550. svr.Get("/ip", [&](const Request &req, Response &res) {
  16551. observed_remote_addr = req.remote_addr;
  16552. res.set_content("ok", "text/plain");
  16553. });
  16554. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16555. auto se = detail::scope_exit([&] {
  16556. svr.stop();
  16557. t.join();
  16558. ASSERT_FALSE(svr.is_running());
  16559. });
  16560. svr.wait_until_ready();
  16561. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  16562. // a forged address and the trusted proxy's own address; the forged value must
  16563. // not win over the address the trusted proxy actually recorded.
  16564. Client cli(HOST, PORT);
  16565. auto res = cli.Get(
  16566. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  16567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16568. EXPECT_EQ(StatusCode::OK_200, res->status);
  16569. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  16570. }
  16571. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  16572. Server svr;
  16573. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16574. std::string observed_remote_addr;
  16575. std::string observed_xff;
  16576. svr.Get("/ip", [&](const Request &req, Response &res) {
  16577. observed_remote_addr = req.remote_addr;
  16578. observed_xff = req.get_header_value("X-Forwarded-For");
  16579. res.set_content("ok", "text/plain");
  16580. });
  16581. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16582. auto se = detail::scope_exit([&] {
  16583. svr.stop();
  16584. t.join();
  16585. ASSERT_FALSE(svr.is_running());
  16586. });
  16587. svr.wait_until_ready();
  16588. Client cli(HOST, PORT);
  16589. auto res = cli.Get(
  16590. "/ip",
  16591. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16593. EXPECT_EQ(StatusCode::OK_200, res->status);
  16594. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16595. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16596. }
  16597. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  16598. Server svr;
  16599. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16600. std::string observed_remote_addr;
  16601. std::string observed_xff;
  16602. svr.Get("/ip", [&](const Request &req, Response &res) {
  16603. observed_remote_addr = req.remote_addr;
  16604. observed_xff = req.get_header_value("X-Forwarded-For");
  16605. res.set_content("ok", "text/plain");
  16606. });
  16607. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16608. auto se = detail::scope_exit([&] {
  16609. svr.stop();
  16610. t.join();
  16611. ASSERT_FALSE(svr.is_running());
  16612. });
  16613. svr.wait_until_ready();
  16614. std::string raw_req =
  16615. "GET /ip HTTP/1.1\r\n"
  16616. "Host: localhost\r\n"
  16617. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  16618. "Connection: close\r\n"
  16619. "\r\n";
  16620. std::string out;
  16621. ASSERT_TRUE(send_request(5, raw_req, &out));
  16622. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16623. // Header parser trims surrounding whitespace of the header value
  16624. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  16625. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16626. }
  16627. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  16628. // one comma-joined value, in the order received. Proxies such as HAProxy append
  16629. // their own X-Forwarded-For as a separate field line rather than extending the
  16630. // one the client sent, so every occurrence has to be taken into account.
  16631. // Reading only the first one hands back the address the client chose.
  16632. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  16633. Server svr;
  16634. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16635. std::string observed_remote_addr;
  16636. size_t observed_xff_count = 0;
  16637. svr.Get("/ip", [&](const Request &req, Response &res) {
  16638. observed_remote_addr = req.remote_addr;
  16639. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  16640. res.set_content("ok", "text/plain");
  16641. });
  16642. auto port = svr.bind_to_any_port(HOST);
  16643. thread t = thread([&]() { svr.listen_after_bind(); });
  16644. auto se = detail::scope_exit([&] {
  16645. svr.stop();
  16646. t.join();
  16647. ASSERT_FALSE(svr.is_running());
  16648. });
  16649. svr.wait_until_ready();
  16650. // The client supplies the first field line; the trusted proxy appends the
  16651. // address it observed as a second one.
  16652. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  16653. "Host: localhost\r\n"
  16654. "X-Forwarded-For: 1.2.3.4\r\n"
  16655. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  16656. "Connection: close\r\n"
  16657. "\r\n";
  16658. std::string out;
  16659. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16660. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16661. EXPECT_EQ(observed_xff_count, 2U);
  16662. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16663. // The same chain spread over one field line per hop derives the same client
  16664. // address, i.e. the split and the comma-joined representations agree.
  16665. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  16666. "Host: localhost\r\n"
  16667. "X-Forwarded-For: 1.2.3.4\r\n"
  16668. "X-Forwarded-For: 198.51.100.23\r\n"
  16669. "X-Forwarded-For: 192.0.2.45\r\n"
  16670. "Connection: close\r\n"
  16671. "\r\n";
  16672. out.clear();
  16673. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  16674. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16675. EXPECT_EQ(observed_xff_count, 3U);
  16676. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16677. }
  16678. // An X-Forwarded-For header whose value parses to zero IP segments must not
  16679. // crash the server (it used to call front() on an empty vector inside
  16680. // get_client_ip). The connection-level remote address must be retained instead.
  16681. static void run_malformed_xff_test(const std::string &xff_value) {
  16682. Server svr;
  16683. svr.set_trusted_proxies({"192.0.2.45"});
  16684. std::string observed_remote_addr;
  16685. svr.Get("/ip", [&](const Request &req, Response &res) {
  16686. observed_remote_addr = req.remote_addr;
  16687. res.set_content("ok", "text/plain");
  16688. });
  16689. int port = 0;
  16690. thread t = thread([&]() {
  16691. port = svr.bind_to_any_port(HOST);
  16692. svr.listen_after_bind();
  16693. });
  16694. auto se = detail::scope_exit([&] {
  16695. svr.stop();
  16696. t.join();
  16697. ASSERT_FALSE(svr.is_running());
  16698. });
  16699. svr.wait_until_ready();
  16700. Client cli(HOST, port);
  16701. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  16702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16703. EXPECT_EQ(StatusCode::OK_200, res->status);
  16704. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16705. observed_remote_addr == "127.0.0.1");
  16706. }
  16707. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  16708. run_malformed_xff_test("");
  16709. }
  16710. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  16711. run_malformed_xff_test(",");
  16712. }
  16713. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  16714. run_malformed_xff_test(", , ,");
  16715. }
  16716. // The same rule applies to Accept: a request whose acceptable types are spread
  16717. // over several field lines must be negotiated against all of them.
  16718. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  16719. // case-insensitive connection options. Comparing the whole field value against
  16720. // one option misses a client that sends several of them, and misses every
  16721. // casing but the one written in the comparison.
  16722. //
  16723. // Sends req, reads the response, then reuses the same socket for a second
  16724. // request to find out whether the server kept the connection.
  16725. static void probe_connection_reuse(int port, const std::string &req,
  16726. bool *announced_close, bool *reusable) {
  16727. auto error = Error::Success;
  16728. auto sock = detail::create_client_socket(
  16729. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16730. /*connection_timeout_sec=*/5, 0,
  16731. /*read_timeout_sec=*/1, 0,
  16732. /*write_timeout_sec=*/5, 0, std::string(), error);
  16733. ASSERT_NE(sock, INVALID_SOCKET);
  16734. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  16735. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  16736. "Host: localhost\r\n"
  16737. "Connection: close\r\n"
  16738. "\r\n";
  16739. std::string first_response;
  16740. std::string second_response;
  16741. detail::process_client_socket(
  16742. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  16743. [&](Stream &strm) {
  16744. if (strm.write(req.data(), req.size()) !=
  16745. static_cast<ssize_t>(req.size())) {
  16746. return false;
  16747. }
  16748. char buf[512];
  16749. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  16750. // Headers plus the two-byte body of the handler below
  16751. while (reader.getline()) {
  16752. first_response += reader.ptr();
  16753. if (first_response.find("ok") != std::string::npos) { break; }
  16754. }
  16755. if (strm.write(second.data(), second.size()) !=
  16756. static_cast<ssize_t>(second.size())) {
  16757. return true;
  16758. }
  16759. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  16760. while (reader2.getline()) {
  16761. second_response += reader2.ptr();
  16762. if (second_response.find("ok") != std::string::npos) { break; }
  16763. }
  16764. return true;
  16765. });
  16766. *announced_close =
  16767. first_response.find("Connection: close") != std::string::npos;
  16768. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  16769. }
  16770. class ConnectionTokenTest : public ::testing::Test {
  16771. protected:
  16772. void SetUp() override {
  16773. svr_.Get("/keepalive", [](const Request &, Response &res) {
  16774. res.set_content("ok", "text/plain");
  16775. });
  16776. port_ = svr_.bind_to_any_port(HOST);
  16777. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16778. svr_.wait_until_ready();
  16779. }
  16780. void TearDown() override {
  16781. svr_.stop();
  16782. if (thread_.joinable()) { thread_.join(); }
  16783. }
  16784. Server svr_;
  16785. int port_ = 0;
  16786. thread thread_;
  16787. };
  16788. // "close" alongside another option still closes the connection, and the
  16789. // response says so rather than leaving the peer to discover it.
  16790. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  16791. bool announced_close = false;
  16792. bool reusable = true;
  16793. probe_connection_reuse(port_,
  16794. "GET /keepalive HTTP/1.1\r\n"
  16795. "Host: localhost\r\n"
  16796. "Connection: keep-alive, close\r\n"
  16797. "\r\n",
  16798. &announced_close, &reusable);
  16799. EXPECT_TRUE(announced_close);
  16800. EXPECT_FALSE(reusable);
  16801. }
  16802. // "close" split over two field lines is the same list, so it is honored too.
  16803. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  16804. bool announced_close = false;
  16805. bool reusable = true;
  16806. probe_connection_reuse(port_,
  16807. "GET /keepalive HTTP/1.1\r\n"
  16808. "Host: localhost\r\n"
  16809. "Connection: keep-alive\r\n"
  16810. "Connection: close\r\n"
  16811. "\r\n",
  16812. &announced_close, &reusable);
  16813. EXPECT_TRUE(announced_close);
  16814. EXPECT_FALSE(reusable);
  16815. }
  16816. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  16817. // keep-alive in the spelling everyone actually sends keeps its connection.
  16818. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  16819. bool announced_close = false;
  16820. bool reusable = false;
  16821. probe_connection_reuse(port_,
  16822. "GET /keepalive HTTP/1.0\r\n"
  16823. "Host: localhost\r\n"
  16824. "Connection: keep-alive\r\n"
  16825. "\r\n",
  16826. &announced_close, &reusable);
  16827. EXPECT_FALSE(announced_close);
  16828. EXPECT_TRUE(reusable);
  16829. }
  16830. // A token the value merely contains is not the token itself.
  16831. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  16832. bool announced_close = false;
  16833. bool reusable = false;
  16834. probe_connection_reuse(port_,
  16835. "GET /keepalive HTTP/1.1\r\n"
  16836. "Host: localhost\r\n"
  16837. "Connection: notclose\r\n"
  16838. "\r\n",
  16839. &announced_close, &reusable);
  16840. EXPECT_FALSE(announced_close);
  16841. EXPECT_TRUE(reusable);
  16842. }
  16843. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  16844. Server svr;
  16845. std::vector<std::string> observed_types;
  16846. svr.Get("/", [&](const Request &req, Response &res) {
  16847. observed_types = req.accept_content_types;
  16848. res.set_content("ok", "text/plain");
  16849. });
  16850. auto port = svr.bind_to_any_port(HOST);
  16851. thread t = thread([&]() { svr.listen_after_bind(); });
  16852. auto se = detail::scope_exit([&] {
  16853. svr.stop();
  16854. t.join();
  16855. ASSERT_FALSE(svr.is_running());
  16856. });
  16857. svr.wait_until_ready();
  16858. Client cli(HOST, port);
  16859. Headers headers;
  16860. headers.emplace("Accept", "text/plain;q=0.5");
  16861. headers.emplace("Accept", "application/json");
  16862. auto res = cli.Get("/", headers);
  16863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16864. EXPECT_EQ(StatusCode::OK_200, res->status);
  16865. // Sorted by q-value, so the second field line's type comes first
  16866. ASSERT_EQ(2U, observed_types.size());
  16867. EXPECT_EQ("application/json", observed_types[0]);
  16868. EXPECT_EQ("text/plain", observed_types[1]);
  16869. }
  16870. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  16871. // empty field line must not contribute a bare comma to the combined value.
  16872. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  16873. Server svr;
  16874. std::vector<std::string> observed_types;
  16875. svr.Get("/", [&](const Request &req, Response &res) {
  16876. observed_types = req.accept_content_types;
  16877. res.set_content("ok", "text/plain");
  16878. });
  16879. auto port = svr.bind_to_any_port(HOST);
  16880. thread t = thread([&]() { svr.listen_after_bind(); });
  16881. auto se = detail::scope_exit([&] {
  16882. svr.stop();
  16883. t.join();
  16884. ASSERT_FALSE(svr.is_running());
  16885. });
  16886. svr.wait_until_ready();
  16887. // Empty first field line, then a real one
  16888. std::string raw_req = "GET / HTTP/1.1\r\n"
  16889. "Host: localhost\r\n"
  16890. "Accept:\r\n"
  16891. "Accept: application/json\r\n"
  16892. "Connection: close\r\n"
  16893. "\r\n";
  16894. std::string out;
  16895. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16896. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16897. ASSERT_EQ(1U, observed_types.size());
  16898. EXPECT_EQ("application/json", observed_types[0]);
  16899. }
  16900. // The skip in get_combined_header_value() is what keeps an empty field line
  16901. // from contributing a bare comma. Only a trailing empty field line exercises
  16902. // it: a leading one is already covered by the "combined is still empty" check,
  16903. // and parse_accept_header() now ignores the empty element either way, so the
  16904. // request-level test above can no longer tell the two apart.
  16905. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  16906. Headers headers;
  16907. headers.emplace("Accept", "text/html");
  16908. headers.emplace("Accept", "");
  16909. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  16910. headers.clear();
  16911. headers.emplace("Accept", "");
  16912. headers.emplace("Accept", "application/json");
  16913. EXPECT_EQ("application/json",
  16914. detail::get_combined_header_value(headers, "Accept"));
  16915. }
  16916. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16917. // An encoding offered on a later Accept-Encoding field line is still offered.
  16918. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  16919. Server svr;
  16920. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16921. res.set_content(std::string(1024, 'x'), "text/plain");
  16922. });
  16923. auto port = svr.bind_to_any_port(HOST);
  16924. thread t = thread([&]() { svr.listen_after_bind(); });
  16925. auto se = detail::scope_exit([&] {
  16926. svr.stop();
  16927. t.join();
  16928. ASSERT_FALSE(svr.is_running());
  16929. });
  16930. svr.wait_until_ready();
  16931. Client cli(HOST, port);
  16932. cli.set_decompress(false);
  16933. Headers headers;
  16934. headers.emplace("Accept-Encoding", "identity");
  16935. headers.emplace("Accept-Encoding", "gzip");
  16936. auto res = cli.Get("/", headers);
  16937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16938. EXPECT_EQ(StatusCode::OK_200, res->status);
  16939. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  16940. }
  16941. #endif
  16942. #ifndef _WIN32
  16943. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  16944. Server svr;
  16945. svr.Post("/post", [&](const Request &req, Response &res) {
  16946. res.set_content(req.body, "text/plain");
  16947. });
  16948. svr.Put("/put", [&](const Request &req, Response &res) {
  16949. res.set_content(req.body, "text/plain");
  16950. });
  16951. svr.Patch("/patch", [&](const Request &req, Response &res) {
  16952. res.set_content(req.body, "text/plain");
  16953. });
  16954. svr.Delete("/delete", [&](const Request &req, Response &res) {
  16955. res.set_content(req.body, "text/plain");
  16956. });
  16957. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16958. auto se = detail::scope_exit([&] {
  16959. svr.stop();
  16960. t.join();
  16961. ASSERT_FALSE(svr.is_running());
  16962. });
  16963. svr.wait_until_ready();
  16964. std::string resp;
  16965. // POST without Content-Length
  16966. ASSERT_TRUE(send_request(5,
  16967. "POST /post HTTP/1.1\r\n"
  16968. "Host: localhost\r\n"
  16969. "Connection: close\r\n"
  16970. "\r\n",
  16971. &resp));
  16972. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16973. // PUT without Content-Length
  16974. resp.clear();
  16975. ASSERT_TRUE(send_request(5,
  16976. "PUT /put HTTP/1.1\r\n"
  16977. "Host: localhost\r\n"
  16978. "Connection: close\r\n"
  16979. "\r\n",
  16980. &resp));
  16981. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16982. // PATCH without Content-Length
  16983. resp.clear();
  16984. ASSERT_TRUE(send_request(5,
  16985. "PATCH /patch HTTP/1.1\r\n"
  16986. "Host: localhost\r\n"
  16987. "Connection: close\r\n"
  16988. "\r\n",
  16989. &resp));
  16990. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16991. // DELETE without Content-Length
  16992. resp.clear();
  16993. ASSERT_TRUE(send_request(5,
  16994. "DELETE /delete HTTP/1.1\r\n"
  16995. "Host: localhost\r\n"
  16996. "Connection: close\r\n"
  16997. "\r\n",
  16998. &resp));
  16999. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17000. }
  17001. #endif
  17002. //==============================================================================
  17003. // open_stream() Tests
  17004. //==============================================================================
  17005. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  17006. std::string result;
  17007. char buf[8192];
  17008. ssize_t n;
  17009. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17010. result.append(buf, static_cast<size_t>(n));
  17011. }
  17012. return result;
  17013. }
  17014. // Mock stream for unit tests
  17015. class MockStream : public Stream {
  17016. public:
  17017. std::string data;
  17018. size_t pos = 0;
  17019. ssize_t error_after = -1; // -1 = no error
  17020. explicit MockStream(const std::string &d, ssize_t err = -1)
  17021. : data(d), error_after(err) {}
  17022. bool is_readable() const override { return true; }
  17023. bool wait_readable() const override { return true; }
  17024. bool wait_writable() const override { return true; }
  17025. ssize_t read(char *ptr, size_t size) override {
  17026. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  17027. if (pos >= data.size()) return 0;
  17028. size_t limit =
  17029. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  17030. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  17031. std::memcpy(ptr, data.data() + pos, to_read);
  17032. pos += to_read;
  17033. return static_cast<ssize_t>(to_read);
  17034. }
  17035. ssize_t write(const char *, size_t) override { return -1; }
  17036. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  17037. ip = "127.0.0.1";
  17038. port = 0;
  17039. }
  17040. void get_local_ip_and_port(std::string &ip, int &port) const override {
  17041. ip = "127.0.0.1";
  17042. port = 0;
  17043. }
  17044. socket_t socket() const override { return INVALID_SOCKET; }
  17045. time_t duration() const override { return 0; }
  17046. };
  17047. TEST(StreamHandleTest, Basic) {
  17048. ClientImpl::StreamHandle handle;
  17049. EXPECT_FALSE(handle.is_valid());
  17050. handle.response = detail::make_unique<Response>();
  17051. handle.error = Error::Connection;
  17052. EXPECT_FALSE(handle.is_valid());
  17053. handle.error = Error::Success;
  17054. EXPECT_TRUE(handle.is_valid());
  17055. }
  17056. TEST(BodyReaderTest, Basic) {
  17057. MockStream stream("Hello, World!");
  17058. detail::BodyReader reader;
  17059. reader.stream = &stream;
  17060. reader.content_length = 13;
  17061. char buf[32];
  17062. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  17063. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  17064. EXPECT_TRUE(reader.eof);
  17065. }
  17066. TEST(BodyReaderTest, NoStream) {
  17067. detail::BodyReader reader;
  17068. char buf[32];
  17069. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17070. EXPECT_EQ(Error::Connection, reader.last_error);
  17071. }
  17072. TEST(BodyReaderTest, Error) {
  17073. MockStream stream("Hello, World!", 5);
  17074. detail::BodyReader reader;
  17075. reader.stream = &stream;
  17076. reader.content_length = 13;
  17077. char buf[32];
  17078. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  17079. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17080. EXPECT_EQ(Error::Read, reader.last_error);
  17081. }
  17082. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  17083. // Mock-based StreamHandle tests relying on private internals are removed.
  17084. class OpenStreamTest : public ::testing::Test {
  17085. protected:
  17086. void SetUp() override {
  17087. svr_.Get("/hello", [](const Request &, Response &res) {
  17088. res.set_content("Hello World!", "text/plain");
  17089. });
  17090. svr_.Get("/large", [](const Request &, Response &res) {
  17091. res.set_content(std::string(10000, 'X'), "text/plain");
  17092. });
  17093. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  17094. res.set_content("Hello World!", "image/jpeg");
  17095. res.set_header("Content-Encoding", "UTF-8");
  17096. });
  17097. svr_.Get("/chunked", [](const Request &, Response &res) {
  17098. res.set_chunked_content_provider("text/plain",
  17099. [](size_t offset, DataSink &sink) {
  17100. if (offset < 15) {
  17101. sink.write("chunk", 5);
  17102. return true;
  17103. }
  17104. sink.done();
  17105. return true;
  17106. });
  17107. });
  17108. svr_.Get("/compressible", [](const Request &, Response &res) {
  17109. res.set_chunked_content_provider("text/plain", [](size_t offset,
  17110. DataSink &sink) {
  17111. if (offset < 100 * 1024) {
  17112. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  17113. sink.write(chunk.data(), chunk.size());
  17114. return true;
  17115. }
  17116. sink.done();
  17117. return true;
  17118. });
  17119. });
  17120. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  17121. [](const Request & /*req*/, Response &res) {
  17122. auto i = new int(0);
  17123. res.set_header("Trailer", "Content-Length, X-Allowed");
  17124. res.set_chunked_content_provider(
  17125. "text/plain",
  17126. [i](size_t /*offset*/, DataSink &sink) {
  17127. switch (*i) {
  17128. case 0: sink.os << "123"; break;
  17129. case 1: sink.os << "456"; break;
  17130. case 2: sink.os << "789"; break;
  17131. case 3: {
  17132. sink.done_with_trailer(
  17133. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  17134. } break;
  17135. }
  17136. (*i)++;
  17137. return true;
  17138. },
  17139. [i](bool success) {
  17140. EXPECT_TRUE(success);
  17141. delete i;
  17142. });
  17143. });
  17144. // Echo headers endpoint for header-related tests
  17145. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  17146. std::string body;
  17147. for (const auto &h : req.headers) {
  17148. body.append(h.first);
  17149. body.push_back(':');
  17150. body.append(h.second);
  17151. body.push_back('\n');
  17152. }
  17153. res.set_content(body, "text/plain");
  17154. });
  17155. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  17156. std::string body;
  17157. for (const auto &h : req.headers) {
  17158. body.append(h.first);
  17159. body.push_back(':');
  17160. body.append(h.second);
  17161. body.push_back('\n');
  17162. }
  17163. res.set_content(body, "text/plain");
  17164. });
  17165. port_ = svr_.bind_to_any_port("127.0.0.1");
  17166. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17167. svr_.wait_until_ready();
  17168. }
  17169. void TearDown() override {
  17170. svr_.stop();
  17171. if (thread_.joinable()) thread_.join();
  17172. }
  17173. Server svr_;
  17174. std::thread thread_;
  17175. int port_ = 0;
  17176. };
  17177. TEST_F(OpenStreamTest, Basic) {
  17178. Client cli("127.0.0.1", port_);
  17179. auto handle = cli.open_stream("GET", "/hello");
  17180. EXPECT_TRUE(handle.is_valid());
  17181. EXPECT_EQ("Hello World!", read_all(handle));
  17182. }
  17183. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  17184. Client cli("127.0.0.1", port_);
  17185. auto handle = cli.open_stream("GET", "/unknown-encoding");
  17186. ASSERT_TRUE(handle.is_valid());
  17187. EXPECT_EQ("Hello World!", read_all(handle));
  17188. }
  17189. TEST_F(OpenStreamTest, SmallBuffer) {
  17190. Client cli("127.0.0.1", port_);
  17191. auto handle = cli.open_stream("GET", "/hello");
  17192. std::string result;
  17193. char buf[4];
  17194. ssize_t n;
  17195. while ((n = handle.read(buf, sizeof(buf))) > 0)
  17196. result.append(buf, static_cast<size_t>(n));
  17197. EXPECT_EQ("Hello World!", result);
  17198. }
  17199. TEST_F(OpenStreamTest, DefaultHeaders) {
  17200. Client cli("127.0.0.1", port_);
  17201. // open_stream GET should include Host, User-Agent and Accept-Encoding
  17202. {
  17203. auto handle = cli.open_stream("GET", "/echo-headers");
  17204. ASSERT_TRUE(handle.is_valid());
  17205. auto body = read_all(handle);
  17206. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  17207. std::string::npos);
  17208. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  17209. std::string::npos);
  17210. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  17211. }
  17212. // open_stream POST with body and no explicit content_type should NOT add
  17213. // text/plain Content-Type (behavior differs from non-streaming path), but
  17214. // should include Content-Length
  17215. {
  17216. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  17217. ASSERT_TRUE(handle.is_valid());
  17218. auto body = read_all(handle);
  17219. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  17220. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  17221. }
  17222. // open_stream POST with explicit Content-Type should preserve it
  17223. {
  17224. auto handle = cli.open_stream("POST", "/echo-headers", {},
  17225. {{"Content-Type", "application/custom"}},
  17226. "{}", "application/custom");
  17227. ASSERT_TRUE(handle.is_valid());
  17228. auto body = read_all(handle);
  17229. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  17230. }
  17231. // User-specified User-Agent must not be overwritten for stream API
  17232. {
  17233. auto handle = cli.open_stream("GET", "/echo-headers", {},
  17234. {{"User-Agent", "MyAgent/1.2"}});
  17235. ASSERT_TRUE(handle.is_valid());
  17236. auto body = read_all(handle);
  17237. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  17238. }
  17239. }
  17240. TEST_F(OpenStreamTest, Large) {
  17241. Client cli("127.0.0.1", port_);
  17242. auto handle = cli.open_stream("GET", "/large");
  17243. EXPECT_EQ(10000u, read_all(handle).size());
  17244. }
  17245. TEST_F(OpenStreamTest, ConnectionError) {
  17246. Client cli("127.0.0.1", 9999);
  17247. auto handle = cli.open_stream("GET", "/hello");
  17248. EXPECT_FALSE(handle.is_valid());
  17249. }
  17250. TEST_F(OpenStreamTest, Chunked) {
  17251. Client cli("127.0.0.1", port_);
  17252. auto handle = cli.open_stream("GET", "/chunked");
  17253. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17254. "Transfer-Encoding") == "chunked");
  17255. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  17256. }
  17257. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  17258. Client cli("127.0.0.1", port_);
  17259. auto handle =
  17260. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  17261. ASSERT_TRUE(handle.is_valid());
  17262. // Consume body to allow trailers to be received/parsed
  17263. auto body = read_all(handle);
  17264. // Explicitly parse trailers (ensure trailers are available for assertion)
  17265. handle.parse_trailers_if_needed();
  17266. EXPECT_EQ(std::string("123456789"), body);
  17267. // The response should include a Trailer header declaring both names
  17268. ASSERT_TRUE(handle.response);
  17269. EXPECT_TRUE(handle.response->has_header("Trailer"));
  17270. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  17271. handle.response->get_header_value("Trailer"));
  17272. // Prohibited trailer must not be present
  17273. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  17274. // Allowed trailer should be present
  17275. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  17276. EXPECT_EQ(std::string("yes"),
  17277. handle.response->get_trailer_value("X-Allowed"));
  17278. // Verify trailers are NOT present as regular headers
  17279. EXPECT_EQ(std::string(""),
  17280. handle.response->get_header_value("Content-Length"));
  17281. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  17282. }
  17283. static std::thread serve_single_response(std::promise<int> &port_promise,
  17284. const std::string &response) {
  17285. return std::thread([&port_promise, response] {
  17286. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17287. default_socket_options(srv);
  17288. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17289. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  17290. sockaddr_in addr{};
  17291. addr.sin_family = AF_INET;
  17292. addr.sin_port = htons(0); // Let OS assign a free port
  17293. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17294. int opt = 1;
  17295. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  17296. #ifdef _WIN32
  17297. reinterpret_cast<const char *>(&opt),
  17298. #else
  17299. &opt,
  17300. #endif
  17301. sizeof(opt));
  17302. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  17303. ::listen(srv, 1) != 0) {
  17304. port_promise.set_value(-1);
  17305. detail::close_socket(srv);
  17306. return;
  17307. }
  17308. socklen_t addr_len = sizeof(addr);
  17309. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  17310. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  17311. sockaddr_in cli_addr{};
  17312. socklen_t cli_len = sizeof(cli_addr);
  17313. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17314. if (cli != INVALID_SOCKET) {
  17315. // Read the complete HTTP request (until the blank line that terminates
  17316. // headers) before sending the response. If the server closes the socket
  17317. // while the client's request data is still unread in the kernel receive
  17318. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  17319. // connection on both sides: it discards the client's receive buffer
  17320. // (which already holds our response) and causes any in-progress write on
  17321. // the client to fail with ECONNRESET. Reading all request data first
  17322. // ensures close() emits a graceful FIN.
  17323. {
  17324. char rbuf[256];
  17325. std::string req;
  17326. while (req.find("\r\n\r\n") == std::string::npos) {
  17327. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  17328. if (n <= 0) { break; }
  17329. req.append(rbuf, static_cast<size_t>(n));
  17330. }
  17331. }
  17332. ::send(cli,
  17333. #ifdef _WIN32
  17334. static_cast<const char *>(response.c_str()),
  17335. static_cast<int>(response.size()),
  17336. #else
  17337. response.c_str(), response.size(),
  17338. #endif
  17339. 0);
  17340. detail::close_socket(cli);
  17341. }
  17342. detail::close_socket(srv);
  17343. });
  17344. }
  17345. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  17346. #ifndef _WIN32
  17347. signal(SIGPIPE, SIG_IGN);
  17348. #endif
  17349. std::promise<int> port_promise;
  17350. auto port_future = port_promise.get_future();
  17351. auto server_thread =
  17352. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  17353. "Content-Type: text/plain\r\n"
  17354. "Content-Length: not-a-number\r\n"
  17355. "Connection: close\r\n"
  17356. "\r\n"
  17357. "hello");
  17358. auto port = port_future.get();
  17359. ASSERT_GT(port, 0);
  17360. Client cli("127.0.0.1", port);
  17361. auto handle = cli.open_stream("GET", "/");
  17362. EXPECT_FALSE(handle.is_valid());
  17363. server_thread.join();
  17364. }
  17365. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  17366. #ifndef _WIN32
  17367. signal(SIGPIPE, SIG_IGN);
  17368. #endif
  17369. std::promise<int> port_promise;
  17370. auto port_future = port_promise.get_future();
  17371. auto server_thread = serve_single_response(
  17372. port_promise, "HTTP/1.1 200 OK\r\n"
  17373. "Content-Type: text/plain\r\n"
  17374. "Content-Length: 99999999999999999999999999\r\n"
  17375. "Connection: close\r\n"
  17376. "\r\n"
  17377. "hello");
  17378. auto port = port_future.get();
  17379. ASSERT_GT(port, 0);
  17380. // Historically std::stoull would throw std::out_of_range here and crash
  17381. // the process, then parsing silently clamped to a bogus framing length and
  17382. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  17383. // so the stream fails to open, matching the not-a-number case above. The
  17384. // process still must NOT terminate.
  17385. Client cli("127.0.0.1", port);
  17386. auto handle = cli.open_stream("GET", "/");
  17387. EXPECT_FALSE(handle.is_valid());
  17388. server_thread.join();
  17389. }
  17390. // Serves `response` to the single request `fn` makes with a fresh client.
  17391. template <typename Fn>
  17392. static void with_single_response(const std::string &response, Fn fn) {
  17393. #ifndef _WIN32
  17394. signal(SIGPIPE, SIG_IGN);
  17395. #endif
  17396. std::promise<int> port_promise;
  17397. auto port_future = port_promise.get_future();
  17398. auto server_thread = serve_single_response(port_promise, response);
  17399. auto se = detail::scope_exit([&] { server_thread.join(); });
  17400. auto port = port_future.get();
  17401. ASSERT_GT(port, 0);
  17402. Client cli("127.0.0.1", port);
  17403. fn(cli);
  17404. }
  17405. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  17406. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  17407. // the chunked coding and drop Content-Length, so a front-end that trusts
  17408. // Content-Length would disagree about where the body ends (response
  17409. // smuggling). The client must reject such a response.
  17410. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17411. for (const char *te : {"chunked", "gzip, chunked"}) {
  17412. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  17413. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  17414. "\r\n" + "Connection: close\r\n" + "\r\n" +
  17415. "5\r\nhello\r\n0\r\n\r\n";
  17416. with_single_response(response, [&](Client &cli) {
  17417. auto res = cli.Get("/");
  17418. EXPECT_FALSE(static_cast<bool>(res)) << te;
  17419. EXPECT_EQ(Error::Read, res.error()) << te;
  17420. });
  17421. with_single_response(response, [&](Client &cli) {
  17422. auto handle = cli.open_stream("GET", "/");
  17423. EXPECT_FALSE(handle.is_valid()) << te;
  17424. EXPECT_EQ(Error::Read, handle.error) << te;
  17425. });
  17426. }
  17427. }
  17428. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  17429. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  17430. // closing the connection (unlike a request, which must be rejected).
  17431. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  17432. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  17433. "Transfer-Encoding: chunked\r\n"
  17434. "Connection: close\r\n"
  17435. "\r\n"
  17436. "5\r\nhello\r\n0\r\n\r\n",
  17437. "HTTP/1.1 200 OK\r\n"
  17438. "Transfer-Encoding: gzip\r\n"
  17439. "Connection: close\r\n"
  17440. "\r\n"
  17441. "hello"}) {
  17442. with_single_response(response, [&](Client &cli) {
  17443. auto res = cli.Get("/");
  17444. ASSERT_TRUE(static_cast<bool>(res)) << response;
  17445. EXPECT_EQ("hello", res->body);
  17446. });
  17447. with_single_response(response, [&](Client &cli) {
  17448. auto handle = cli.open_stream("GET", "/");
  17449. ASSERT_TRUE(handle.is_valid()) << response;
  17450. EXPECT_EQ("hello", read_all(handle));
  17451. });
  17452. }
  17453. }
  17454. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  17455. // framing headers describe nothing to read and must not be rejected.
  17456. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  17457. const std::string framing = "Content-Length: 5\r\n"
  17458. "Transfer-Encoding: chunked\r\n"
  17459. "Connection: close\r\n"
  17460. "\r\n";
  17461. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17462. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  17463. });
  17464. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17465. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  17466. });
  17467. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  17468. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  17469. with_single_response(response, [&](Client &cli) {
  17470. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  17471. });
  17472. with_single_response(response, [&](Client &cli) {
  17473. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  17474. });
  17475. }
  17476. }
  17477. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17478. TEST_F(OpenStreamTest, Gzip) {
  17479. Client cli("127.0.0.1", port_);
  17480. auto handle = cli.open_stream("GET", "/compressible", {},
  17481. {{"Accept-Encoding", "gzip"}});
  17482. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  17483. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17484. }
  17485. #endif
  17486. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17487. TEST_F(OpenStreamTest, Brotli) {
  17488. Client cli("127.0.0.1", port_);
  17489. auto handle =
  17490. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  17491. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  17492. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17493. }
  17494. #endif
  17495. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17496. TEST_F(OpenStreamTest, Zstd) {
  17497. Client cli("127.0.0.1", port_);
  17498. auto handle = cli.open_stream("GET", "/compressible", {},
  17499. {{"Accept-Encoding", "zstd"}});
  17500. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  17501. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17502. }
  17503. #endif
  17504. #ifdef CPPHTTPLIB_SSL_ENABLED
  17505. class SSLOpenStreamTest : public ::testing::Test {
  17506. protected:
  17507. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  17508. void SetUp() override {
  17509. svr_.Get("/hello", [](const Request &, Response &res) {
  17510. res.set_content("Hello SSL World!", "text/plain");
  17511. });
  17512. svr_.Get("/chunked", [](const Request &, Response &res) {
  17513. res.set_chunked_content_provider("text/plain",
  17514. [](size_t offset, DataSink &sink) {
  17515. if (offset < 15) {
  17516. sink.write("chunk", 5);
  17517. return true;
  17518. }
  17519. sink.done();
  17520. return true;
  17521. });
  17522. });
  17523. svr_.Post("/echo", [](const Request &req, Response &res) {
  17524. res.set_content(req.body, req.get_header_value("Content-Type"));
  17525. });
  17526. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  17527. std::string body = req.body;
  17528. res.set_chunked_content_provider(
  17529. "text/plain", [body](size_t offset, DataSink &sink) {
  17530. if (offset < body.size()) {
  17531. sink.write(body.data() + offset, body.size() - offset);
  17532. }
  17533. sink.done();
  17534. return true;
  17535. });
  17536. });
  17537. port_ = svr_.bind_to_any_port("127.0.0.1");
  17538. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17539. svr_.wait_until_ready();
  17540. }
  17541. void TearDown() override {
  17542. svr_.stop();
  17543. if (thread_.joinable()) thread_.join();
  17544. }
  17545. SSLServer svr_;
  17546. std::thread thread_;
  17547. int port_ = 0;
  17548. };
  17549. TEST_F(SSLOpenStreamTest, Basic) {
  17550. SSLClient cli("127.0.0.1", port_);
  17551. cli.enable_server_certificate_verification(false);
  17552. auto handle = cli.open_stream("GET", "/hello");
  17553. ASSERT_TRUE(handle.is_valid());
  17554. EXPECT_EQ("Hello SSL World!", read_all(handle));
  17555. }
  17556. TEST_F(SSLOpenStreamTest, Chunked) {
  17557. SSLClient cli("127.0.0.1", port_);
  17558. cli.enable_server_certificate_verification(false);
  17559. auto handle = cli.open_stream("GET", "/chunked");
  17560. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17561. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17562. "Transfer-Encoding") == "chunked");
  17563. auto body = read_all(handle);
  17564. EXPECT_EQ("chunkchunkchunk", body);
  17565. }
  17566. TEST_F(SSLOpenStreamTest, Post) {
  17567. SSLClient cli("127.0.0.1", port_);
  17568. cli.enable_server_certificate_verification(false);
  17569. auto handle =
  17570. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  17571. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17572. EXPECT_EQ(200, handle.response->status);
  17573. auto body = read_all(handle);
  17574. EXPECT_EQ("Hello SSL POST", body);
  17575. }
  17576. TEST_F(SSLOpenStreamTest, PostChunked) {
  17577. SSLClient cli("127.0.0.1", port_);
  17578. cli.enable_server_certificate_verification(false);
  17579. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  17580. "Chunked SSL Data", "text/plain");
  17581. ASSERT_TRUE(handle.is_valid());
  17582. EXPECT_EQ(200, handle.response->status);
  17583. auto body = read_all(handle);
  17584. EXPECT_EQ("Chunked SSL Data", body);
  17585. }
  17586. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  17587. // Content-Length is terminated by the server closing the connection. When the
  17588. // SSL peer sends a close_notify after the body, the client must treat it as a
  17589. // clean EOF and return a successful response rather than an error.
  17590. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  17591. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17592. ASSERT_TRUE(svr.is_valid());
  17593. svr.set_keep_alive_max_count(1);
  17594. const std::string expected_body = "Hello from connection-close response!";
  17595. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  17596. res.set_content_provider("text/plain",
  17597. [&](size_t offset, DataSink &sink) -> bool {
  17598. if (offset < expected_body.size()) {
  17599. sink.write(expected_body.data() + offset,
  17600. expected_body.size() - offset);
  17601. }
  17602. sink.done();
  17603. return true;
  17604. });
  17605. });
  17606. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  17607. auto se = detail::scope_exit([&] {
  17608. svr.stop();
  17609. listen_thread.join();
  17610. ASSERT_FALSE(svr.is_running());
  17611. });
  17612. svr.wait_until_ready();
  17613. SSLClient cli(HOST, PORT);
  17614. cli.enable_server_certificate_verification(false);
  17615. auto res = cli.Get("/no-content-length");
  17616. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  17617. EXPECT_EQ(StatusCode::OK_200, res->status);
  17618. EXPECT_EQ(expected_body, res->body);
  17619. }
  17620. #endif // CPPHTTPLIB_SSL_ENABLED
  17621. //==============================================================================
  17622. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  17623. // results for various scenarios.
  17624. //==============================================================================
  17625. TEST(ParityTest, GetVsOpenStream) {
  17626. Server svr;
  17627. const std::string path = "/parity";
  17628. const std::string content = "Parity test content: hello world";
  17629. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17630. res.set_content(content, "text/plain");
  17631. });
  17632. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17633. auto se = detail::scope_exit([&] {
  17634. svr.stop();
  17635. t.join();
  17636. ASSERT_FALSE(svr.is_running());
  17637. });
  17638. svr.wait_until_ready();
  17639. Client cli(HOST, PORT);
  17640. // Non-stream path
  17641. auto r1 = cli.Get(path);
  17642. ASSERT_TRUE(r1);
  17643. EXPECT_EQ(StatusCode::OK_200, r1->status);
  17644. // Stream path
  17645. auto h = cli.open_stream("GET", path);
  17646. ASSERT_TRUE(h.is_valid());
  17647. EXPECT_EQ(r1->body, read_all(h));
  17648. }
  17649. // Helper to compress data with provided compressor type T
  17650. template <typename Compressor>
  17651. static std::string compress_payload_for_parity(const std::string &in) {
  17652. std::string out;
  17653. Compressor compressor;
  17654. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  17655. [&](const char *data, size_t n) {
  17656. out.append(data, n);
  17657. return true;
  17658. });
  17659. EXPECT_TRUE(ok);
  17660. return out;
  17661. }
  17662. // Helper function for compression parity tests
  17663. template <typename Compressor>
  17664. static void test_compression_parity(const std::string &original,
  17665. const std::string &path,
  17666. const std::string &encoding) {
  17667. const std::string compressed =
  17668. compress_payload_for_parity<Compressor>(original);
  17669. Server svr;
  17670. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17671. res.set_content(compressed, "application/octet-stream");
  17672. res.set_header("Content-Encoding", encoding);
  17673. });
  17674. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  17675. auto se = detail::scope_exit([&] {
  17676. svr.stop();
  17677. t.join();
  17678. ASSERT_FALSE(svr.is_running());
  17679. });
  17680. svr.wait_until_ready();
  17681. Client cli(HOST, PORT);
  17682. // Non-streaming
  17683. {
  17684. auto res = cli.Get(path);
  17685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17686. EXPECT_EQ(StatusCode::OK_200, res->status);
  17687. EXPECT_EQ(original, res->body);
  17688. }
  17689. // Streaming
  17690. {
  17691. auto h = cli.open_stream("GET", path);
  17692. ASSERT_TRUE(h.is_valid());
  17693. EXPECT_EQ(original, read_all(h));
  17694. }
  17695. }
  17696. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17697. TEST(ParityTest, Gzip) {
  17698. test_compression_parity<detail::gzip_compressor>(
  17699. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  17700. }
  17701. #endif
  17702. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17703. TEST(ParityTest, Brotli) {
  17704. test_compression_parity<detail::brotli_compressor>(
  17705. "Hello, brotli parity test payload", "/parity-br", "br");
  17706. }
  17707. #endif
  17708. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17709. TEST(ParityTest, Zstd) {
  17710. test_compression_parity<detail::zstd_compressor>(
  17711. "Zstandard parity test payload", "/parity-zstd", "zstd");
  17712. }
  17713. #endif
  17714. //==============================================================================
  17715. // New Stream API Tests
  17716. //==============================================================================
  17717. inline std::string read_body(httplib::stream::Result &result) {
  17718. std::string body;
  17719. while (result.next()) {
  17720. body.append(result.data(), result.size());
  17721. }
  17722. return body;
  17723. }
  17724. TEST(ClientConnectionTest, Basic) {
  17725. httplib::ClientConnection conn;
  17726. EXPECT_FALSE(conn.is_open());
  17727. conn.sock = 1;
  17728. EXPECT_TRUE(conn.is_open());
  17729. httplib::ClientConnection conn2(std::move(conn));
  17730. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  17731. conn2.sock = INVALID_SOCKET;
  17732. }
  17733. // Unified test server for all stream::* tests
  17734. class StreamApiTest : public ::testing::Test {
  17735. protected:
  17736. void SetUp() override {
  17737. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17738. res.set_content("Hello World!", "text/plain");
  17739. });
  17740. svr_.Get("/echo-params",
  17741. [](const httplib::Request &req, httplib::Response &res) {
  17742. std::string r;
  17743. for (const auto &p : req.params) {
  17744. if (!r.empty()) r += "&";
  17745. r += p.first + "=" + p.second;
  17746. }
  17747. res.set_content(r, "text/plain");
  17748. });
  17749. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17750. res.set_content(req.body, req.get_header_value("Content-Type"));
  17751. });
  17752. svr_.Post("/echo-headers",
  17753. [](const httplib::Request &req, httplib::Response &res) {
  17754. std::string r;
  17755. for (const auto &h : req.headers)
  17756. r += h.first + ": " + h.second + "\n";
  17757. res.set_content(r, "text/plain");
  17758. });
  17759. svr_.Post("/echo-params",
  17760. [](const httplib::Request &req, httplib::Response &res) {
  17761. std::string r = "params:";
  17762. for (const auto &p : req.params)
  17763. r += p.first + "=" + p.second + ";";
  17764. res.set_content(r + " body:" + req.body, "text/plain");
  17765. });
  17766. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  17767. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  17768. });
  17769. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17770. res.set_content("PUT:" + req.body, "text/plain");
  17771. });
  17772. svr_.Patch("/echo",
  17773. [](const httplib::Request &req, httplib::Response &res) {
  17774. res.set_content("PATCH:" + req.body, "text/plain");
  17775. });
  17776. svr_.Delete(
  17777. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  17778. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  17779. "text/plain");
  17780. });
  17781. svr_.Get("/head-test",
  17782. [](const httplib::Request &, httplib::Response &res) {
  17783. res.set_content("body for HEAD", "text/plain");
  17784. });
  17785. svr_.Options("/options",
  17786. [](const httplib::Request &, httplib::Response &res) {
  17787. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  17788. });
  17789. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  17790. svr_.wait_until_ready();
  17791. }
  17792. void TearDown() override {
  17793. svr_.stop();
  17794. if (thread_.joinable()) thread_.join();
  17795. }
  17796. httplib::Server svr_;
  17797. std::thread thread_;
  17798. };
  17799. // stream::Get tests
  17800. TEST_F(StreamApiTest, GetBasic) {
  17801. httplib::Client cli(HOST, PORT);
  17802. auto result = httplib::stream::Get(cli, "/hello");
  17803. ASSERT_TRUE(result.is_valid());
  17804. EXPECT_EQ(200, result.status());
  17805. EXPECT_EQ("Hello World!", read_body(result));
  17806. }
  17807. TEST_F(StreamApiTest, GetWithParams) {
  17808. httplib::Client cli(HOST, PORT);
  17809. httplib::Params params{{"foo", "bar"}};
  17810. auto result = httplib::stream::Get(cli, "/echo-params", params);
  17811. ASSERT_TRUE(result.is_valid());
  17812. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  17813. }
  17814. TEST_F(StreamApiTest, GetConnectionError) {
  17815. httplib::Client cli(HOST, 9999);
  17816. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  17817. }
  17818. TEST_F(StreamApiTest, Get404) {
  17819. httplib::Client cli(HOST, PORT);
  17820. auto result = httplib::stream::Get(cli, "/nonexistent");
  17821. EXPECT_TRUE(result.is_valid());
  17822. EXPECT_EQ(404, result.status());
  17823. }
  17824. // stream::Post tests
  17825. TEST_F(StreamApiTest, PostBasic) {
  17826. httplib::Client cli(HOST, PORT);
  17827. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  17828. "application/json");
  17829. ASSERT_TRUE(result.is_valid());
  17830. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  17831. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  17832. }
  17833. TEST_F(StreamApiTest, PostWithHeaders) {
  17834. httplib::Client cli(HOST, PORT);
  17835. httplib::Headers headers{{"X-Custom", "value"}};
  17836. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  17837. "text/plain");
  17838. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  17839. }
  17840. TEST_F(StreamApiTest, PostWithParams) {
  17841. httplib::Client cli(HOST, PORT);
  17842. httplib::Params params{{"k", "v"}};
  17843. auto result =
  17844. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  17845. auto body = read_body(result);
  17846. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  17847. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  17848. }
  17849. TEST_F(StreamApiTest, PostLarge) {
  17850. httplib::Client cli(HOST, PORT);
  17851. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  17852. size_t total = 0;
  17853. while (result.next()) {
  17854. total += result.size();
  17855. }
  17856. EXPECT_EQ(100u * 1024u, total);
  17857. }
  17858. // stream::Put/Patch tests
  17859. TEST_F(StreamApiTest, PutAndPatch) {
  17860. httplib::Client cli(HOST, PORT);
  17861. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  17862. EXPECT_EQ("PUT:test", read_body(put));
  17863. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  17864. EXPECT_EQ("PATCH:test", read_body(patch));
  17865. }
  17866. // stream::Delete tests
  17867. TEST_F(StreamApiTest, Delete) {
  17868. httplib::Client cli(HOST, PORT);
  17869. auto del1 = httplib::stream::Delete(cli, "/resource");
  17870. EXPECT_EQ("Deleted", read_body(del1));
  17871. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  17872. EXPECT_EQ("Deleted:data", read_body(del2));
  17873. }
  17874. // stream::Head/Options tests
  17875. TEST_F(StreamApiTest, HeadAndOptions) {
  17876. httplib::Client cli(HOST, PORT);
  17877. auto head = httplib::stream::Head(cli, "/head-test");
  17878. EXPECT_TRUE(head.is_valid());
  17879. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  17880. auto opts = httplib::stream::Options(cli, "/options");
  17881. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  17882. }
  17883. // SSL stream::* tests
  17884. #ifdef CPPHTTPLIB_SSL_ENABLED
  17885. class SSLStreamApiTest : public ::testing::Test {
  17886. protected:
  17887. void SetUp() override {
  17888. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17889. res.set_content("Hello SSL!", "text/plain");
  17890. });
  17891. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17892. res.set_content(req.body, "text/plain");
  17893. });
  17894. port_ = svr_.bind_to_any_port("127.0.0.1");
  17895. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17896. svr_.wait_until_ready();
  17897. }
  17898. void TearDown() override {
  17899. svr_.stop();
  17900. if (thread_.joinable()) thread_.join();
  17901. }
  17902. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  17903. std::thread thread_;
  17904. int port_ = 0;
  17905. };
  17906. TEST_F(SSLStreamApiTest, GetAndPost) {
  17907. httplib::SSLClient cli("127.0.0.1", port_);
  17908. cli.enable_server_certificate_verification(false);
  17909. auto get = httplib::stream::Get(cli, "/hello");
  17910. EXPECT_EQ("Hello SSL!", read_body(get));
  17911. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  17912. EXPECT_EQ("test", read_body(post));
  17913. }
  17914. #endif
  17915. // Tests for Error::Timeout and Error::ConnectionClosed error types
  17916. // These errors are set in SocketStream/SSLSocketStream and propagated through
  17917. // BodyReader
  17918. TEST(ErrorHandlingTest, StreamReadTimeout) {
  17919. // Test that read timeout during streaming is detected
  17920. // Use a large content-length response where server delays mid-stream
  17921. Server svr;
  17922. svr.Get("/slow-stream", [](const Request &, Response &res) {
  17923. // Send a large response with delay in the middle
  17924. res.set_content_provider(
  17925. 1000, // content_length
  17926. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  17927. if (offset < 100) {
  17928. // Send first 100 bytes immediately
  17929. std::string data(100, 'A');
  17930. sink.write(data.c_str(), data.size());
  17931. return true;
  17932. }
  17933. // Then delay longer than client timeout
  17934. std::this_thread::sleep_for(std::chrono::seconds(3));
  17935. std::string data(900, 'B');
  17936. sink.write(data.c_str(), data.size());
  17937. return true;
  17938. });
  17939. });
  17940. auto port = 8091;
  17941. std::thread t([&]() { svr.listen("localhost", port); });
  17942. svr.wait_until_ready();
  17943. Client cli("localhost", port);
  17944. cli.set_read_timeout(1, 0); // 1 second timeout
  17945. auto handle = cli.open_stream("GET", "/slow-stream");
  17946. ASSERT_TRUE(handle.is_valid());
  17947. char buf[256];
  17948. ssize_t total = 0;
  17949. ssize_t n;
  17950. bool got_error = false;
  17951. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17952. total += n;
  17953. }
  17954. if (n < 0) {
  17955. got_error = true;
  17956. // Should be timeout or read error
  17957. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  17958. handle.get_read_error() == Error::Read)
  17959. << "Actual error: " << to_string(handle.get_read_error());
  17960. }
  17961. // Either we got an error, or we got less data than expected
  17962. EXPECT_TRUE(got_error || total < 1000)
  17963. << "Expected timeout but got all " << total << " bytes";
  17964. svr.stop();
  17965. t.join();
  17966. }
  17967. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  17968. // Test connection closed detection via BodyReader
  17969. Server svr;
  17970. std::atomic<bool> close_now{false};
  17971. svr.Get("/will-close", [&](const Request &, Response &res) {
  17972. res.set_content_provider(
  17973. 10000, // Large content_length that we won't fully send
  17974. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17975. if (offset < 100) {
  17976. std::string data(100, 'X');
  17977. sink.write(data.c_str(), data.size());
  17978. return true;
  17979. }
  17980. // Wait for signal then abort
  17981. while (!close_now) {
  17982. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17983. }
  17984. return false; // Abort - server will close connection
  17985. });
  17986. });
  17987. auto port = 8092;
  17988. std::thread t([&]() { svr.listen("localhost", port); });
  17989. svr.wait_until_ready();
  17990. Client cli("localhost", port);
  17991. auto handle = cli.open_stream("GET", "/will-close");
  17992. ASSERT_TRUE(handle.is_valid());
  17993. char buf[256];
  17994. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17995. EXPECT_GT(n, 0) << "First read should succeed";
  17996. // Signal server to close
  17997. close_now = true;
  17998. // Keep reading until error or EOF
  17999. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18000. // Keep reading
  18001. }
  18002. // Should get an error since content_length wasn't satisfied
  18003. if (n < 0) {
  18004. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18005. handle.get_read_error() == Error::Read)
  18006. << "Actual error: " << to_string(handle.get_read_error());
  18007. }
  18008. svr.stop();
  18009. t.join();
  18010. }
  18011. #ifdef CPPHTTPLIB_SSL_ENABLED
  18012. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  18013. // Test that read timeout during SSL streaming is detected
  18014. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18015. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18016. res.set_content_provider(
  18017. 1000, "text/plain",
  18018. [](size_t offset, size_t /*length*/, DataSink &sink) {
  18019. if (offset < 100) {
  18020. std::string data(100, 'A');
  18021. sink.write(data.c_str(), data.size());
  18022. return true;
  18023. }
  18024. std::this_thread::sleep_for(std::chrono::seconds(3));
  18025. std::string data(900, 'B');
  18026. sink.write(data.c_str(), data.size());
  18027. return true;
  18028. });
  18029. });
  18030. auto port = 8093;
  18031. std::thread t([&]() { svr.listen("localhost", port); });
  18032. svr.wait_until_ready();
  18033. SSLClient cli("localhost", port);
  18034. cli.enable_server_certificate_verification(false);
  18035. cli.set_read_timeout(1, 0); // 1 second timeout
  18036. auto handle = cli.open_stream("GET", "/slow-stream");
  18037. ASSERT_TRUE(handle.is_valid());
  18038. char buf[256];
  18039. ssize_t total = 0;
  18040. ssize_t n;
  18041. bool got_error = false;
  18042. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18043. total += n;
  18044. }
  18045. if (n < 0) {
  18046. got_error = true;
  18047. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18048. handle.get_read_error() == Error::Read)
  18049. << "Actual error: " << to_string(handle.get_read_error());
  18050. }
  18051. EXPECT_TRUE(got_error || total < 1000)
  18052. << "Expected timeout but got all " << total << " bytes";
  18053. svr.stop();
  18054. t.join();
  18055. }
  18056. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  18057. // Test SSL connection closed detection
  18058. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18059. std::atomic<bool> close_now{false};
  18060. svr.Get("/will-close", [&](const Request &, Response &res) {
  18061. res.set_content_provider(
  18062. 10000, "text/plain",
  18063. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18064. if (offset < 100) {
  18065. std::string data(100, 'X');
  18066. sink.write(data.c_str(), data.size());
  18067. return true;
  18068. }
  18069. while (!close_now) {
  18070. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18071. }
  18072. return false;
  18073. });
  18074. });
  18075. auto port = 8094;
  18076. std::thread t([&]() { svr.listen("localhost", port); });
  18077. svr.wait_until_ready();
  18078. SSLClient cli("localhost", port);
  18079. cli.enable_server_certificate_verification(false);
  18080. auto handle = cli.open_stream("GET", "/will-close");
  18081. ASSERT_TRUE(handle.is_valid());
  18082. char buf[256];
  18083. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18084. EXPECT_GT(n, 0);
  18085. // Signal server to close
  18086. close_now = true;
  18087. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18088. // Keep reading
  18089. }
  18090. if (n < 0) {
  18091. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18092. handle.get_read_error() == Error::Read)
  18093. << "Actual error: " << to_string(handle.get_read_error());
  18094. }
  18095. svr.stop();
  18096. t.join();
  18097. }
  18098. #endif
  18099. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  18100. using namespace httplib;
  18101. // Create a test file
  18102. const char *fname = "etag_testfile.txt";
  18103. const char *content = "etag-content";
  18104. {
  18105. std::ofstream ofs(fname);
  18106. ofs << content;
  18107. ASSERT_TRUE(ofs.good());
  18108. }
  18109. Server svr;
  18110. svr.set_mount_point("/static", ".");
  18111. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18112. svr.wait_until_ready();
  18113. Client cli(HOST, PORT);
  18114. // First request: should get 200 with ETag header
  18115. auto res1 = cli.Get("/static/etag_testfile.txt");
  18116. ASSERT_TRUE(res1);
  18117. ASSERT_EQ(200, res1->status);
  18118. ASSERT_TRUE(res1->has_header("ETag"));
  18119. std::string etag = res1->get_header_value("ETag");
  18120. EXPECT_FALSE(etag.empty());
  18121. // Verify ETag format: W/"hex-hex"
  18122. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  18123. EXPECT_EQ('W', etag[0]);
  18124. EXPECT_EQ('/', etag[1]);
  18125. EXPECT_EQ('"', etag[2]);
  18126. EXPECT_EQ('"', etag.back());
  18127. // Exact match: expect 304 Not Modified
  18128. Headers h2 = {{"If-None-Match", etag}};
  18129. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  18130. ASSERT_TRUE(res2);
  18131. EXPECT_EQ(304, res2->status);
  18132. // Wildcard match: expect 304 Not Modified
  18133. Headers h3 = {{"If-None-Match", "*"}};
  18134. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  18135. ASSERT_TRUE(res3);
  18136. EXPECT_EQ(304, res3->status);
  18137. // Non-matching ETag: expect 200
  18138. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  18139. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  18140. ASSERT_TRUE(res4);
  18141. EXPECT_EQ(200, res4->status);
  18142. // Multiple ETags with one matching: expect 304
  18143. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  18144. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  18145. ASSERT_TRUE(res5);
  18146. EXPECT_EQ(304, res5->status);
  18147. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  18148. // that equivalent to the single comma-separated list above, so the match on
  18149. // the second line must still be found.
  18150. Headers h6;
  18151. h6.emplace("If-None-Match", "W/\"other\"");
  18152. h6.emplace("If-None-Match", etag);
  18153. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  18154. ASSERT_TRUE(res6);
  18155. EXPECT_EQ(304, res6->status);
  18156. svr.stop();
  18157. t.join();
  18158. std::remove(fname);
  18159. }
  18160. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  18161. using namespace httplib;
  18162. Server svr;
  18163. svr.set_mount_point("/static", ".");
  18164. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18165. svr.wait_until_ready();
  18166. Client cli(HOST, PORT);
  18167. // Send If-None-Match: * to a non-existent file
  18168. Headers h = {{"If-None-Match", "*"}};
  18169. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  18170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18171. EXPECT_EQ(404, res->status);
  18172. svr.stop();
  18173. t.join();
  18174. }
  18175. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  18176. using namespace httplib;
  18177. // Create a test file
  18178. const char *fname = "etag_boundary_testfile.txt";
  18179. const char *content = "boundary-test";
  18180. {
  18181. std::ofstream ofs(fname);
  18182. ofs << content;
  18183. ASSERT_TRUE(ofs.good());
  18184. }
  18185. Server svr;
  18186. svr.set_mount_point("/static", ".");
  18187. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18188. svr.wait_until_ready();
  18189. Client cli(HOST, PORT);
  18190. // Get the actual ETag
  18191. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  18192. ASSERT_TRUE(res1);
  18193. ASSERT_EQ(200, res1->status);
  18194. ASSERT_TRUE(res1->has_header("ETag"));
  18195. std::string etag = res1->get_header_value("ETag");
  18196. // Test 1: Very long ETag value (longer than actual ETag)
  18197. // Should NOT match and return 200 (not trigger out-of-bounds read)
  18198. Headers h1 = {{"If-None-Match", "W/"
  18199. "\"very-long-etag-value-that-is-much-longer-"
  18200. "than-the-actual-etag-value\""}};
  18201. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  18202. ASSERT_TRUE(res2);
  18203. EXPECT_EQ(200, res2->status); // Should not match
  18204. // Test 2: Long string followed by wildcard
  18205. // Should match on "*" and return 304 (without out-of-bounds read on the long
  18206. // string)
  18207. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  18208. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  18209. ASSERT_TRUE(res3);
  18210. EXPECT_EQ(304, res3->status); // Should match on "*"
  18211. // Test 3: Wildcard followed by long string
  18212. // Should match on "*" immediately and return 304
  18213. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  18214. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  18215. ASSERT_TRUE(res4);
  18216. EXPECT_EQ(304, res4->status); // Should match on "*"
  18217. // Test 4: Multiple long non-matching values
  18218. // Should NOT match and return 200 (test that all comparisons are safe)
  18219. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  18220. "W/\"second-long-non-matching-value\", "
  18221. "W/\"third-long-non-matching-value\""}};
  18222. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  18223. ASSERT_TRUE(res5);
  18224. EXPECT_EQ(200, res5->status); // Should not match
  18225. // Test 5: Single character that is not "*" (edge case)
  18226. Headers h5 = {{"If-None-Match", "X"}};
  18227. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  18228. ASSERT_TRUE(res6);
  18229. EXPECT_EQ(200, res6->status); // Should not match
  18230. svr.stop();
  18231. t.join();
  18232. std::remove(fname);
  18233. }
  18234. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  18235. using namespace httplib;
  18236. // Create a test file
  18237. const char *fname = "ims_testfile.txt";
  18238. const char *content = "if-modified-since-test";
  18239. {
  18240. std::ofstream ofs(fname);
  18241. ofs << content;
  18242. ASSERT_TRUE(ofs.good());
  18243. }
  18244. Server svr;
  18245. svr.set_mount_point("/static", ".");
  18246. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18247. svr.wait_until_ready();
  18248. Client cli(HOST, PORT);
  18249. // First request: should get 200 with Last-Modified header
  18250. auto res1 = cli.Get("/static/ims_testfile.txt");
  18251. ASSERT_TRUE(res1);
  18252. ASSERT_EQ(200, res1->status);
  18253. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18254. std::string last_modified = res1->get_header_value("Last-Modified");
  18255. EXPECT_FALSE(last_modified.empty());
  18256. // If-Modified-Since with same time: expect 304
  18257. Headers h2 = {{"If-Modified-Since", last_modified}};
  18258. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  18259. ASSERT_TRUE(res2);
  18260. EXPECT_EQ(304, res2->status);
  18261. // If-Modified-Since with future time: expect 304
  18262. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18263. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  18264. ASSERT_TRUE(res3);
  18265. EXPECT_EQ(304, res3->status);
  18266. // If-Modified-Since with past time: expect 200
  18267. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18268. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  18269. ASSERT_TRUE(res4);
  18270. EXPECT_EQ(200, res4->status);
  18271. // If-None-Match takes precedence over If-Modified-Since
  18272. // (send matching ETag with old If-Modified-Since -> should still be 304)
  18273. ASSERT_TRUE(res1->has_header("ETag"));
  18274. std::string etag = res1->get_header_value("ETag");
  18275. Headers h5 = {{"If-None-Match", etag},
  18276. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18277. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  18278. ASSERT_TRUE(res5);
  18279. EXPECT_EQ(304, res5->status);
  18280. svr.stop();
  18281. t.join();
  18282. std::remove(fname);
  18283. }
  18284. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  18285. using namespace httplib;
  18286. Server svr;
  18287. // Endpoint that returns compressible content
  18288. svr.Get("/compressible", [](const Request &, Response &res) {
  18289. // Return a large enough body to trigger compression
  18290. std::string body(1000, 'a');
  18291. res.set_content(body, "text/plain");
  18292. });
  18293. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18294. svr.wait_until_ready();
  18295. Client cli(HOST, PORT);
  18296. // Request with gzip support: should get Vary header when compressed
  18297. cli.set_compress(true);
  18298. auto res1 = cli.Get("/compressible");
  18299. ASSERT_TRUE(res1);
  18300. EXPECT_EQ(200, res1->status);
  18301. // If Content-Encoding is set, Vary should also be set
  18302. if (res1->has_header("Content-Encoding")) {
  18303. EXPECT_TRUE(res1->has_header("Vary"));
  18304. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  18305. }
  18306. // Request without Accept-Encoding header: should not have compression
  18307. Headers h_no_compress;
  18308. auto res2 = cli.Get("/compressible", h_no_compress);
  18309. ASSERT_TRUE(res2);
  18310. EXPECT_EQ(200, res2->status);
  18311. // Verify Vary header is present when compression is applied
  18312. // (the exact behavior depends on server configuration)
  18313. svr.stop();
  18314. t.join();
  18315. }
  18316. TEST(ETagTest, IfRangeWithETag) {
  18317. using namespace httplib;
  18318. // Create a test file with known content
  18319. const char *fname = "if_range_testfile.txt";
  18320. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  18321. {
  18322. std::ofstream ofs(fname);
  18323. ofs << content;
  18324. ASSERT_TRUE(ofs.good());
  18325. }
  18326. Server svr;
  18327. svr.set_mount_point("/static", ".");
  18328. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18329. svr.wait_until_ready();
  18330. Client cli(HOST, PORT);
  18331. // First request: get ETag
  18332. auto res1 = cli.Get("/static/if_range_testfile.txt");
  18333. ASSERT_TRUE(res1);
  18334. ASSERT_EQ(200, res1->status);
  18335. ASSERT_TRUE(res1->has_header("ETag"));
  18336. std::string etag = res1->get_header_value("ETag");
  18337. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  18338. // Since our server generates weak ETags (W/"..."), If-Range with our
  18339. // ETag should NOT result in partial content - it should return full content.
  18340. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  18341. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  18342. ASSERT_TRUE(res2);
  18343. // Weak ETag in If-Range -> full content (200), not partial (206)
  18344. EXPECT_EQ(200, res2->status);
  18345. EXPECT_EQ(content, res2->body);
  18346. EXPECT_FALSE(res2->has_header("Content-Range"));
  18347. // Range request with non-matching If-Range (ETag): should get 200 (full
  18348. // content)
  18349. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  18350. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  18351. ASSERT_TRUE(res3);
  18352. EXPECT_EQ(200, res3->status);
  18353. EXPECT_EQ(content, res3->body);
  18354. EXPECT_FALSE(res3->has_header("Content-Range"));
  18355. // Range request with strong ETag (hypothetical - our server doesn't generate
  18356. // strong ETags, but if client sends a strong ETag that doesn't match, it
  18357. // should return full content)
  18358. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  18359. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  18360. ASSERT_TRUE(res4);
  18361. EXPECT_EQ(200, res4->status);
  18362. EXPECT_EQ(content, res4->body);
  18363. EXPECT_FALSE(res4->has_header("Content-Range"));
  18364. svr.stop();
  18365. t.join();
  18366. std::remove(fname);
  18367. }
  18368. TEST(ETagTest, IfRangeWithDate) {
  18369. using namespace httplib;
  18370. // Create a test file
  18371. const char *fname = "if_range_date_testfile.txt";
  18372. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  18373. {
  18374. std::ofstream ofs(fname);
  18375. ofs << content;
  18376. ASSERT_TRUE(ofs.good());
  18377. }
  18378. Server svr;
  18379. svr.set_mount_point("/static", ".");
  18380. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18381. svr.wait_until_ready();
  18382. Client cli(HOST, PORT);
  18383. // First request: get Last-Modified
  18384. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  18385. ASSERT_TRUE(res1);
  18386. ASSERT_EQ(200, res1->status);
  18387. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18388. std::string last_modified = res1->get_header_value("Last-Modified");
  18389. // Range request with matching If-Range (date): should get 206
  18390. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  18391. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  18392. ASSERT_TRUE(res2);
  18393. EXPECT_EQ(206, res2->status);
  18394. EXPECT_EQ("FGHIJ", res2->body);
  18395. // Range request with old If-Range date: should get 200 (full content)
  18396. Headers h3 = {{"Range", "bytes=5-9"},
  18397. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18398. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  18399. ASSERT_TRUE(res3);
  18400. EXPECT_EQ(200, res3->status);
  18401. EXPECT_EQ(content, res3->body);
  18402. // Range request with future If-Range date: should get 206
  18403. Headers h4 = {{"Range", "bytes=0-4"},
  18404. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18405. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  18406. ASSERT_TRUE(res4);
  18407. EXPECT_EQ(206, res4->status);
  18408. EXPECT_EQ("ABCDE", res4->body);
  18409. svr.stop();
  18410. t.join();
  18411. std::remove(fname);
  18412. }
  18413. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  18414. using namespace httplib;
  18415. const char *fname = "etag_malformed.txt";
  18416. const char *content = "malformed-etag";
  18417. {
  18418. std::ofstream ofs(fname);
  18419. ofs << content;
  18420. ASSERT_TRUE(ofs.good());
  18421. }
  18422. Server svr;
  18423. svr.set_mount_point("/static", ".");
  18424. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18425. svr.wait_until_ready();
  18426. Client cli(HOST, PORT);
  18427. // baseline: should get 200 and an ETag
  18428. auto res1 = cli.Get("/static/etag_malformed.txt");
  18429. ASSERT_TRUE(res1);
  18430. ASSERT_EQ(200, res1->status);
  18431. ASSERT_TRUE(res1->has_header("ETag"));
  18432. // Malformed ETag value (missing quotes) should be treated as non-matching
  18433. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  18434. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  18435. ASSERT_TRUE(res_bad);
  18436. EXPECT_EQ(200, res_bad->status);
  18437. // Whitespace-only header value should be considered invalid / non-matching
  18438. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  18439. "Host: localhost\r\n"
  18440. "If-None-Match: \r\n"
  18441. "Connection: close\r\n"
  18442. "\r\n";
  18443. std::string out;
  18444. ASSERT_TRUE(send_request(5, raw_req, &out));
  18445. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18446. svr.stop();
  18447. t.join();
  18448. std::remove(fname);
  18449. }
  18450. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  18451. using namespace httplib;
  18452. const char *fname = "ims_invalid_format.txt";
  18453. const char *content = "ims-bad-format";
  18454. {
  18455. std::ofstream ofs(fname);
  18456. ofs << content;
  18457. ASSERT_TRUE(ofs.good());
  18458. }
  18459. Server svr;
  18460. svr.set_mount_point("/static", ".");
  18461. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18462. svr.wait_until_ready();
  18463. Client cli(HOST, PORT);
  18464. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  18465. ASSERT_TRUE(res1);
  18466. ASSERT_EQ(200, res1->status);
  18467. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18468. // If-Modified-Since with invalid format should not result in 304
  18469. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  18470. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  18471. ASSERT_TRUE(res_bad);
  18472. EXPECT_EQ(200, res_bad->status);
  18473. // If-Range with invalid date format should be treated as mismatch -> full
  18474. // content (200)
  18475. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  18476. {"If-Range", "invalid-date"}};
  18477. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  18478. ASSERT_TRUE(res_ifrange);
  18479. EXPECT_EQ(200, res_ifrange->status);
  18480. svr.stop();
  18481. t.join();
  18482. std::remove(fname);
  18483. }
  18484. TEST(ETagTest, IfRangeWithMalformedETag) {
  18485. using namespace httplib;
  18486. const char *fname = "ifrange_malformed.txt";
  18487. const std::string content = "0123456789";
  18488. {
  18489. std::ofstream ofs(fname);
  18490. ofs << content;
  18491. ASSERT_TRUE(ofs.good());
  18492. }
  18493. Server svr;
  18494. svr.set_mount_point("/static", ".");
  18495. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18496. svr.wait_until_ready();
  18497. Client cli(HOST, PORT);
  18498. // First request: get ETag
  18499. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  18500. ASSERT_TRUE(res1);
  18501. ASSERT_EQ(200, res1->status);
  18502. ASSERT_TRUE(res1->has_header("ETag"));
  18503. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  18504. // full content (200)
  18505. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  18506. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  18507. ASSERT_TRUE(res2);
  18508. EXPECT_EQ(200, res2->status);
  18509. EXPECT_EQ(content, res2->body);
  18510. svr.stop();
  18511. t.join();
  18512. std::remove(fname);
  18513. }
  18514. TEST(ETagTest, ExtremeLargeDateValues) {
  18515. using namespace httplib;
  18516. const char *fname = "ims_extreme_date.txt";
  18517. const char *content = "ims-extreme-date";
  18518. {
  18519. std::ofstream ofs(fname);
  18520. ofs << content;
  18521. ASSERT_TRUE(ofs.good());
  18522. }
  18523. Server svr;
  18524. svr.set_mount_point("/static", ".");
  18525. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18526. svr.wait_until_ready();
  18527. Client cli(HOST, PORT);
  18528. auto res1 = cli.Get(std::string("/static/") + fname);
  18529. ASSERT_TRUE(res1);
  18530. ASSERT_EQ(200, res1->status);
  18531. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18532. // Extremely large year that may overflow date parsing routines.
  18533. Headers h_large_date = {
  18534. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18535. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  18536. ASSERT_TRUE(res_bad);
  18537. // Expect server to treat this as invalid/mismatch and return full content
  18538. EXPECT_EQ(200, res_bad->status);
  18539. // If-Range with extremely large date should be treated as mismatch -> full
  18540. // content (200)
  18541. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  18542. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18543. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  18544. ASSERT_TRUE(res_ifrange);
  18545. EXPECT_EQ(200, res_ifrange->status);
  18546. svr.stop();
  18547. t.join();
  18548. std::remove(fname);
  18549. }
  18550. TEST(ETagTest, NegativeFileModificationTime) {
  18551. using namespace httplib;
  18552. const char *fname = "ims_negative_mtime.txt";
  18553. const std::string content = "negative-mtime";
  18554. {
  18555. std::ofstream ofs(fname);
  18556. ofs << content;
  18557. ASSERT_TRUE(ofs.good());
  18558. }
  18559. // Try to set file mtime to a negative value. This may fail on some
  18560. // platforms/filesystems; if it fails, the test will still verify server
  18561. // behaves safely by performing a regular conditional request.
  18562. #if defined(__APPLE__) || defined(__linux__)
  18563. bool set_negative = false;
  18564. do {
  18565. struct timeval times[2];
  18566. // access time: now
  18567. times[0].tv_sec = time(nullptr);
  18568. times[0].tv_usec = 0;
  18569. // modification time: negative (e.g., -1)
  18570. times[1].tv_sec = -1;
  18571. times[1].tv_usec = 0;
  18572. if (utimes(fname, times) == 0) { set_negative = true; }
  18573. } while (0);
  18574. #else
  18575. bool set_negative = false;
  18576. #endif
  18577. Server svr;
  18578. svr.set_mount_point("/static", ".");
  18579. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18580. svr.wait_until_ready();
  18581. Client cli(HOST, PORT);
  18582. auto res1 = cli.Get(std::string("/static/") + fname);
  18583. ASSERT_TRUE(res1);
  18584. ASSERT_EQ(200, res1->status);
  18585. bool has_last_modified = res1->has_header("Last-Modified");
  18586. std::string last_modified;
  18587. if (has_last_modified) {
  18588. last_modified = res1->get_header_value("Last-Modified");
  18589. }
  18590. if (set_negative) {
  18591. // If we successfully set a negative mtime, ensure server returns a
  18592. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  18593. // with an old date and ensure server handles it without crash.
  18594. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  18595. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  18596. ASSERT_TRUE(res2);
  18597. // Behavior may vary; at minimum ensure server responds (200 or 304).
  18598. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  18599. } else {
  18600. // Could not set negative mtime on this platform; fall back to verifying
  18601. // that normal invalid/malformed dates are treated safely (non-304).
  18602. Headers h_bad_date = {
  18603. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18604. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  18605. ASSERT_TRUE(res_bad);
  18606. EXPECT_EQ(200, res_bad->status);
  18607. }
  18608. svr.stop();
  18609. t.join();
  18610. std::remove(fname);
  18611. }
  18612. //==============================================================================
  18613. // Integration Tests with Server
  18614. //==============================================================================
  18615. class SSEIntegrationTest : public ::testing::Test {
  18616. protected:
  18617. void SetUp() override {
  18618. stop_server_.store(false);
  18619. events_.clear();
  18620. server_ = httplib::detail::make_unique<Server>();
  18621. setup_server();
  18622. start_server();
  18623. }
  18624. void TearDown() override {
  18625. stop_server_.store(true);
  18626. event_cv_.notify_all();
  18627. server_->stop();
  18628. if (server_thread_.joinable()) { server_thread_.join(); }
  18629. }
  18630. void setup_server() {
  18631. // Simple SSE endpoint
  18632. server_->Get("/events", [this](const Request &req, Response &res) {
  18633. auto last_id = req.get_header_value("Last-Event-ID");
  18634. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  18635. res.set_chunked_content_provider(
  18636. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  18637. std::unique_lock<std::mutex> lock(event_mutex_);
  18638. if (event_cv_.wait_for(
  18639. lock, std::chrono::milliseconds(200), [this] {
  18640. return !events_.empty() || stop_server_.load();
  18641. })) {
  18642. if (stop_server_.load()) { return false; }
  18643. if (!events_.empty()) {
  18644. std::string event = events_.front();
  18645. events_.erase(events_.begin());
  18646. sink.write(event.data(), event.size());
  18647. return true;
  18648. }
  18649. }
  18650. return !stop_server_.load();
  18651. });
  18652. });
  18653. // Endpoint that returns error
  18654. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  18655. res.status = 500;
  18656. res.set_content("Internal Server Error", "text/plain");
  18657. });
  18658. // Endpoint for custom event types
  18659. server_->Get("/custom-events", [](const Request &, Response &res) {
  18660. res.set_chunked_content_provider(
  18661. "text/event-stream", [](size_t offset, DataSink &sink) {
  18662. if (offset == 0) {
  18663. std::string event = "event: update\ndata: updated\n\n"
  18664. "event: delete\ndata: deleted\n\n";
  18665. sink.write(event.data(), event.size());
  18666. }
  18667. return false; // End stream after sending
  18668. });
  18669. });
  18670. }
  18671. void start_server() {
  18672. port_ = server_->bind_to_any_port(HOST);
  18673. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18674. // Wait for server to start
  18675. while (!server_->is_running()) {
  18676. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18677. }
  18678. }
  18679. int get_port() const { return port_; }
  18680. void send_event(const std::string &event) {
  18681. std::lock_guard<std::mutex> lock(event_mutex_);
  18682. events_.push_back(event);
  18683. event_cv_.notify_all();
  18684. }
  18685. std::unique_ptr<Server> server_;
  18686. std::thread server_thread_;
  18687. std::mutex event_mutex_;
  18688. std::condition_variable event_cv_;
  18689. std::vector<std::string> events_;
  18690. std::atomic<bool> stop_server_{false};
  18691. std::string last_received_event_id_;
  18692. int port_ = 0;
  18693. };
  18694. //==============================================================================
  18695. // SSE Parsing Tests
  18696. //==============================================================================
  18697. class SSEParsingTest : public SSEIntegrationTest {
  18698. protected:
  18699. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  18700. // A trailing sentinel event tells when the whole stream has been parsed.
  18701. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  18702. auto body = stream + "event: end\ndata: end\n\n";
  18703. server_->Get("/parse", [body](const Request &, Response &res) {
  18704. res.set_content(body, "text/event-stream");
  18705. });
  18706. return collect("/parse");
  18707. }
  18708. // Runs SSEClient against path until an "end" event arrives and returns the
  18709. // messages dispatched before it
  18710. std::vector<sse::SSEMessage> collect(const std::string &path) {
  18711. Client client(HOST, get_port());
  18712. sse::SSEClient sse(client, path);
  18713. std::mutex mutex;
  18714. std::condition_variable cv;
  18715. std::vector<sse::SSEMessage> messages;
  18716. auto done = false;
  18717. sse.on_message([&](const sse::SSEMessage &msg) {
  18718. std::lock_guard<std::mutex> lock(mutex);
  18719. // Ignore a replay from a reconnect that races with stop()
  18720. if (!done) { messages.push_back(msg); }
  18721. });
  18722. sse.on_event("end", [&](const sse::SSEMessage &) {
  18723. std::lock_guard<std::mutex> lock(mutex);
  18724. done = true;
  18725. cv.notify_all();
  18726. });
  18727. sse.set_reconnect_interval(100);
  18728. sse.start_async();
  18729. {
  18730. std::unique_lock<std::mutex> lock(mutex);
  18731. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  18732. }
  18733. sse.stop();
  18734. EXPECT_TRUE(done);
  18735. return messages;
  18736. }
  18737. };
  18738. TEST_F(SSEParsingTest, SingleLineData) {
  18739. auto msgs = parse("data: hello\n\n");
  18740. ASSERT_EQ(msgs.size(), 1u);
  18741. EXPECT_EQ(msgs[0].data, "hello");
  18742. EXPECT_EQ(msgs[0].event, "message");
  18743. }
  18744. TEST_F(SSEParsingTest, MultiLineData) {
  18745. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  18746. ASSERT_EQ(msgs.size(), 1u);
  18747. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  18748. }
  18749. TEST_F(SSEParsingTest, CustomEventType) {
  18750. auto msgs = parse("event: update\ndata: payload\n\n");
  18751. ASSERT_EQ(msgs.size(), 1u);
  18752. EXPECT_EQ(msgs[0].event, "update");
  18753. EXPECT_EQ(msgs[0].data, "payload");
  18754. }
  18755. TEST_F(SSEParsingTest, EventIdHandling) {
  18756. auto msgs = parse("id: 12345\ndata: test\n\n");
  18757. ASSERT_EQ(msgs.size(), 1u);
  18758. EXPECT_EQ(msgs[0].id, "12345");
  18759. }
  18760. TEST_F(SSEParsingTest, EmptyEventId) {
  18761. auto msgs = parse("id:\ndata: test\n\n");
  18762. ASSERT_EQ(msgs.size(), 1u);
  18763. EXPECT_EQ(msgs[0].id, "");
  18764. }
  18765. TEST_F(SSEParsingTest, CommentsIgnored) {
  18766. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  18767. ASSERT_EQ(msgs.size(), 1u);
  18768. EXPECT_EQ(msgs[0].data, "hello");
  18769. EXPECT_EQ(msgs[0].event, "message");
  18770. }
  18771. TEST_F(SSEParsingTest, ColonInValue) {
  18772. auto msgs = parse("data: hello:world:test\n\n");
  18773. ASSERT_EQ(msgs.size(), 1u);
  18774. EXPECT_EQ(msgs[0].data, "hello:world:test");
  18775. }
  18776. TEST_F(SSEParsingTest, FieldNameOnly) {
  18777. // A line without a colon is a field name with an empty value
  18778. auto msgs = parse("data\n\n");
  18779. ASSERT_EQ(msgs.size(), 1u);
  18780. EXPECT_EQ(msgs[0].data, "");
  18781. }
  18782. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  18783. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  18784. ASSERT_EQ(msgs.size(), 1u);
  18785. EXPECT_EQ(msgs[0].event, "update");
  18786. EXPECT_EQ(msgs[0].data, "hello");
  18787. }
  18788. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  18789. auto msgs = parse("data\r\n\r\n");
  18790. ASSERT_EQ(msgs.size(), 1u);
  18791. EXPECT_EQ(msgs[0].data, "");
  18792. }
  18793. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  18794. auto msgs = parse("unknown: value\ndata: hello\n\n");
  18795. ASSERT_EQ(msgs.size(), 1u);
  18796. EXPECT_EQ(msgs[0].data, "hello");
  18797. EXPECT_EQ(msgs[0].event, "message");
  18798. }
  18799. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  18800. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  18801. ASSERT_EQ(msgs.size(), 2u);
  18802. EXPECT_EQ(msgs[0].data, "hello");
  18803. EXPECT_EQ(msgs[1].data, "hello");
  18804. }
  18805. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  18806. // An event without data is not dispatched, and its type must not leak
  18807. // into the next event
  18808. auto msgs = parse("event: update\n\ndata: hello\n\n");
  18809. ASSERT_EQ(msgs.size(), 1u);
  18810. EXPECT_EQ(msgs[0].event, "message");
  18811. EXPECT_EQ(msgs[0].data, "hello");
  18812. }
  18813. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  18814. // The first connection sends only an id; the second echoes back the
  18815. // Last-Event-ID it was reconnected with
  18816. std::atomic<int> connection_count{0};
  18817. server_->Get("/id-only", [&](const Request &req, Response &res) {
  18818. if (connection_count++ == 0) {
  18819. res.set_content("id: 42\n\n", "text/event-stream");
  18820. } else {
  18821. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  18822. "\n\nevent: end\ndata: end\n\n",
  18823. "text/event-stream");
  18824. }
  18825. });
  18826. auto msgs = collect("/id-only");
  18827. ASSERT_EQ(msgs.size(), 1u);
  18828. EXPECT_EQ(msgs[0].data, "42");
  18829. }
  18830. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  18831. // The first connection sets an id and then clears it with an empty one; the
  18832. // second reports whether it was reconnected with a Last-Event-ID
  18833. std::atomic<int> connection_count{0};
  18834. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  18835. if (connection_count++ == 0) {
  18836. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  18837. "text/event-stream");
  18838. } else {
  18839. res.set_content(
  18840. std::string("data: ") +
  18841. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  18842. "\n\nevent: end\ndata: end\n\n",
  18843. "text/event-stream");
  18844. }
  18845. });
  18846. auto msgs = collect("/id-clear");
  18847. ASSERT_EQ(msgs.size(), 3u);
  18848. EXPECT_EQ(msgs[0].id, "1");
  18849. EXPECT_EQ(msgs[1].id, "");
  18850. EXPECT_EQ(msgs[2].data, "not sent");
  18851. }
  18852. TEST_F(SSEParsingTest, CompleteEventParsing) {
  18853. auto msgs = parse("event: notification\nid: evt-42\n"
  18854. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  18855. ASSERT_EQ(msgs.size(), 1u);
  18856. EXPECT_EQ(msgs[0].event, "notification");
  18857. EXPECT_EQ(msgs[0].id, "evt-42");
  18858. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  18859. }
  18860. TEST(SSEMessageTest, Clear) {
  18861. sse::SSEMessage msg;
  18862. msg.event = "custom";
  18863. msg.data = "some data";
  18864. msg.id = "123";
  18865. msg.clear();
  18866. EXPECT_EQ(msg.event, "message");
  18867. EXPECT_EQ(msg.data, "");
  18868. EXPECT_EQ(msg.id, "");
  18869. }
  18870. //==============================================================================
  18871. // SSE Integration Tests
  18872. //==============================================================================
  18873. // Test: Successful connection and on_open callback
  18874. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  18875. // Add a simple endpoint that sends one event and closes
  18876. server_->Get("/simple-event", [](const Request &, Response &res) {
  18877. res.set_chunked_content_provider(
  18878. "text/event-stream", [](size_t offset, DataSink &sink) {
  18879. if (offset == 0) {
  18880. std::string event = "data: hello\n\n";
  18881. sink.write(event.data(), event.size());
  18882. }
  18883. return false; // Close stream after sending
  18884. });
  18885. });
  18886. Client client("localhost", get_port());
  18887. sse::SSEClient sse(client, "/simple-event");
  18888. std::atomic<bool> open_called{false};
  18889. std::atomic<bool> message_received{false};
  18890. sse.on_open([&open_called]() { open_called.store(true); });
  18891. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  18892. if (msg.data == "hello") { message_received.store(true); }
  18893. });
  18894. sse.set_reconnect_interval(100);
  18895. sse.set_max_reconnect_attempts(1);
  18896. // Start async
  18897. sse.start_async();
  18898. // Wait for message to be processed
  18899. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18900. sse.stop();
  18901. EXPECT_TRUE(open_called.load());
  18902. EXPECT_TRUE(message_received.load());
  18903. }
  18904. // Test: on_message callback
  18905. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  18906. // Endpoint that sends multiple events then closes
  18907. server_->Get("/multi-event", [](const Request &, Response &res) {
  18908. res.set_chunked_content_provider(
  18909. "text/event-stream", [](size_t offset, DataSink &sink) {
  18910. if (offset == 0) {
  18911. std::string events = "data: message1\n\ndata: message2\n\n";
  18912. sink.write(events.data(), events.size());
  18913. }
  18914. return false;
  18915. });
  18916. });
  18917. Client client("localhost", get_port());
  18918. sse::SSEClient sse(client, "/multi-event");
  18919. std::vector<std::string> received_messages;
  18920. std::mutex messages_mutex;
  18921. sse.on_message([&](const sse::SSEMessage &msg) {
  18922. std::lock_guard<std::mutex> lock(messages_mutex);
  18923. received_messages.push_back(msg.data);
  18924. });
  18925. sse.set_reconnect_interval(100);
  18926. sse.set_max_reconnect_attempts(1);
  18927. sse.start_async();
  18928. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18929. sse.stop();
  18930. std::lock_guard<std::mutex> lock(messages_mutex);
  18931. EXPECT_GE(received_messages.size(), 2u);
  18932. if (received_messages.size() >= 2) {
  18933. EXPECT_EQ(received_messages[0], "message1");
  18934. EXPECT_EQ(received_messages[1], "message2");
  18935. }
  18936. }
  18937. // Test: on_event for specific types
  18938. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  18939. Client client("localhost", get_port());
  18940. sse::SSEClient sse(client, "/custom-events");
  18941. std::atomic<bool> update_received{false};
  18942. std::atomic<bool> delete_received{false};
  18943. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  18944. if (msg.data == "updated") { update_received.store(true); }
  18945. });
  18946. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  18947. if (msg.data == "deleted") { delete_received.store(true); }
  18948. });
  18949. sse.set_max_reconnect_attempts(1);
  18950. sse.start_async();
  18951. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  18952. sse.stop();
  18953. EXPECT_TRUE(update_received.load());
  18954. EXPECT_TRUE(delete_received.load());
  18955. }
  18956. // Test: on_error callback on connection failure
  18957. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  18958. // Connect to a non-existent port
  18959. Client client("localhost", 59999);
  18960. sse::SSEClient sse(client, "/events");
  18961. std::atomic<bool> error_called{false};
  18962. Error received_error = Error::Success;
  18963. sse.on_error([&](Error err) {
  18964. error_called.store(true);
  18965. received_error = err;
  18966. });
  18967. sse.set_reconnect_interval(50);
  18968. sse.set_max_reconnect_attempts(1);
  18969. sse.start_async();
  18970. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18971. sse.stop();
  18972. EXPECT_TRUE(error_called.load());
  18973. EXPECT_NE(received_error, Error::Success);
  18974. }
  18975. // Test: Last-Event-ID header sent on reconnect
  18976. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  18977. // Endpoint that sends event with ID
  18978. server_->Get("/event-with-id", [](const Request &, Response &res) {
  18979. res.set_chunked_content_provider(
  18980. "text/event-stream", [](size_t offset, DataSink &sink) {
  18981. if (offset == 0) {
  18982. std::string event = "id: evt-123\ndata: test\n\n";
  18983. sink.write(event.data(), event.size());
  18984. }
  18985. return false;
  18986. });
  18987. });
  18988. Client client("localhost", get_port());
  18989. sse::SSEClient sse(client, "/event-with-id");
  18990. std::atomic<bool> id_received{false};
  18991. sse.on_message([&](const sse::SSEMessage &msg) {
  18992. if (!msg.id.empty()) { id_received.store(true); }
  18993. });
  18994. sse.set_reconnect_interval(100);
  18995. sse.set_max_reconnect_attempts(1);
  18996. sse.start_async();
  18997. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18998. sse.stop();
  18999. EXPECT_TRUE(id_received.load());
  19000. EXPECT_EQ(sse.last_event_id(), "evt-123");
  19001. }
  19002. // Test: Manual stop
  19003. TEST_F(SSEIntegrationTest, ManualStop) {
  19004. // Endpoint that sends one event and stays open briefly
  19005. std::atomic<bool> handler_running{true};
  19006. server_->Get("/stay-open", [&handler_running](const Request &,
  19007. Response &res) {
  19008. res.set_chunked_content_provider(
  19009. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  19010. if (offset == 0) {
  19011. std::string event = "data: connected\n\n";
  19012. sink.write(event.data(), event.size());
  19013. }
  19014. // Keep connection open while handler_running is true
  19015. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  19016. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19017. }
  19018. return false;
  19019. });
  19020. });
  19021. Client client("localhost", get_port());
  19022. sse::SSEClient sse(client, "/stay-open");
  19023. std::atomic<bool> connected{false};
  19024. sse.on_open([&connected]() { connected.store(true); });
  19025. sse.set_reconnect_interval(100);
  19026. sse.set_max_reconnect_attempts(1);
  19027. sse.start_async();
  19028. // Wait for connection to establish
  19029. for (int i = 0; i < 20 && !connected.load(); ++i) {
  19030. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19031. }
  19032. EXPECT_TRUE(connected.load());
  19033. EXPECT_TRUE(sse.is_connected());
  19034. // Signal handler to stop
  19035. handler_running.store(false);
  19036. // Stop SSE client
  19037. sse.stop();
  19038. EXPECT_FALSE(sse.is_connected());
  19039. }
  19040. // Test: SSEClient with custom headers
  19041. TEST_F(SSEIntegrationTest, CustomHeaders) {
  19042. // Setup a server endpoint that checks for custom header
  19043. std::atomic<bool> header_received{false};
  19044. server_->Get("/header-check", [&](const Request &req, Response &res) {
  19045. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  19046. header_received.store(true);
  19047. }
  19048. res.set_chunked_content_provider("text/event-stream",
  19049. [](size_t, DataSink &) { return false; });
  19050. });
  19051. Client client("localhost", get_port());
  19052. Headers headers = {{"X-Custom-Header", "custom-value"}};
  19053. sse::SSEClient sse(client, "/header-check", headers);
  19054. sse.set_max_reconnect_attempts(1);
  19055. sse.start_async();
  19056. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19057. sse.stop();
  19058. EXPECT_TRUE(header_received.load());
  19059. }
  19060. // Test: Reconnect interval configuration
  19061. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  19062. Client client("localhost", get_port());
  19063. sse::SSEClient sse(client, "/events");
  19064. auto &result = sse.set_reconnect_interval(500);
  19065. // Builder pattern should return reference to self
  19066. EXPECT_EQ(&result, &sse);
  19067. }
  19068. // Test: Max reconnect attempts
  19069. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  19070. // Connect to non-existent port to force reconnects
  19071. Client client("localhost", 59998);
  19072. sse::SSEClient sse(client, "/events");
  19073. std::atomic<int> error_count{0};
  19074. sse.on_error([&](Error) { error_count.fetch_add(1); });
  19075. sse.set_reconnect_interval(50);
  19076. sse.set_max_reconnect_attempts(2);
  19077. auto start = std::chrono::steady_clock::now();
  19078. sse.start(); // Blocking call
  19079. auto end = std::chrono::steady_clock::now();
  19080. // Should have stopped after 2 failed attempts
  19081. EXPECT_GE(error_count.load(), 2);
  19082. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  19083. auto duration =
  19084. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  19085. #ifdef _WIN32
  19086. // Windows is much slower for socket connection failures
  19087. EXPECT_LT(duration.count(), 7000);
  19088. #else
  19089. EXPECT_LT(duration.count(), 1000);
  19090. #endif
  19091. }
  19092. // Test: Multi-line data in integration
  19093. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  19094. // Endpoint with multi-line data
  19095. server_->Get("/multiline-data", [](const Request &, Response &res) {
  19096. res.set_chunked_content_provider(
  19097. "text/event-stream", [](size_t offset, DataSink &sink) {
  19098. if (offset == 0) {
  19099. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  19100. sink.write(event.data(), event.size());
  19101. }
  19102. return false;
  19103. });
  19104. });
  19105. Client client("localhost", get_port());
  19106. sse::SSEClient sse(client, "/multiline-data");
  19107. std::string received_data;
  19108. std::mutex data_mutex;
  19109. sse.on_message([&](const sse::SSEMessage &msg) {
  19110. std::lock_guard<std::mutex> lock(data_mutex);
  19111. received_data = msg.data;
  19112. });
  19113. sse.set_reconnect_interval(100);
  19114. sse.set_max_reconnect_attempts(1);
  19115. sse.start_async();
  19116. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19117. sse.stop();
  19118. std::lock_guard<std::mutex> lock(data_mutex);
  19119. EXPECT_EQ(received_data, "line1\nline2\nline3");
  19120. }
  19121. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  19122. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  19123. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  19124. DataSink &sink) {
  19125. if (offset == 0) {
  19126. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  19127. sink.write(events.data(), events.size());
  19128. }
  19129. return false;
  19130. });
  19131. });
  19132. Client client("localhost", get_port());
  19133. sse::SSEClient sse(client, "/empty-data-lines");
  19134. std::mutex mutex;
  19135. std::condition_variable cv;
  19136. std::vector<std::string> received;
  19137. sse.on_message([&](const sse::SSEMessage &msg) {
  19138. std::lock_guard<std::mutex> lock(mutex);
  19139. received.push_back(msg.data);
  19140. cv.notify_all();
  19141. });
  19142. sse.set_max_reconnect_attempts(1);
  19143. sse.start_async();
  19144. {
  19145. std::unique_lock<std::mutex> lock(mutex);
  19146. cv.wait_for(lock, std::chrono::seconds(2),
  19147. [&] { return received.size() >= 3; });
  19148. }
  19149. sse.stop();
  19150. ASSERT_GE(received.size(), 3u);
  19151. EXPECT_EQ(received[0], "");
  19152. EXPECT_EQ(received[1], "\nhello");
  19153. EXPECT_EQ(received[2], "");
  19154. }
  19155. // Test: Auto-reconnect after server disconnection
  19156. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  19157. std::atomic<int> connection_count{0};
  19158. std::atomic<int> message_count{0};
  19159. // Endpoint that sends one event and closes, forcing reconnect
  19160. server_->Get("/reconnect-test",
  19161. [&connection_count](const Request &, Response &res) {
  19162. connection_count.fetch_add(1);
  19163. res.set_chunked_content_provider(
  19164. "text/event-stream", [](size_t offset, DataSink &sink) {
  19165. if (offset == 0) {
  19166. std::string event = "data: hello\n\n";
  19167. sink.write(event.data(), event.size());
  19168. }
  19169. return false; // Close connection after sending
  19170. });
  19171. });
  19172. Client client("localhost", get_port());
  19173. sse::SSEClient sse(client, "/reconnect-test");
  19174. sse.on_message([&message_count](const sse::SSEMessage &) {
  19175. message_count.fetch_add(1);
  19176. });
  19177. sse.set_reconnect_interval(100);
  19178. sse.set_max_reconnect_attempts(3);
  19179. sse.start_async();
  19180. // Wait long enough for multiple reconnects
  19181. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19182. sse.stop();
  19183. // Should have connected multiple times (initial + reconnects)
  19184. EXPECT_GE(connection_count.load(), 2);
  19185. // Should have received messages from multiple connections
  19186. EXPECT_GE(message_count.load(), 2);
  19187. }
  19188. // Test: A retry field that is not all ASCII digits is ignored
  19189. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  19190. std::atomic<int> connection_count{0};
  19191. server_->Get("/bad-retry",
  19192. [&connection_count](const Request &, Response &res) {
  19193. connection_count.fetch_add(1);
  19194. res.set_chunked_content_provider(
  19195. "text/event-stream", [](size_t offset, DataSink &sink) {
  19196. if (offset == 0) {
  19197. std::string event = "retry: -1\ndata: hello\n\n";
  19198. sink.write(event.data(), event.size());
  19199. }
  19200. return false;
  19201. });
  19202. });
  19203. Client client("localhost", get_port());
  19204. sse::SSEClient sse(client, "/bad-retry");
  19205. sse.set_reconnect_interval(10000);
  19206. sse.start_async();
  19207. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19208. sse.stop();
  19209. EXPECT_EQ(connection_count.load(), 1);
  19210. }
  19211. // Test: A retry field of all ASCII digits sets the reconnection time
  19212. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  19213. std::atomic<int> connection_count{0};
  19214. server_->Get("/zero-retry",
  19215. [&connection_count](const Request &, Response &res) {
  19216. connection_count.fetch_add(1);
  19217. res.set_chunked_content_provider(
  19218. "text/event-stream", [](size_t offset, DataSink &sink) {
  19219. if (offset == 0) {
  19220. std::string event = "retry: 0\ndata: hello\n\n";
  19221. sink.write(event.data(), event.size());
  19222. }
  19223. return false;
  19224. });
  19225. });
  19226. Client client("localhost", get_port());
  19227. sse::SSEClient sse(client, "/zero-retry");
  19228. sse.set_reconnect_interval(10000);
  19229. sse.start_async();
  19230. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19231. sse.stop();
  19232. // The server-supplied interval is applied, but never below 100ms, so
  19233. // "retry: 0" does not cause a busy reconnect loop
  19234. EXPECT_GE(connection_count.load(), 2);
  19235. EXPECT_LE(connection_count.load(), 10);
  19236. }
  19237. // Test: Last-Event-ID sent on reconnect
  19238. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  19239. std::atomic<int> connection_count{0};
  19240. std::vector<std::string> received_last_event_ids;
  19241. std::mutex id_mutex;
  19242. // Endpoint that checks Last-Event-ID header and sends event with ID
  19243. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  19244. int conn = connection_count.fetch_add(1);
  19245. // Capture the Last-Event-ID header from each connection
  19246. {
  19247. std::lock_guard<std::mutex> lock(id_mutex);
  19248. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  19249. }
  19250. res.set_chunked_content_provider(
  19251. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  19252. if (offset == 0) {
  19253. std::string event =
  19254. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  19255. sink.write(event.data(), event.size());
  19256. }
  19257. return false;
  19258. });
  19259. });
  19260. Client client("localhost", get_port());
  19261. sse::SSEClient sse(client, "/reconnect-with-id");
  19262. sse.set_reconnect_interval(100);
  19263. sse.set_max_reconnect_attempts(3);
  19264. sse.start_async();
  19265. // Wait for at least 2 connections
  19266. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19267. sse.stop();
  19268. // Verify behavior
  19269. std::lock_guard<std::mutex> lock(id_mutex);
  19270. EXPECT_GE(received_last_event_ids.size(), 2u);
  19271. // First connection should have no Last-Event-ID
  19272. if (!received_last_event_ids.empty()) {
  19273. EXPECT_EQ(received_last_event_ids[0], "");
  19274. }
  19275. // Second connection should have Last-Event-ID from first connection
  19276. if (received_last_event_ids.size() >= 2) {
  19277. EXPECT_EQ(received_last_event_ids[1], "event-0");
  19278. }
  19279. }
  19280. // Test: set_headers updates headers used on reconnect
  19281. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  19282. std::vector<std::string> received_tokens;
  19283. std::mutex token_mutex;
  19284. // Endpoint that captures Authorization header
  19285. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  19286. {
  19287. std::lock_guard<std::mutex> lock(token_mutex);
  19288. received_tokens.push_back(req.get_header_value("Authorization"));
  19289. }
  19290. res.set_chunked_content_provider(
  19291. "text/event-stream", [](size_t offset, DataSink &sink) {
  19292. if (offset == 0) {
  19293. std::string event = "data: hello\n\n";
  19294. sink.write(event.data(), event.size());
  19295. }
  19296. return false; // Close connection to trigger reconnect
  19297. });
  19298. });
  19299. Client client("localhost", get_port());
  19300. Headers headers = {{"Authorization", "Bearer old-token"}};
  19301. sse::SSEClient sse(client, "/auth-check", headers);
  19302. // Update headers on each successful connection
  19303. sse.on_open(
  19304. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  19305. sse.set_reconnect_interval(100);
  19306. sse.set_max_reconnect_attempts(3);
  19307. sse.start_async();
  19308. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19309. sse.stop();
  19310. std::lock_guard<std::mutex> lock(token_mutex);
  19311. ASSERT_GE(received_tokens.size(), 2u);
  19312. // First connection uses original header
  19313. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  19314. // Second connection uses updated header from set_headers
  19315. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  19316. }
  19317. // Test: 401 allows reconnection (so on_error can refresh headers)
  19318. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  19319. std::atomic<int> connection_count{0};
  19320. // Endpoint: returns 401 on first attempt, 200 on second
  19321. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  19322. int conn = connection_count.fetch_add(1);
  19323. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  19324. res.status = StatusCode::Unauthorized_401;
  19325. res.set_content("Unauthorized", "text/plain");
  19326. return;
  19327. }
  19328. res.set_chunked_content_provider(
  19329. "text/event-stream", [](size_t offset, DataSink &sink) {
  19330. if (offset == 0) {
  19331. std::string event = "data: authenticated\n\n";
  19332. sink.write(event.data(), event.size());
  19333. }
  19334. return false;
  19335. });
  19336. });
  19337. Client client("localhost", get_port());
  19338. Headers headers = {{"Authorization", "Bearer expired"}};
  19339. sse::SSEClient sse(client, "/auth-retry", headers);
  19340. std::atomic<bool> message_received{false};
  19341. // Refresh token on error
  19342. sse.on_error(
  19343. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  19344. sse.on_message([&](const sse::SSEMessage &msg) {
  19345. if (msg.data == "authenticated") { message_received.store(true); }
  19346. });
  19347. sse.set_reconnect_interval(100);
  19348. sse.set_max_reconnect_attempts(3);
  19349. sse.start_async();
  19350. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19351. sse.stop();
  19352. // Should have reconnected after 401 and succeeded with new token
  19353. EXPECT_GE(connection_count.load(), 2);
  19354. EXPECT_TRUE(message_received.load());
  19355. }
  19356. TEST(Issue2318Test, EmptyHostString) {
  19357. {
  19358. httplib::Client cli_empty("", PORT);
  19359. auto res = cli_empty.Get("/");
  19360. ASSERT_FALSE(res);
  19361. EXPECT_EQ(httplib::Error::Connection, res.error());
  19362. }
  19363. {
  19364. httplib::Client cli(" ", PORT);
  19365. auto res = cli.Get("/");
  19366. ASSERT_FALSE(res);
  19367. EXPECT_EQ(httplib::Error::Connection, res.error());
  19368. }
  19369. }
  19370. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19371. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  19372. Server svr;
  19373. // Set a small payload limit (1KB)
  19374. svr.set_payload_max_length(1024);
  19375. svr.Post("/test", [&](const Request &req, Response &res) {
  19376. res.set_content("Body size: " + std::to_string(req.body.size()),
  19377. "text/plain");
  19378. });
  19379. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19380. auto se = detail::scope_exit([&] {
  19381. svr.stop();
  19382. listen_thread.join();
  19383. });
  19384. svr.wait_until_ready();
  19385. // Create data that compresses well but exceeds limit when decompressed
  19386. // 8KB of repeated null bytes compresses to a very small size
  19387. std::string original_data(8 * 1024, '\0');
  19388. // Compress the data using gzip
  19389. std::string compressed_data;
  19390. detail::gzip_compressor compressor;
  19391. compressor.compress(original_data.data(), original_data.size(), true,
  19392. [&](const char *data, size_t size) {
  19393. compressed_data.append(data, size);
  19394. return true;
  19395. });
  19396. // Verify compression worked (compressed should be much smaller)
  19397. ASSERT_LT(compressed_data.size(), original_data.size());
  19398. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  19399. // Send compressed data with Content-Encoding: gzip
  19400. Client cli(HOST, PORT);
  19401. Headers headers = {{"Content-Encoding", "gzip"}};
  19402. auto res =
  19403. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  19404. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  19405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19406. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  19407. }
  19408. #endif
  19409. // ============================================================================
  19410. // OpenSSL-Specific Tests
  19411. // ============================================================================
  19412. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  19413. X509 *readCertificate(const std::string &strFileName) {
  19414. std::ifstream inStream(strFileName);
  19415. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  19416. std::istreambuf_iterator<char>());
  19417. if (strCertPEM.empty()) return (nullptr);
  19418. BIO *pbCert = BIO_new(BIO_s_mem());
  19419. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  19420. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  19421. BIO_free(pbCert);
  19422. return (pCert);
  19423. }
  19424. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  19425. std::ifstream inStream(strFileName);
  19426. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  19427. std::istreambuf_iterator<char>());
  19428. if (strPrivateKeyPEM.empty()) return (nullptr);
  19429. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  19430. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  19431. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  19432. BIO_free(pbPrivKey);
  19433. return (pPrivateKey);
  19434. }
  19435. TEST(BindServerTest, UpdateCerts) {
  19436. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19437. int port = svr.bind_to_any_port("0.0.0.0");
  19438. ASSERT_TRUE(svr.is_valid());
  19439. ASSERT_TRUE(port > 0);
  19440. X509 *cert = readCertificate(SERVER_CERT_FILE);
  19441. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  19442. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  19443. ASSERT_TRUE(cert != nullptr);
  19444. ASSERT_TRUE(ca_cert != nullptr);
  19445. ASSERT_TRUE(key != nullptr);
  19446. X509_STORE *cert_store = X509_STORE_new();
  19447. X509_STORE_add_cert(cert_store, ca_cert);
  19448. // svr.update_certs(cert, key, cert_store); // deprecated
  19449. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  19450. CLIENT_CA_CERT_FILE);
  19451. ASSERT_TRUE(svr.is_valid());
  19452. svr.stop();
  19453. X509_STORE_free(cert_store);
  19454. X509_free(cert);
  19455. X509_free(ca_cert);
  19456. EVP_PKEY_free(key);
  19457. }
  19458. // Test that update_certs() updates client CA list correctly
  19459. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  19460. // Start with file-based constructor
  19461. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19462. ASSERT_TRUE(svr.is_valid());
  19463. // Initially no client CA list should be set
  19464. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19465. ASSERT_TRUE(ssl_ctx != nullptr);
  19466. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  19467. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  19468. EXPECT_EQ(0, count_before);
  19469. // Now update with client CA (PEM string)
  19470. std::string cert_pem, key_pem, ca_pem;
  19471. read_file(SERVER_CERT_FILE, cert_pem);
  19472. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  19473. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  19474. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  19475. ASSERT_TRUE(svr.is_valid());
  19476. // Now client CA list should be set
  19477. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  19478. ASSERT_TRUE(ca_list_after != nullptr);
  19479. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  19480. }
  19481. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  19482. // Test that the file-path SSLServer constructor properly sets the client CA
  19483. // list that is sent to clients during the TLS handshake (CertificateRequest)
  19484. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19485. ASSERT_TRUE(svr.is_valid());
  19486. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19487. ASSERT_TRUE(ssl_ctx != nullptr);
  19488. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  19489. ASSERT_TRUE(ca_list != nullptr);
  19490. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  19491. }
  19492. #endif
  19493. // ============================================================================
  19494. // MbedTLS-Specific Tests
  19495. // ============================================================================
  19496. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  19497. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  19498. using namespace httplib::tls;
  19499. // Track if callback was invoked
  19500. bool callback_invoked = false;
  19501. // The callback receives void* ctx which is actually MbedTlsContext*
  19502. // We can access the mbedtls_ssl_config via the context
  19503. auto setup_callback = [&callback_invoked](void *ctx) {
  19504. callback_invoked = true;
  19505. // Cast to MbedTlsContext* to access the ssl config
  19506. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  19507. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  19508. // Use static variables to hold certificate data (simplified for test)
  19509. static mbedtls_x509_crt own_cert;
  19510. static mbedtls_pk_context own_key;
  19511. static mbedtls_x509_crt ca_chain;
  19512. static bool initialized = false;
  19513. if (!initialized) {
  19514. mbedtls_x509_crt_init(&own_cert);
  19515. mbedtls_pk_init(&own_key);
  19516. mbedtls_x509_crt_init(&ca_chain);
  19517. // Load server certificate
  19518. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  19519. return false;
  19520. }
  19521. // Load server private key.
  19522. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  19523. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  19524. #if MBEDTLS_VERSION_MAJOR == 3
  19525. ,
  19526. mbedtls_ctr_drbg_random, nullptr
  19527. #endif
  19528. ) != 0) {
  19529. return false;
  19530. }
  19531. // Load CA chain for client verification
  19532. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  19533. return false;
  19534. }
  19535. initialized = true;
  19536. }
  19537. // Configure the SSL config
  19538. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  19539. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  19540. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  19541. // Set minimum TLS version using mbedTLS native API
  19542. #if MBEDTLS_VERSION_MAJOR >= 3
  19543. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  19544. #else
  19545. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  19546. MBEDTLS_SSL_MINOR_VERSION_3);
  19547. #endif
  19548. return true;
  19549. };
  19550. SSLServer svr(setup_callback);
  19551. ASSERT_TRUE(svr.is_valid());
  19552. ASSERT_TRUE(callback_invoked);
  19553. svr.Get("/test", [&](const Request &req, Response &res) {
  19554. res.set_content("test", "text/plain");
  19555. auto cert = req.peer_cert();
  19556. ASSERT_TRUE(static_cast<bool>(cert));
  19557. auto common_name = cert.subject_cn();
  19558. EXPECT_EQ("Common Name", common_name);
  19559. });
  19560. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19561. auto se = detail::scope_exit([&] {
  19562. svr.stop();
  19563. t.join();
  19564. ASSERT_FALSE(svr.is_running());
  19565. });
  19566. svr.wait_until_ready();
  19567. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  19568. cli.enable_server_certificate_verification(false);
  19569. cli.set_connection_timeout(30);
  19570. auto res = cli.Get("/test");
  19571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19572. ASSERT_EQ(StatusCode::OK_200, res->status);
  19573. }
  19574. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  19575. // context (owning mbedtls_ssl_config) before shutting down a still-open
  19576. // keep-alive SSL session, which reads through that config in
  19577. // mbedtls_ssl_close_notify.
  19578. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  19579. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19580. ASSERT_TRUE(svr.is_valid());
  19581. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19582. res.set_content("test", "text/plain");
  19583. });
  19584. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19585. auto se = detail::scope_exit([&] {
  19586. svr.stop();
  19587. t.join();
  19588. ASSERT_FALSE(svr.is_running());
  19589. });
  19590. svr.wait_until_ready();
  19591. {
  19592. SSLClient cli(HOST, PORT);
  19593. cli.enable_server_certificate_verification(false);
  19594. cli.set_keep_alive(true);
  19595. auto res = cli.Get("/test");
  19596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19597. ASSERT_EQ(StatusCode::OK_200, res->status);
  19598. // cli is destructed here with the keep-alive SSL session still open.
  19599. }
  19600. }
  19601. #endif
  19602. // WebSocket Tests
  19603. TEST(WebSocketTest, RSVBitsMustBeZero) {
  19604. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  19605. // defining the meaning of these bits has been negotiated.
  19606. auto make_frame = [](uint8_t first_byte) {
  19607. std::string frame;
  19608. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  19609. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  19610. frame += "Hello";
  19611. return frame;
  19612. };
  19613. // RSV1 set (0x40)
  19614. {
  19615. detail::BufferStream strm;
  19616. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  19617. ws::Opcode opcode;
  19618. std::string payload;
  19619. bool fin;
  19620. EXPECT_EQ(
  19621. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19622. ws::impl::FrameRead::Fail);
  19623. }
  19624. // RSV2 set (0x20)
  19625. {
  19626. detail::BufferStream strm;
  19627. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  19628. ws::Opcode opcode;
  19629. std::string payload;
  19630. bool fin;
  19631. EXPECT_EQ(
  19632. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19633. ws::impl::FrameRead::Fail);
  19634. }
  19635. // RSV3 set (0x10)
  19636. {
  19637. detail::BufferStream strm;
  19638. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  19639. ws::Opcode opcode;
  19640. std::string payload;
  19641. bool fin;
  19642. EXPECT_EQ(
  19643. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19644. ws::impl::FrameRead::Fail);
  19645. }
  19646. // No RSV bits set - should succeed
  19647. {
  19648. detail::BufferStream strm;
  19649. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  19650. ws::Opcode opcode;
  19651. std::string payload;
  19652. bool fin;
  19653. EXPECT_EQ(
  19654. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19655. ws::impl::FrameRead::Ok);
  19656. EXPECT_EQ(ws::Opcode::Text, opcode);
  19657. EXPECT_EQ("Hello", payload);
  19658. EXPECT_TRUE(fin);
  19659. }
  19660. }
  19661. TEST(WebSocketTest, ControlFrameValidation) {
  19662. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  19663. // payload length <= 125.
  19664. // Ping with FIN=0 - must be rejected
  19665. {
  19666. detail::BufferStream strm;
  19667. std::string frame;
  19668. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  19669. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19670. strm.write(frame.data(), frame.size());
  19671. ws::Opcode opcode;
  19672. std::string payload;
  19673. bool fin;
  19674. EXPECT_EQ(
  19675. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19676. ws::impl::FrameRead::Fail);
  19677. }
  19678. // Close with FIN=0 - must be rejected
  19679. {
  19680. detail::BufferStream strm;
  19681. std::string frame;
  19682. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  19683. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19684. strm.write(frame.data(), frame.size());
  19685. ws::Opcode opcode;
  19686. std::string payload;
  19687. bool fin;
  19688. EXPECT_EQ(
  19689. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19690. ws::impl::FrameRead::Fail);
  19691. }
  19692. // Ping with payload_len=126 (extended length) - must be rejected
  19693. {
  19694. detail::BufferStream strm;
  19695. std::string frame;
  19696. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19697. frame += static_cast<char>(126); // payload_len=126 (>125)
  19698. frame += static_cast<char>(0x00); // extended length high byte
  19699. frame += static_cast<char>(126); // extended length low byte
  19700. frame += std::string(126, 'x');
  19701. strm.write(frame.data(), frame.size());
  19702. ws::Opcode opcode;
  19703. std::string payload;
  19704. bool fin;
  19705. EXPECT_EQ(
  19706. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19707. ws::impl::FrameRead::Fail);
  19708. }
  19709. // Ping with FIN=1 and payload_len=125 - should succeed
  19710. {
  19711. detail::BufferStream strm;
  19712. std::string frame;
  19713. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19714. frame += static_cast<char>(125); // payload_len=125
  19715. frame += std::string(125, 'x');
  19716. strm.write(frame.data(), frame.size());
  19717. ws::Opcode opcode;
  19718. std::string payload;
  19719. bool fin;
  19720. EXPECT_EQ(
  19721. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19722. ws::impl::FrameRead::Ok);
  19723. EXPECT_EQ(ws::Opcode::Ping, opcode);
  19724. EXPECT_EQ(125u, payload.size());
  19725. EXPECT_TRUE(fin);
  19726. }
  19727. }
  19728. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  19729. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  19730. // length MUST be 0.
  19731. // MSB set - must be rejected
  19732. {
  19733. detail::BufferStream strm;
  19734. std::string frame;
  19735. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19736. frame += static_cast<char>(127); // 64-bit extended length
  19737. frame += static_cast<char>(0x80); // MSB set (invalid)
  19738. frame += std::string(7, '\0'); // remaining 7 bytes of length
  19739. strm.write(frame.data(), frame.size());
  19740. ws::Opcode opcode;
  19741. std::string payload;
  19742. bool fin;
  19743. EXPECT_EQ(
  19744. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19745. ws::impl::FrameRead::Fail);
  19746. }
  19747. // MSB clear - should pass length parsing (will be rejected by max_len,
  19748. // but that's a different check; use a small length to verify)
  19749. {
  19750. detail::BufferStream strm;
  19751. std::string frame;
  19752. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19753. frame += static_cast<char>(127); // 64-bit extended length
  19754. frame += std::string(7, '\0'); // high bytes = 0
  19755. frame += static_cast<char>(0x03); // length = 3
  19756. frame += "abc";
  19757. strm.write(frame.data(), frame.size());
  19758. ws::Opcode opcode;
  19759. std::string payload;
  19760. bool fin;
  19761. EXPECT_EQ(
  19762. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19763. ws::impl::FrameRead::Ok);
  19764. EXPECT_EQ(ws::Opcode::Text, opcode);
  19765. EXPECT_EQ("abc", payload);
  19766. }
  19767. }
  19768. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  19769. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  19770. // Valid UTF-8
  19771. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  19772. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  19773. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  19774. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  19775. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  19776. // Invalid UTF-8
  19777. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  19778. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  19779. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  19780. EXPECT_FALSE(
  19781. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  19782. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  19783. }
  19784. TEST(WebSocketTest, ConnectAndDisconnect) {
  19785. Server svr;
  19786. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19787. std::string msg;
  19788. while (ws.read(msg)) {}
  19789. });
  19790. auto port = svr.bind_to_any_port(HOST);
  19791. std::thread t([&]() { svr.listen_after_bind(); });
  19792. svr.wait_until_ready();
  19793. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19794. auto res = client.connect();
  19795. ASSERT_TRUE(res);
  19796. EXPECT_EQ(Error::Success, res.error());
  19797. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  19798. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  19799. EXPECT_TRUE(client.is_open());
  19800. client.close();
  19801. EXPECT_FALSE(client.is_open());
  19802. svr.stop();
  19803. t.join();
  19804. }
  19805. TEST(WebSocketTest, ValidURL) {
  19806. ws::WebSocketClient ws1("ws://localhost:8080/path");
  19807. EXPECT_TRUE(ws1.is_valid());
  19808. ws::WebSocketClient ws2("ws://example.com/path");
  19809. EXPECT_TRUE(ws2.is_valid());
  19810. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  19811. EXPECT_TRUE(ws3.is_valid());
  19812. #ifdef CPPHTTPLIB_SSL_ENABLED
  19813. ws::WebSocketClient wss1("wss://example.com/path");
  19814. EXPECT_TRUE(wss1.is_valid());
  19815. ws::WebSocketClient wss2("wss://example.com:443/path");
  19816. EXPECT_TRUE(wss2.is_valid());
  19817. #endif
  19818. }
  19819. TEST(WebSocketTest, InvalidURL) {
  19820. // No scheme
  19821. ws::WebSocketClient ws1("localhost:8080/path");
  19822. EXPECT_FALSE(ws1.is_valid());
  19823. // No path
  19824. ws::WebSocketClient ws2("ws://localhost:8080");
  19825. EXPECT_FALSE(ws2.is_valid());
  19826. // Empty string
  19827. ws::WebSocketClient ws3("");
  19828. EXPECT_FALSE(ws3.is_valid());
  19829. // Missing host
  19830. ws::WebSocketClient ws4("ws://:8080/path");
  19831. EXPECT_FALSE(ws4.is_valid());
  19832. // Port number overflow — should not crash
  19833. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  19834. EXPECT_FALSE(ws5.is_valid());
  19835. // Port out of range
  19836. ws::WebSocketClient ws6("ws://localhost:99999/path");
  19837. EXPECT_FALSE(ws6.is_valid());
  19838. }
  19839. TEST(WebSocketTest, UnsupportedScheme) {
  19840. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  19841. ws::WebSocketClient ws1("http://localhost:8080/path");
  19842. EXPECT_FALSE(ws1.is_valid());
  19843. ws::WebSocketClient ws2("https://localhost:8080/path");
  19844. EXPECT_FALSE(ws2.is_valid());
  19845. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  19846. EXPECT_FALSE(ws3.is_valid());
  19847. #else
  19848. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  19849. std::invalid_argument);
  19850. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  19851. std::invalid_argument);
  19852. #endif
  19853. }
  19854. TEST(WebSocketTest, ConnectWhenInvalid) {
  19855. ws::WebSocketClient ws("not a valid url");
  19856. EXPECT_FALSE(ws.is_valid());
  19857. auto res = ws.connect();
  19858. EXPECT_FALSE(res);
  19859. EXPECT_EQ(Error::Connection, res.error());
  19860. EXPECT_EQ(-1, res.status());
  19861. }
  19862. TEST(WebSocketTest, ConnectRefusedReportsError) {
  19863. // Grab a port that is free, then close it again so nothing listens there
  19864. Server svr;
  19865. auto port = svr.bind_to_any_port(HOST);
  19866. svr.stop();
  19867. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19868. auto res = client.connect();
  19869. ASSERT_FALSE(res);
  19870. EXPECT_EQ(Error::Connection, res.error());
  19871. EXPECT_EQ(-1, res.status());
  19872. }
  19873. TEST(WebSocketTest, DefaultPort) {
  19874. ws::WebSocketClient ws1("ws://example.com/path");
  19875. EXPECT_TRUE(ws1.is_valid());
  19876. // ws:// defaults to port 80 (verified by successful parse)
  19877. #ifdef CPPHTTPLIB_SSL_ENABLED
  19878. ws::WebSocketClient ws2("wss://example.com/path");
  19879. EXPECT_TRUE(ws2.is_valid());
  19880. // wss:// defaults to port 443 (verified by successful parse)
  19881. #endif
  19882. }
  19883. TEST(WebSocketTest, IPv6LiteralAddress) {
  19884. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  19885. EXPECT_TRUE(ws1.is_valid());
  19886. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  19887. EXPECT_TRUE(ws2.is_valid());
  19888. }
  19889. TEST(WebSocketTest, ComplexPath) {
  19890. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  19891. EXPECT_TRUE(ws1.is_valid());
  19892. ws::WebSocketClient ws2("ws://localhost:8080/");
  19893. EXPECT_TRUE(ws2.is_valid());
  19894. }
  19895. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  19896. Server svr;
  19897. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19898. std::string msg;
  19899. while (ws.read(msg)) {}
  19900. });
  19901. auto port = svr.bind_to_any_port(HOST);
  19902. std::thread t([&]() { svr.listen_after_bind(); });
  19903. svr.wait_until_ready();
  19904. auto another_host = "example.com";
  19905. auto wrong_ip = "192.0.2.1";
  19906. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19907. client.set_hostname_addr_map({{another_host, wrong_ip}});
  19908. ASSERT_TRUE(client.connect());
  19909. EXPECT_TRUE(client.is_open());
  19910. client.close();
  19911. svr.stop();
  19912. t.join();
  19913. }
  19914. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  19915. Server svr;
  19916. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19917. std::string msg;
  19918. while (ws.read(msg)) {}
  19919. });
  19920. auto port = svr.bind_to_any_port(HOST);
  19921. std::thread t([&]() { svr.listen_after_bind(); });
  19922. svr.wait_until_ready();
  19923. auto wrong_ip = "192.0.2.1";
  19924. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19925. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  19926. client.set_connection_timeout(1);
  19927. client.set_read_timeout(1);
  19928. client.set_write_timeout(1);
  19929. EXPECT_FALSE(client.connect());
  19930. EXPECT_FALSE(client.is_open());
  19931. svr.stop();
  19932. t.join();
  19933. }
  19934. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  19935. // A mapped value that is not an IP literal must be resolved. HOST resolves
  19936. // from the hosts file, so this test needs no external DNS. "target.invalid"
  19937. // (RFC 6761) is only a map key and the Host header value.
  19938. auto host = "target.invalid";
  19939. Server svr;
  19940. std::string received_host;
  19941. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19942. received_host = req.get_header_value("Host");
  19943. std::string msg;
  19944. while (ws.read(msg)) {}
  19945. });
  19946. auto port = svr.bind_to_any_port(HOST);
  19947. std::thread t([&]() { svr.listen_after_bind(); });
  19948. // ASSERT_* below returns from the test body, which would leave t joinable
  19949. // and make ~thread call std::terminate.
  19950. auto se = detail::scope_exit([&] {
  19951. svr.stop();
  19952. if (t.joinable()) { t.join(); }
  19953. });
  19954. svr.wait_until_ready();
  19955. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  19956. std::to_string(port) + "/ws");
  19957. client.set_hostname_addr_map({{host, HOST}});
  19958. ASSERT_TRUE(client.connect());
  19959. EXPECT_TRUE(client.is_open());
  19960. client.close();
  19961. svr.stop();
  19962. t.join();
  19963. // The mapping only redirects the connection; the identity stays host_.
  19964. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  19965. }
  19966. class WebSocketIntegrationTest : public ::testing::Test {
  19967. protected:
  19968. void SetUp() override {
  19969. server_ = httplib::detail::make_unique<Server>();
  19970. setup_server();
  19971. start_server();
  19972. }
  19973. void TearDown() override {
  19974. server_->stop();
  19975. if (server_thread_.joinable()) { server_thread_.join(); }
  19976. }
  19977. void setup_server() {
  19978. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19979. std::string msg;
  19980. ws::ReadResult ret;
  19981. while ((ret = ws.read(msg))) {
  19982. if (ret == ws::Binary) {
  19983. ws.send(msg.data(), msg.size());
  19984. } else {
  19985. ws.send(msg);
  19986. }
  19987. }
  19988. });
  19989. server_->WebSocket("/ws-echo-string",
  19990. [](const Request &, ws::WebSocket &ws) {
  19991. std::string msg;
  19992. while (ws.read(msg)) {
  19993. ws.send("echo: " + msg);
  19994. }
  19995. });
  19996. server_->WebSocket(
  19997. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  19998. // Echo back request metadata
  19999. ws.send("path:" + req.path);
  20000. ws.send("header:" + req.get_header_value("X-Test-Header"));
  20001. std::string msg;
  20002. while (ws.read(msg)) {}
  20003. });
  20004. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  20005. std::string msg;
  20006. ws.read(msg); // wait for a message
  20007. ws.close();
  20008. });
  20009. server_->WebSocket("/ws-close-status",
  20010. [](const Request &, ws::WebSocket &ws) {
  20011. std::string msg;
  20012. ws.read(msg); // wait for a message
  20013. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  20014. });
  20015. server_->WebSocket(
  20016. "/ws-subprotocol",
  20017. [](const Request &, ws::WebSocket &ws) {
  20018. std::string msg;
  20019. while (ws.read(msg)) {
  20020. ws.send(msg);
  20021. }
  20022. },
  20023. [](const std::vector<std::string> &protocols) -> std::string {
  20024. for (const auto &p : protocols) {
  20025. if (p == "graphql-ws") { return p; }
  20026. }
  20027. return "";
  20028. });
  20029. }
  20030. void start_server() {
  20031. port_ = server_->bind_to_any_port(HOST);
  20032. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20033. server_->wait_until_ready();
  20034. }
  20035. std::unique_ptr<Server> server_;
  20036. std::thread server_thread_;
  20037. int port_ = 0;
  20038. };
  20039. TEST_F(WebSocketIntegrationTest, TextEcho) {
  20040. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20041. "/ws-echo");
  20042. ASSERT_TRUE(client.connect());
  20043. ASSERT_TRUE(client.is_open());
  20044. ASSERT_TRUE(client.send("Hello WebSocket"));
  20045. std::string msg;
  20046. EXPECT_EQ(ws::Text, client.read(msg));
  20047. EXPECT_EQ("Hello WebSocket", msg);
  20048. client.close();
  20049. }
  20050. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  20051. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20052. "/ws-echo");
  20053. ASSERT_TRUE(client.connect());
  20054. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  20055. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  20056. std::string msg;
  20057. EXPECT_EQ(ws::Binary, client.read(msg));
  20058. EXPECT_EQ(binary_data, msg);
  20059. client.close();
  20060. }
  20061. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  20062. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20063. "/ws-echo");
  20064. ASSERT_TRUE(client.connect());
  20065. for (int i = 0; i < 10; i++) {
  20066. auto text = "message " + std::to_string(i);
  20067. ASSERT_TRUE(client.send(text));
  20068. std::string msg;
  20069. ASSERT_TRUE(client.read(msg));
  20070. EXPECT_EQ(text, msg);
  20071. }
  20072. client.close();
  20073. }
  20074. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  20075. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20076. "/ws-close");
  20077. ASSERT_TRUE(client.connect());
  20078. // Send a message to trigger the server to close
  20079. ASSERT_TRUE(client.send("trigger close"));
  20080. // The server will close, so read should return false
  20081. std::string msg;
  20082. EXPECT_FALSE(client.read(msg));
  20083. EXPECT_FALSE(client.is_open());
  20084. }
  20085. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  20086. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20087. "/ws-echo");
  20088. ASSERT_TRUE(client.connect());
  20089. // 128KB message
  20090. std::string large_data(128 * 1024, 'X');
  20091. ASSERT_TRUE(client.send(large_data));
  20092. std::string msg;
  20093. ASSERT_TRUE(client.read(msg));
  20094. EXPECT_EQ(large_data, msg);
  20095. client.close();
  20096. }
  20097. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  20098. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20099. "/ws-echo");
  20100. ASSERT_TRUE(client.connect());
  20101. const int num_threads = 4;
  20102. std::vector<std::thread> threads;
  20103. std::atomic<int> send_count{0};
  20104. for (int t = 0; t < num_threads; t++) {
  20105. threads.emplace_back([&client, &send_count, t]() {
  20106. for (int i = 0; i < 5; i++) {
  20107. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  20108. if (client.send(text)) { send_count++; }
  20109. }
  20110. });
  20111. }
  20112. for (auto &th : threads) {
  20113. th.join();
  20114. }
  20115. int received = 0;
  20116. std::string msg;
  20117. while (received < send_count.load()) {
  20118. if (!client.read(msg)) { break; }
  20119. received++;
  20120. }
  20121. EXPECT_EQ(send_count.load(), received);
  20122. client.close();
  20123. }
  20124. TEST_F(WebSocketIntegrationTest, ReadString) {
  20125. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20126. "/ws-echo-string");
  20127. ASSERT_TRUE(client.connect());
  20128. ASSERT_TRUE(client.send("hello"));
  20129. std::string msg;
  20130. ASSERT_TRUE(client.read(msg));
  20131. EXPECT_EQ("echo: hello", msg);
  20132. ASSERT_TRUE(client.send("world"));
  20133. ASSERT_TRUE(client.read(msg));
  20134. EXPECT_EQ("echo: world", msg);
  20135. client.close();
  20136. }
  20137. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  20138. Headers headers = {{"X-Test-Header", "test-value"}};
  20139. ws::WebSocketClient client(
  20140. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  20141. ASSERT_TRUE(client.connect());
  20142. std::string msg;
  20143. ASSERT_TRUE(client.read(msg));
  20144. EXPECT_EQ("path:/ws-request-info", msg);
  20145. ASSERT_TRUE(client.read(msg));
  20146. EXPECT_EQ("header:test-value", msg);
  20147. client.close();
  20148. }
  20149. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  20150. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20151. "/ws-echo");
  20152. client.set_read_timeout(1, 0); // 1 second
  20153. ASSERT_TRUE(client.connect());
  20154. // Don't send anything — server echo handler waits for a message, so read()
  20155. // should time out. The connection survives it: nothing was consumed.
  20156. std::string msg;
  20157. EXPECT_EQ(client.read(msg), ws::Timeout);
  20158. EXPECT_TRUE(client.is_open());
  20159. // And it is still usable afterwards.
  20160. EXPECT_TRUE(client.send("after timeout"));
  20161. EXPECT_EQ(client.read(msg), ws::Text);
  20162. EXPECT_EQ(msg, "after timeout");
  20163. }
  20164. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  20165. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20166. "/ws-echo");
  20167. client.set_read_timeout(1, 0);
  20168. ASSERT_TRUE(client.connect());
  20169. ASSERT_TRUE(client.send("first"));
  20170. std::string msg;
  20171. ASSERT_EQ(client.read(msg), ws::Text);
  20172. ASSERT_EQ(msg, "first");
  20173. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  20174. // not be used with a read timeout: it would reprocess the previous message.
  20175. EXPECT_EQ(client.read(msg), ws::Timeout);
  20176. EXPECT_EQ(msg, "first");
  20177. }
  20178. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  20179. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20180. "/ws-echo");
  20181. ASSERT_TRUE(client.connect());
  20182. // Setting it once the connection is open reaches the live stream, not just
  20183. // the seed for the next connect().
  20184. client.set_read_timeout(1, 0);
  20185. std::string msg;
  20186. EXPECT_EQ(client.read(msg), ws::Timeout);
  20187. EXPECT_TRUE(client.is_open());
  20188. }
  20189. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  20190. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20191. "/ws-echo");
  20192. client.set_read_timeout(5, 0);
  20193. ASSERT_TRUE(client.connect());
  20194. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20195. // The server should reject it and close the connection.
  20196. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  20197. client.send(oversized);
  20198. // The server's read() should have failed due to payload limit,
  20199. // so our read() should return false (connection closed).
  20200. std::string msg;
  20201. EXPECT_FALSE(client.read(msg));
  20202. }
  20203. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  20204. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20205. "/ws-echo");
  20206. client.set_read_timeout(10, 0);
  20207. ASSERT_TRUE(client.connect());
  20208. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20209. // This should succeed.
  20210. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  20211. ASSERT_TRUE(client.send(at_limit));
  20212. std::string msg;
  20213. ASSERT_TRUE(client.read(msg));
  20214. EXPECT_EQ(at_limit.size(), msg.size());
  20215. client.close();
  20216. }
  20217. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  20218. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20219. "/nonexistent");
  20220. auto res = client.connect();
  20221. EXPECT_FALSE(res);
  20222. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20223. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  20224. EXPECT_FALSE(client.is_open());
  20225. }
  20226. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  20227. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20228. "/ws-echo");
  20229. ASSERT_TRUE(client.connect());
  20230. ASSERT_TRUE(client.send(""));
  20231. std::string msg;
  20232. EXPECT_EQ(ws::Text, client.read(msg));
  20233. EXPECT_EQ("", msg);
  20234. client.close();
  20235. }
  20236. TEST_F(WebSocketIntegrationTest, Reconnect) {
  20237. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20238. "/ws-echo");
  20239. // First connection
  20240. ASSERT_TRUE(client.connect());
  20241. ASSERT_TRUE(client.send("first"));
  20242. std::string msg;
  20243. ASSERT_TRUE(client.read(msg));
  20244. EXPECT_EQ("first", msg);
  20245. client.close();
  20246. EXPECT_FALSE(client.is_open());
  20247. // Reconnect using the same client object
  20248. ASSERT_TRUE(client.connect());
  20249. ASSERT_TRUE(client.is_open());
  20250. ASSERT_TRUE(client.send("second"));
  20251. ASSERT_TRUE(client.read(msg));
  20252. EXPECT_EQ("second", msg);
  20253. client.close();
  20254. }
  20255. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  20256. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20257. "/ws-close-status");
  20258. ASSERT_TRUE(client.connect());
  20259. // Trigger the server to close with GoingAway status
  20260. ASSERT_TRUE(client.send("trigger"));
  20261. // read() should return false after receiving the close frame
  20262. std::string msg;
  20263. EXPECT_FALSE(client.read(msg));
  20264. EXPECT_FALSE(client.is_open());
  20265. }
  20266. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  20267. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20268. "/ws-echo");
  20269. ASSERT_TRUE(client.connect());
  20270. client.close(ws::CloseStatus::GoingAway, "client leaving");
  20271. EXPECT_FALSE(client.is_open());
  20272. }
  20273. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  20274. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  20275. ws::WebSocketClient client(
  20276. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20277. ASSERT_TRUE(client.connect());
  20278. // Server should have selected graphql-ws
  20279. EXPECT_EQ("graphql-ws", client.subprotocol());
  20280. client.close();
  20281. }
  20282. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  20283. Headers headers;
  20284. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  20285. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  20286. ws::WebSocketClient client(
  20287. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20288. ASSERT_TRUE(client.connect());
  20289. // The offer on the second field line counts too, so graphql-ws is selected
  20290. EXPECT_EQ("graphql-ws", client.subprotocol());
  20291. client.close();
  20292. }
  20293. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  20294. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  20295. ws::WebSocketClient client(
  20296. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20297. ASSERT_TRUE(client.connect());
  20298. // Server should not have selected any subprotocol
  20299. EXPECT_TRUE(client.subprotocol().empty());
  20300. client.close();
  20301. }
  20302. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  20303. // Connect without requesting any subprotocol
  20304. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20305. "/ws-subprotocol");
  20306. ASSERT_TRUE(client.connect());
  20307. EXPECT_TRUE(client.subprotocol().empty());
  20308. client.close();
  20309. }
  20310. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  20311. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20312. "/ws-echo");
  20313. client.set_tcp_nodelay(true);
  20314. client.set_connection_timeout(3, 0);
  20315. bool socket_options_called = false;
  20316. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  20317. ASSERT_TRUE(client.connect());
  20318. ASSERT_TRUE(client.is_open());
  20319. EXPECT_TRUE(socket_options_called);
  20320. ASSERT_TRUE(client.send("hello"));
  20321. std::string msg;
  20322. auto result = client.read(msg);
  20323. EXPECT_EQ(result, ws::ReadResult::Text);
  20324. EXPECT_EQ(msg, "hello");
  20325. client.close();
  20326. }
  20327. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  20328. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20329. "/ws-echo");
  20330. client.set_connection_timeout(std::chrono::seconds(3));
  20331. client.set_write_timeout(std::chrono::seconds(3));
  20332. // A sub-second remainder exercises the seconds/microseconds split.
  20333. client.set_read_timeout(std::chrono::milliseconds(1500));
  20334. ASSERT_TRUE(client.connect());
  20335. auto start = std::chrono::steady_clock::now();
  20336. std::string msg;
  20337. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  20338. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  20339. std::chrono::steady_clock::now() - start)
  20340. .count();
  20341. // Above 1s so that dropping the microseconds half of the split fails here.
  20342. // Ignoring the setter altogether would not reach this line at all: a client
  20343. // waits forever by default.
  20344. EXPECT_GE(elapsed, 1400);
  20345. EXPECT_LT(elapsed, 30000);
  20346. }
  20347. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  20348. Server svr;
  20349. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  20350. if (!req.has_header("Authorization")) {
  20351. res.status = StatusCode::Unauthorized_401;
  20352. res.set_content("Unauthorized", "text/plain");
  20353. return Server::HandlerResponse::Handled;
  20354. }
  20355. return Server::HandlerResponse::Unhandled;
  20356. });
  20357. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20358. std::string msg;
  20359. while (ws.read(msg)) {
  20360. ws.send(msg);
  20361. }
  20362. });
  20363. auto port = svr.bind_to_any_port("localhost");
  20364. std::thread t([&]() { svr.listen_after_bind(); });
  20365. svr.wait_until_ready();
  20366. // Without Authorization header - should be rejected before upgrade
  20367. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  20368. EXPECT_FALSE(client1.connect());
  20369. // The rejection is framed like any other HTTP response
  20370. {
  20371. Client cli("localhost", port);
  20372. Headers headers = {{"Upgrade", "websocket"},
  20373. {"Connection", "Upgrade"},
  20374. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20375. {"Sec-WebSocket-Version", "13"}};
  20376. auto res = cli.Get("/ws", headers);
  20377. ASSERT_TRUE(res);
  20378. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20379. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20380. EXPECT_EQ("Unauthorized", res->body);
  20381. }
  20382. // With Authorization header - should succeed
  20383. Headers headers = {{"Authorization", "Bearer token123"}};
  20384. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  20385. headers);
  20386. ASSERT_TRUE(client2.connect());
  20387. ASSERT_TRUE(client2.send("hello"));
  20388. std::string msg;
  20389. ASSERT_TRUE(client2.read(msg));
  20390. EXPECT_EQ("hello", msg);
  20391. client2.close();
  20392. svr.stop();
  20393. t.join();
  20394. }
  20395. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  20396. Server svr;
  20397. std::atomic<int> pre_request_calls{0};
  20398. std::atomic<bool> route_matched{false};
  20399. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  20400. pre_request_calls++;
  20401. if (req.matched_route == "/ws/:id") { route_matched = true; }
  20402. if (req.get_header_value("Authorization") != "Bearer token123") {
  20403. res.status = StatusCode::Unauthorized_401;
  20404. res.set_content("Unauthorized", "text/plain");
  20405. return Server::HandlerResponse::Handled;
  20406. }
  20407. return Server::HandlerResponse::Unhandled;
  20408. });
  20409. std::atomic<bool> handler_called{false};
  20410. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  20411. handler_called = true;
  20412. ws.send(req.matched_route + " " + req.path_params.at("id"));
  20413. });
  20414. auto port = svr.bind_to_any_port("localhost");
  20415. std::thread t([&]() { svr.listen_after_bind(); });
  20416. svr.wait_until_ready();
  20417. // Without Authorization header - should be rejected before upgrade
  20418. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  20419. "/ws/1");
  20420. EXPECT_FALSE(client1.connect());
  20421. EXPECT_FALSE(handler_called);
  20422. EXPECT_EQ(1, pre_request_calls);
  20423. EXPECT_TRUE(route_matched);
  20424. // The rejection is an ordinary HTTP response, not a protocol switch
  20425. {
  20426. Client cli("localhost", port);
  20427. Headers headers = {{"Upgrade", "websocket"},
  20428. {"Connection", "Upgrade"},
  20429. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20430. {"Sec-WebSocket-Version", "13"}};
  20431. auto res = cli.Get("/ws/1", headers);
  20432. ASSERT_TRUE(res);
  20433. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20434. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20435. EXPECT_EQ("Unauthorized", res->body);
  20436. }
  20437. EXPECT_FALSE(handler_called);
  20438. // With Authorization header - should succeed
  20439. Headers headers = {{"Authorization", "Bearer token123"}};
  20440. ws::WebSocketClient client2(
  20441. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  20442. ASSERT_TRUE(client2.connect());
  20443. std::string msg;
  20444. ASSERT_TRUE(client2.read(msg));
  20445. EXPECT_EQ("/ws/:id 2", msg);
  20446. EXPECT_TRUE(handler_called);
  20447. client2.close();
  20448. svr.stop();
  20449. t.join();
  20450. }
  20451. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  20452. Server svr;
  20453. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20454. // A read timeout is how a handler gets control back. Without it, a handler
  20455. // parked in read() can never write on the connection it is reading.
  20456. ws.set_read_timeout(std::chrono::milliseconds(100));
  20457. std::string msg;
  20458. while (ws.is_open()) {
  20459. auto r = ws.read(msg);
  20460. if (r == httplib::ws::Timeout) {
  20461. ws.send("tick");
  20462. continue;
  20463. }
  20464. if (r == httplib::ws::Fail) { break; }
  20465. ws.send(msg);
  20466. }
  20467. });
  20468. auto port = svr.bind_to_any_port("localhost");
  20469. std::thread t([&]() { svr.listen_after_bind(); });
  20470. svr.wait_until_ready();
  20471. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20472. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  20473. ASSERT_TRUE(client.connect());
  20474. // The client sends nothing, so anything it receives came out of the
  20475. // handler's timeout path.
  20476. std::string msg;
  20477. ASSERT_EQ(client.read(msg), ws::Text);
  20478. EXPECT_EQ("tick", msg);
  20479. client.close();
  20480. svr.stop();
  20481. t.join();
  20482. }
  20483. // Stream::read may return fewer bytes than asked for. This is that contract at
  20484. // its worst -- one byte per call -- which is what a frame header straddling a
  20485. // read buffer's boundary looks like to the frame parser.
  20486. class WsByteAtATimeStream : public Stream {
  20487. public:
  20488. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  20489. bool is_readable() const override { return true; }
  20490. bool wait_readable() const override { return true; }
  20491. bool wait_writable() const override { return true; }
  20492. ssize_t read(char *ptr, size_t size) override {
  20493. if (size == 0 || pos_ >= data_.size()) { return 0; }
  20494. *ptr = data_[pos_++];
  20495. return 1;
  20496. }
  20497. ssize_t write(const char *, size_t size) override {
  20498. return static_cast<ssize_t>(size);
  20499. }
  20500. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20501. ip = "127.0.0.1";
  20502. port = 0;
  20503. }
  20504. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20505. ip = "127.0.0.1";
  20506. port = 0;
  20507. }
  20508. socket_t socket() const override { return INVALID_SOCKET; }
  20509. time_t duration() const override { return 0; }
  20510. private:
  20511. std::string data_;
  20512. size_t pos_ = 0;
  20513. };
  20514. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  20515. // A 200-byte payload uses the 16-bit extended length, so the header, the
  20516. // length and the mask key are all multi-byte fields here. Each used to be
  20517. // read with a single read() call, which fails as soon as one is split.
  20518. std::string body(200, 'x');
  20519. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  20520. std::string frame;
  20521. frame += static_cast<char>(0x81); // FIN + Text
  20522. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  20523. frame += static_cast<char>(body.size() >> 8);
  20524. frame += static_cast<char>(body.size() & 0xff);
  20525. for (size_t i = 0; i < 4; i++) {
  20526. frame += static_cast<char>(mask[i]);
  20527. }
  20528. for (size_t i = 0; i < body.size(); i++) {
  20529. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  20530. }
  20531. WsByteAtATimeStream strm(frame);
  20532. ws::Opcode opcode;
  20533. std::string payload;
  20534. bool fin = false;
  20535. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  20536. /*expect_masked=*/true, 1024),
  20537. ws::impl::FrameRead::Ok);
  20538. EXPECT_TRUE(fin);
  20539. EXPECT_EQ(opcode, ws::Opcode::Text);
  20540. EXPECT_EQ(payload, body);
  20541. }
  20542. TEST(WebSocketTest, QueryStringInHandshake) {
  20543. Server svr;
  20544. std::mutex mtx;
  20545. std::string received_target;
  20546. std::string received_token;
  20547. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20548. {
  20549. std::lock_guard<std::mutex> lock(mtx);
  20550. received_target = req.target;
  20551. if (req.has_param("token")) {
  20552. received_token = req.get_param_value("token");
  20553. }
  20554. }
  20555. std::string msg;
  20556. while (ws.read(msg)) {
  20557. ws.send(msg);
  20558. }
  20559. });
  20560. auto port = svr.bind_to_any_port("localhost");
  20561. std::thread t([&]() { svr.listen_after_bind(); });
  20562. svr.wait_until_ready();
  20563. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  20564. "/ws?token=ABC&session=123");
  20565. ASSERT_TRUE(client.connect());
  20566. // Round-trip ensures the handler has run and captured the request.
  20567. ASSERT_TRUE(client.send("hello"));
  20568. std::string msg;
  20569. ASSERT_TRUE(client.read(msg));
  20570. EXPECT_EQ("hello", msg);
  20571. client.close();
  20572. {
  20573. std::lock_guard<std::mutex> lock(mtx);
  20574. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  20575. EXPECT_EQ("ABC", received_token);
  20576. }
  20577. svr.stop();
  20578. t.join();
  20579. }
  20580. // Run a handshake against a throwaway server and hand the request the server
  20581. // received back to the caller, so tests can assert on the headers the client
  20582. // actually put on the wire.
  20583. static void capture_websocket_handshake_request(
  20584. const Headers &client_headers,
  20585. std::function<void(const Request &, int port)> verify) {
  20586. Server svr;
  20587. std::mutex mtx;
  20588. Request received;
  20589. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20590. {
  20591. std::lock_guard<std::mutex> lock(mtx);
  20592. received = req;
  20593. }
  20594. std::string msg;
  20595. while (ws.read(msg)) {
  20596. ws.send(msg);
  20597. }
  20598. });
  20599. auto port = svr.bind_to_any_port("localhost");
  20600. std::thread t([&]() { svr.listen_after_bind(); });
  20601. auto se = detail::scope_exit([&] {
  20602. svr.stop();
  20603. t.join();
  20604. });
  20605. svr.wait_until_ready();
  20606. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  20607. client_headers);
  20608. ASSERT_TRUE(client.connect());
  20609. ASSERT_TRUE(client.send("hello"));
  20610. std::string msg;
  20611. ASSERT_TRUE(client.read(msg));
  20612. client.close();
  20613. {
  20614. std::lock_guard<std::mutex> lock(mtx);
  20615. verify(received, port);
  20616. }
  20617. }
  20618. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  20619. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  20620. // Non-default port must be present in the Host header. Default ports
  20621. // (80/443) are omitted; that logic is covered by
  20622. // MakeHostAndPortStringTest.
  20623. EXPECT_EQ("localhost:" + std::to_string(port),
  20624. req.get_header_value("Host"));
  20625. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  20626. req.get_header_value("User-Agent"));
  20627. EXPECT_FALSE(req.has_header("Accept"));
  20628. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  20629. EXPECT_FALSE(req.has_header("Content-Length"));
  20630. });
  20631. }
  20632. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  20633. capture_websocket_handshake_request(
  20634. {{"Host", "example.com"},
  20635. {"User-Agent", "custom-agent"},
  20636. {"X-Custom", "value"}},
  20637. [](const Request &req, int) {
  20638. EXPECT_EQ("example.com", req.get_header_value("Host"));
  20639. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  20640. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  20641. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  20642. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  20643. });
  20644. }
  20645. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  20646. capture_websocket_handshake_request(
  20647. {{"Upgrade", "bogus"},
  20648. {"Connection", "close"},
  20649. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  20650. {"Sec-WebSocket-Version", "8"}},
  20651. [](const Request &req, int) {
  20652. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  20653. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  20654. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  20655. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  20656. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  20657. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  20658. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  20659. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  20660. req.get_header_value("Sec-WebSocket-Key"));
  20661. });
  20662. }
  20663. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  20664. // A header the client refuses to send must abort the handshake before any
  20665. // part of it reaches the wire; a lone request line would otherwise sit in
  20666. // the peer's buffer as a truncated request.
  20667. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20668. ASSERT_NE(INVALID_SOCKET, srv);
  20669. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  20670. sockaddr_in addr{};
  20671. addr.sin_family = AF_INET;
  20672. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  20673. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20674. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  20675. ASSERT_EQ(0, ::listen(srv, 1));
  20676. sockaddr_in bound{};
  20677. socklen_t bound_len = sizeof(bound);
  20678. ASSERT_EQ(
  20679. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  20680. auto port = ntohs(bound.sin_port);
  20681. ssize_t received = -1;
  20682. std::thread t([&] {
  20683. // Bound every blocking call so a regression fails the test with a bad
  20684. // value instead of hanging the suite.
  20685. fd_set rfds;
  20686. FD_ZERO(&rfds);
  20687. FD_SET(srv, &rfds);
  20688. timeval tv{5, 0};
  20689. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  20690. 0) {
  20691. return;
  20692. }
  20693. sockaddr_in cli_addr{};
  20694. socklen_t cli_len = sizeof(cli_addr);
  20695. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20696. if (cli == INVALID_SOCKET) { return; }
  20697. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  20698. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20699. char buf[4096];
  20700. received = ::recv(cli, buf, sizeof(buf), 0);
  20701. });
  20702. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  20703. // connect() has already shut the socket down by the time it returns false,
  20704. // so the peer sees EOF without waiting for the client to be destroyed.
  20705. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  20706. {{"X-Bad", "a\r\nInjected: 1"}});
  20707. EXPECT_FALSE(client.connect());
  20708. t.join();
  20709. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  20710. EXPECT_EQ(0, received);
  20711. }
  20712. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  20713. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  20714. // contains "upgrade" as a substring is a different token and must not
  20715. // start a WebSocket handshake.
  20716. auto make_request = [](const std::vector<std::string> &connection_values) {
  20717. Request req;
  20718. req.method = "GET";
  20719. req.headers.emplace("Upgrade", "websocket");
  20720. for (const auto &value : connection_values) {
  20721. req.headers.emplace("Connection", value);
  20722. }
  20723. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20724. req.headers.emplace("Sec-WebSocket-Version", "13");
  20725. return req;
  20726. };
  20727. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  20728. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  20729. EXPECT_TRUE(
  20730. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  20731. EXPECT_TRUE(
  20732. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  20733. EXPECT_TRUE(
  20734. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  20735. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  20736. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  20737. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  20738. EXPECT_FALSE(
  20739. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  20740. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  20741. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20742. }
  20743. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  20744. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  20745. // asks recipients to match each protocol-name case-insensitively, and RFC
  20746. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  20747. // client naming websocket alongside another protocol, or on a second field
  20748. // line, is offering websocket; a value that merely contains "websocket" as a
  20749. // substring is a different protocol name and is not.
  20750. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  20751. Request req;
  20752. req.method = "GET";
  20753. for (const auto &value : upgrade_values) {
  20754. req.headers.emplace("Upgrade", value);
  20755. }
  20756. req.headers.emplace("Connection", "Upgrade");
  20757. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20758. req.headers.emplace("Sec-WebSocket-Version", "13");
  20759. return req;
  20760. };
  20761. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  20762. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  20763. EXPECT_TRUE(
  20764. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  20765. EXPECT_TRUE(
  20766. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  20767. EXPECT_TRUE(
  20768. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  20769. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  20770. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  20771. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  20772. EXPECT_FALSE(
  20773. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  20774. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  20775. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20776. }
  20777. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  20778. Server svr;
  20779. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  20780. auto port = svr.bind_to_any_port("localhost");
  20781. std::thread t([&]() { svr.listen_after_bind(); });
  20782. auto se = detail::scope_exit([&] {
  20783. svr.stop();
  20784. t.join();
  20785. });
  20786. svr.wait_until_ready();
  20787. Headers headers = {{"Upgrade", "websocket"},
  20788. {"Connection", "notupgrade"},
  20789. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20790. {"Sec-WebSocket-Version", "13"}};
  20791. Client cli("localhost", port);
  20792. auto res = cli.Get("/ws", headers);
  20793. // The route exists only as a WebSocket route, so a request that fails the
  20794. // handshake check falls through to ordinary routing.
  20795. ASSERT_TRUE(res);
  20796. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  20797. }
  20798. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  20799. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  20800. // Connection value is the only thing left for the client to reject.
  20801. Server svr;
  20802. svr.Get("/ws", [](const Request &req, Response &res) {
  20803. res.status = StatusCode::SwitchingProtocol_101;
  20804. res.set_header("Upgrade", "websocket");
  20805. res.set_header("Connection", "notupgrade");
  20806. res.set_header("Sec-WebSocket-Accept",
  20807. detail::websocket_accept_key(
  20808. req.get_header_value("Sec-WebSocket-Key")));
  20809. });
  20810. auto port = svr.bind_to_any_port("localhost");
  20811. std::thread t([&]() { svr.listen_after_bind(); });
  20812. auto se = detail::scope_exit([&] {
  20813. svr.stop();
  20814. t.join();
  20815. });
  20816. svr.wait_until_ready();
  20817. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20818. auto res = client.connect();
  20819. EXPECT_FALSE(res);
  20820. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20821. EXPECT_FALSE(client.is_open());
  20822. }
  20823. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  20824. // The socket path doubles as the URL host, so it must not contain '/'.
  20825. const char *shard = getenv("GTEST_SHARD_INDEX");
  20826. const std::string sock_path =
  20827. shard ? std::string("httplib-ws-") + shard + ".sock"
  20828. : std::string("httplib-ws.sock");
  20829. std::remove(sock_path.c_str());
  20830. Server svr;
  20831. std::mutex mtx;
  20832. std::string received_host;
  20833. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20834. {
  20835. std::lock_guard<std::mutex> lock(mtx);
  20836. received_host = req.get_header_value("Host");
  20837. }
  20838. std::string msg;
  20839. while (ws.read(msg)) {
  20840. ws.send(msg);
  20841. }
  20842. });
  20843. svr.set_address_family(AF_UNIX);
  20844. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  20845. auto se = detail::scope_exit([&] {
  20846. svr.stop();
  20847. t.join();
  20848. std::remove(sock_path.c_str());
  20849. });
  20850. svr.wait_until_ready();
  20851. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  20852. client.set_address_family(AF_UNIX);
  20853. ASSERT_TRUE(client.connect());
  20854. ASSERT_TRUE(client.send("hello"));
  20855. std::string msg;
  20856. ASSERT_TRUE(client.read(msg));
  20857. client.close();
  20858. {
  20859. std::lock_guard<std::mutex> lock(mtx);
  20860. // There is no host:port for a Unix socket, so the same "localhost"
  20861. // placeholder the HTTP client uses is expected.
  20862. EXPECT_EQ("localhost", received_host);
  20863. }
  20864. }
  20865. // Two threads must never parse WebSocket frames from the same stream.
  20866. // close() used to read the peer's Close reply with its own frame read, so it
  20867. // raced a reader thread that was in the middle of a payload: the payload loop
  20868. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  20869. // so bytes taken by close() were replaced with bytes from further along the
  20870. // stream. The message kept its length and silently changed content.
  20871. //
  20872. // The raw peer below sends a frame header plus part of the payload, waits for
  20873. // the handler to call close(), and only then sends the rest. Whichever thread
  20874. // would win the race for those bytes, the message must arrive intact, because
  20875. // close() must not touch the stream while read() owns it.
  20876. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  20877. #ifndef _WIN32
  20878. signal(SIGPIPE, SIG_IGN);
  20879. #endif
  20880. const size_t payload_len = 120; // fits the 7-bit length field
  20881. const size_t prefix_len = 8;
  20882. const int attempts = 8;
  20883. std::string expected(payload_len, '\0');
  20884. for (size_t i = 0; i < payload_len; i++) {
  20885. expected[i] = static_cast<char>('a' + i % 26);
  20886. }
  20887. std::atomic<bool> peer_stalled{false};
  20888. std::atomic<bool> handler_done{false};
  20889. std::mutex received_mutex;
  20890. std::vector<std::string> received;
  20891. // Bound every wait, so a regression fails the test instead of hanging the
  20892. // suite.
  20893. auto wait_for = [](const std::atomic<bool> &flag) {
  20894. for (int i = 0; i < 500 && !flag; i++) {
  20895. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20896. }
  20897. };
  20898. Server svr;
  20899. svr.set_websocket_ping_interval(0);
  20900. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  20901. std::thread reader([&]() {
  20902. std::string msg;
  20903. while (ws.read(msg)) {
  20904. std::lock_guard<std::mutex> guard(received_mutex);
  20905. received.push_back(msg);
  20906. }
  20907. });
  20908. // Wait until the peer stalls mid-payload, so the reader thread is parked
  20909. // inside read_websocket_frame() when close() runs.
  20910. wait_for(peer_stalled);
  20911. ws.close();
  20912. reader.join();
  20913. handler_done = true;
  20914. });
  20915. auto port = svr.bind_to_any_port("127.0.0.1");
  20916. std::thread t([&]() { svr.listen_after_bind(); });
  20917. auto se = detail::scope_exit([&] {
  20918. svr.stop();
  20919. t.join();
  20920. });
  20921. svr.wait_until_ready();
  20922. auto send_bytes = [](socket_t s, const std::string &data) {
  20923. #ifdef _WIN32
  20924. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  20925. #else
  20926. auto n = ::send(s, data.data(), data.size(), 0);
  20927. #endif
  20928. return n == static_cast<decltype(n)>(data.size());
  20929. };
  20930. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  20931. // Every length used here fits the 7-bit length field.
  20932. auto masked_header = [](uint8_t first_byte, size_t len) {
  20933. std::string h;
  20934. h += static_cast<char>(first_byte);
  20935. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  20936. h.append(4, '\0'); // mask key
  20937. return h;
  20938. };
  20939. for (int attempt = 0; attempt < attempts; attempt++) {
  20940. peer_stalled = false;
  20941. handler_done = false;
  20942. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  20943. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  20944. auto se_sock = detail::scope_exit([&] {
  20945. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  20946. });
  20947. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20948. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20949. sockaddr_in addr{};
  20950. addr.sin_family = AF_INET;
  20951. addr.sin_port = htons(static_cast<uint16_t>(port));
  20952. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20953. ASSERT_EQ(
  20954. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  20955. << "attempt " << attempt;
  20956. ASSERT_TRUE(send_bytes(sock,
  20957. "GET /ws HTTP/1.1\r\n"
  20958. "Host: 127.0.0.1\r\n"
  20959. "Upgrade: websocket\r\n"
  20960. "Connection: Upgrade\r\n"
  20961. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  20962. "Sec-WebSocket-Version: 13\r\n"
  20963. "\r\n"))
  20964. << "attempt " << attempt;
  20965. std::string response;
  20966. while (response.find("\r\n\r\n") == std::string::npos) {
  20967. char buf[512];
  20968. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  20969. if (n <= 0) { break; }
  20970. response.append(buf, static_cast<size_t>(n));
  20971. }
  20972. ASSERT_NE(std::string::npos, response.find(" 101 "))
  20973. << "attempt " << attempt;
  20974. // Send the header of a Binary message but only the first prefix_len bytes
  20975. // of its payload, leaving the reader thread stalled inside the payload.
  20976. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  20977. expected.substr(0, prefix_len)))
  20978. << "attempt " << attempt;
  20979. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20980. peer_stalled = true;
  20981. // Let close() send its Close frame and park in its own read before the
  20982. // rest of the payload arrives, so both threads are waiting for it.
  20983. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20984. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  20985. close_frame += static_cast<char>(0x03); // status 1000
  20986. close_frame += static_cast<char>(0xE8);
  20987. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  20988. << "attempt " << attempt;
  20989. // Closing the peer releases the reader thread even on the buggy path,
  20990. // where it waits for bytes another thread already consumed.
  20991. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20992. detail::close_socket(sock);
  20993. sock = INVALID_SOCKET;
  20994. wait_for(handler_done);
  20995. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  20996. }
  20997. std::lock_guard<std::mutex> guard(received_mutex);
  20998. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  20999. << "a message in flight when close() ran was dropped";
  21000. for (size_t i = 0; i < received.size(); i++) {
  21001. EXPECT_EQ(expected, received[i]) << "message " << i;
  21002. }
  21003. }
  21004. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21005. class WebSocketSSLIntegrationTest : public ::testing::Test {
  21006. protected:
  21007. void SetUp() override {
  21008. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  21009. SERVER_PRIVATE_KEY_FILE);
  21010. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21011. std::string msg;
  21012. ws::ReadResult ret;
  21013. while ((ret = ws.read(msg))) {
  21014. if (ret == ws::Binary) {
  21015. ws.send(msg.data(), msg.size());
  21016. } else {
  21017. ws.send(msg);
  21018. }
  21019. }
  21020. });
  21021. port_ = server_->bind_to_any_port(HOST);
  21022. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21023. server_->wait_until_ready();
  21024. }
  21025. void TearDown() override {
  21026. server_->stop();
  21027. if (server_thread_.joinable()) { server_thread_.join(); }
  21028. }
  21029. std::unique_ptr<SSLServer> server_;
  21030. std::thread server_thread_;
  21031. int port_ = 0;
  21032. };
  21033. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  21034. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21035. "/ws-echo");
  21036. client.enable_server_certificate_verification(false);
  21037. ASSERT_TRUE(client.connect());
  21038. ASSERT_TRUE(client.is_open());
  21039. ASSERT_TRUE(client.send("Hello WSS"));
  21040. std::string msg;
  21041. EXPECT_EQ(ws::Text, client.read(msg));
  21042. EXPECT_EQ("Hello WSS", msg);
  21043. client.close();
  21044. }
  21045. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  21046. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  21047. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  21048. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  21049. // client (without calling close() first) is the only path that runs
  21050. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  21051. // bug exactly.
  21052. //
  21053. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  21054. // when linked against an instrumented libssl; run under Valgrind to catch it
  21055. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  21056. // suite (the freed session otherwise stalls on the close handshake) — this test
  21057. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  21058. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  21059. {
  21060. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21061. "/ws-echo");
  21062. client.enable_server_certificate_verification(false);
  21063. client.set_read_timeout(2, 0);
  21064. client.set_write_timeout(2, 0);
  21065. ASSERT_TRUE(client.connect());
  21066. ASSERT_TRUE(client.is_open());
  21067. ASSERT_TRUE(client.send("still open"));
  21068. // Intentionally do NOT call client.close(): leaving scope runs
  21069. // shutdown_and_close() with the WebSocket still open, which must send the
  21070. // close frame while the TLS session is still alive.
  21071. }
  21072. }
  21073. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  21074. // shutdown_and_close() at the start of connect(), reproducing the same
  21075. // use-after-free within the test body rather than at scope exit. The second
  21076. // connect must succeed and echo, proving the close handshake ran over a live
  21077. // session. See the note above about memory-tool requirements.
  21078. TEST_F(WebSocketSSLIntegrationTest,
  21079. ReconnectWhileOpenSendsCloseOverLiveSession) {
  21080. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21081. "/ws-echo");
  21082. client.enable_server_certificate_verification(false);
  21083. client.set_read_timeout(2, 0);
  21084. client.set_write_timeout(2, 0);
  21085. ASSERT_TRUE(client.connect());
  21086. ASSERT_TRUE(client.is_open());
  21087. ASSERT_TRUE(client.send("still open"));
  21088. // Reconnect without closing first: connect() calls shutdown_and_close() on
  21089. // the still-open connection, which must not touch a freed TLS session.
  21090. ASSERT_TRUE(client.connect());
  21091. ASSERT_TRUE(client.is_open());
  21092. ASSERT_TRUE(client.send("after reconnect"));
  21093. std::string msg;
  21094. EXPECT_EQ(ws::Text, client.read(msg));
  21095. EXPECT_EQ("after reconnect", msg);
  21096. client.close();
  21097. }
  21098. #endif
  21099. #ifdef CPPHTTPLIB_SSL_ENABLED
  21100. class WebSocketSSLCATest : public ::testing::Test {
  21101. protected:
  21102. void SetUp() override {
  21103. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  21104. SERVER_PRIVATE_KEY_FILE);
  21105. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21106. std::string msg;
  21107. while (ws.read(msg)) {
  21108. ws.send(msg);
  21109. }
  21110. });
  21111. port_ = server_->bind_to_any_port("127.0.0.1");
  21112. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21113. server_->wait_until_ready();
  21114. }
  21115. void TearDown() override {
  21116. server_->stop();
  21117. if (server_thread_.joinable()) { server_thread_.join(); }
  21118. }
  21119. std::string url() const {
  21120. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  21121. }
  21122. std::unique_ptr<SSLServer> server_;
  21123. std::thread server_thread_;
  21124. int port_ = 0;
  21125. };
  21126. // A custom CA loaded as PEM verifies the server with full certificate
  21127. // verification enabled
  21128. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  21129. ws::WebSocketClient client(url());
  21130. std::string cert;
  21131. read_file(SERVER_CERT2_FILE, cert);
  21132. client.load_ca_cert_store(cert.c_str(), cert.size());
  21133. ASSERT_TRUE(client.connect());
  21134. ASSERT_TRUE(client.send("hello"));
  21135. std::string msg;
  21136. EXPECT_EQ(ws::Text, client.read(msg));
  21137. EXPECT_EQ("hello", msg);
  21138. client.close();
  21139. }
  21140. // A custom CA that does not cover the server must fail verification (the
  21141. // custom CA is exclusive; system certs are not loaded alongside it)
  21142. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  21143. ws::WebSocketClient client(url());
  21144. std::string cert;
  21145. read_file(CLIENT_CA_CERT_FILE, cert);
  21146. client.load_ca_cert_store(cert.c_str(), cert.size());
  21147. auto res = client.connect();
  21148. ASSERT_FALSE(res);
  21149. EXPECT_EQ(Error::SSLServerVerification, res.error());
  21150. EXPECT_EQ(-1, res.status());
  21151. EXPECT_NE(0u, res.ssl_backend_error());
  21152. }
  21153. // The same CA as a file path rather than PEM in memory
  21154. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  21155. ws::WebSocketClient client(url());
  21156. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21157. ASSERT_TRUE(client.connect());
  21158. ASSERT_TRUE(client.send("hello"));
  21159. std::string msg;
  21160. EXPECT_EQ(ws::Text, client.read(msg));
  21161. EXPECT_EQ("hello", msg);
  21162. client.close();
  21163. }
  21164. // ...and a CA file that does not cover the server still fails, so it is the
  21165. // path above that decides the outcome
  21166. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  21167. ws::WebSocketClient client(url());
  21168. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21169. ASSERT_FALSE(client.connect());
  21170. }
  21171. // Regression test: reconnecting with a native custom CA store used to reuse
  21172. // a store handle the previous TLS context had already freed (use-after-free
  21173. // under the OpenSSL backend). The context now lives as long as the client.
  21174. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  21175. ws::WebSocketClient client(url());
  21176. std::string cert;
  21177. read_file(SERVER_CERT2_FILE, cert);
  21178. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  21179. ASSERT_TRUE(client.connect());
  21180. client.close();
  21181. ASSERT_TRUE(client.connect());
  21182. ASSERT_TRUE(client.send("again"));
  21183. std::string msg;
  21184. EXPECT_EQ(ws::Text, client.read(msg));
  21185. EXPECT_EQ("again", msg);
  21186. client.close();
  21187. }
  21188. // Regression test: a certificate with a trusted chain but no identity match
  21189. // for the server IP must be rejected. The Mbed TLS backend used to skip
  21190. // verification entirely for IP hosts, so this connection succeeded there.
  21191. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  21192. // chain verification while the identity check must still fail.
  21193. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  21194. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21195. ASSERT_TRUE(svr.is_valid());
  21196. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21197. std::string msg;
  21198. while (ws.read(msg)) {
  21199. ws.send(msg);
  21200. }
  21201. });
  21202. auto port = svr.bind_to_any_port("127.0.0.1");
  21203. auto t = std::thread([&]() { svr.listen_after_bind(); });
  21204. auto se = detail::scope_exit([&] {
  21205. svr.stop();
  21206. t.join();
  21207. });
  21208. svr.wait_until_ready();
  21209. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  21210. "/echo");
  21211. std::string cert;
  21212. read_file(SERVER_CERT_FILE, cert);
  21213. client.load_ca_cert_store(cert.c_str(), cert.size());
  21214. ASSERT_FALSE(client.connect());
  21215. }
  21216. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  21217. // SNI, so nothing binds the host name to the TLS session. These bind the
  21218. // server to "localhost" instead, the only shape that exercises the SNI and
  21219. // hostname-verification path with certificate verification left enabled.
  21220. class WebSocketSSLDnsHostTest : public ::testing::Test {
  21221. protected:
  21222. void Start(const char *cert_file) {
  21223. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  21224. SERVER_PRIVATE_KEY_FILE);
  21225. ASSERT_TRUE(server_->is_valid());
  21226. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21227. std::string msg;
  21228. while (ws.read(msg)) {
  21229. ws.send(msg);
  21230. }
  21231. });
  21232. port_ = server_->bind_to_any_port("localhost");
  21233. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21234. server_->wait_until_ready();
  21235. }
  21236. void TearDown() override {
  21237. if (server_) { server_->stop(); }
  21238. if (server_thread_.joinable()) { server_thread_.join(); }
  21239. }
  21240. std::string url() const {
  21241. return "wss://localhost:" + std::to_string(port_) + "/echo";
  21242. }
  21243. std::unique_ptr<SSLServer> server_;
  21244. std::thread server_thread_;
  21245. int port_ = 0;
  21246. };
  21247. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  21248. // out and the connection is usable
  21249. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  21250. Start(SERVER_CERT2_FILE);
  21251. ws::WebSocketClient client(url());
  21252. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21253. ASSERT_TRUE(client.connect());
  21254. ASSERT_TRUE(client.send("hello"));
  21255. std::string msg;
  21256. EXPECT_EQ(ws::Text, client.read(msg));
  21257. EXPECT_EQ("hello", msg);
  21258. client.close();
  21259. }
  21260. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  21261. // while the identity check must still reject "localhost"
  21262. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  21263. Start(SERVER_CERT_FILE);
  21264. ws::WebSocketClient client(url());
  21265. client.set_ca_cert_path(SERVER_CERT_FILE);
  21266. auto res = client.connect();
  21267. ASSERT_FALSE(res);
  21268. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  21269. EXPECT_EQ(-1, res.status());
  21270. }
  21271. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  21272. // disabled: the chain is still checked, only the identity check is skipped
  21273. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  21274. Start(SERVER_CERT_FILE);
  21275. ws::WebSocketClient client(url());
  21276. client.set_ca_cert_path(SERVER_CERT_FILE);
  21277. client.enable_server_hostname_verification(false);
  21278. ASSERT_TRUE(client.connect());
  21279. ASSERT_TRUE(client.send("hello"));
  21280. std::string msg;
  21281. EXPECT_EQ(ws::Text, client.read(msg));
  21282. EXPECT_EQ("hello", msg);
  21283. client.close();
  21284. }
  21285. // A CA that did not sign the server certificate fails the chain, even though
  21286. // the name would match
  21287. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  21288. Start(SERVER_CERT2_FILE);
  21289. ws::WebSocketClient client(url());
  21290. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21291. ASSERT_FALSE(client.connect());
  21292. }
  21293. // With verification disabled, neither the chain nor the name is checked
  21294. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  21295. Start(SERVER_CERT_FILE);
  21296. ws::WebSocketClient client(url());
  21297. client.enable_server_certificate_verification(false);
  21298. ASSERT_TRUE(client.connect());
  21299. ASSERT_TRUE(client.send("hello"));
  21300. std::string msg;
  21301. EXPECT_EQ(ws::Text, client.read(msg));
  21302. EXPECT_EQ("hello", msg);
  21303. client.close();
  21304. }
  21305. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  21306. protected:
  21307. void SetUp() override {
  21308. server_ = httplib::detail::make_unique<SSLServer>(
  21309. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21310. ASSERT_TRUE(server_->is_valid());
  21311. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21312. std::string msg;
  21313. while (ws.read(msg)) {
  21314. ws.send(msg);
  21315. }
  21316. });
  21317. port_ = server_->bind_to_any_port("localhost");
  21318. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21319. server_->wait_until_ready();
  21320. }
  21321. void TearDown() override {
  21322. server_->stop();
  21323. if (server_thread_.joinable()) { server_thread_.join(); }
  21324. }
  21325. std::string url() const {
  21326. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  21327. }
  21328. void ConnectWithClientCert(const std::string &client_cert_file,
  21329. const std::string &client_private_key_file,
  21330. const char *private_key_password) {
  21331. std::string cert_pem, key_pem;
  21332. read_file(client_cert_file, cert_pem);
  21333. read_file(client_private_key_file, key_pem);
  21334. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  21335. key_pem.c_str(), key_pem.size(),
  21336. private_key_password};
  21337. ws::WebSocketClient client(url(), pem);
  21338. ASSERT_TRUE(client.is_valid());
  21339. client.enable_server_certificate_verification(false);
  21340. ASSERT_TRUE(client.connect());
  21341. ASSERT_TRUE(client.send("hello"));
  21342. std::string msg;
  21343. EXPECT_EQ(ws::Text, client.read(msg));
  21344. EXPECT_EQ("hello", msg);
  21345. client.close();
  21346. }
  21347. std::unique_ptr<SSLServer> server_;
  21348. std::thread server_thread_;
  21349. int port_ = 0;
  21350. };
  21351. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  21352. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  21353. }
  21354. // Control for the tests above: the fixture's server really does require a
  21355. // client certificate, so it is the PEM the constructor installed that decides
  21356. // the outcome.
  21357. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  21358. ws::WebSocketClient client(url());
  21359. ASSERT_TRUE(client.is_valid());
  21360. client.enable_server_certificate_verification(false);
  21361. EXPECT_FALSE(client.connect());
  21362. }
  21363. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  21364. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  21365. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  21366. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  21367. }
  21368. #endif
  21369. #if !defined(_WIN32)
  21370. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  21371. auto secret_dir = std::string("./symlink_test_secret");
  21372. auto served_dir = std::string("./symlink_test_served");
  21373. auto secret_file = secret_dir + "/secret.txt";
  21374. auto symlink_path = served_dir + "/escape";
  21375. // Setup: create directories and files
  21376. mkdir(secret_dir.c_str(), 0755);
  21377. mkdir(served_dir.c_str(), 0755);
  21378. {
  21379. std::ofstream ofs(secret_file);
  21380. ofs << "SECRET_DATA";
  21381. }
  21382. // Create symlink using absolute path so it resolves correctly
  21383. #ifdef PATH_MAX
  21384. char abs_secret[PATH_MAX];
  21385. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  21386. #else
  21387. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  21388. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  21389. ASSERT_NE(nullptr, abs_secret);
  21390. #endif
  21391. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  21392. auto se = detail::scope_exit([&] {
  21393. unlink(symlink_path.c_str());
  21394. unlink(secret_file.c_str());
  21395. rmdir(served_dir.c_str());
  21396. rmdir(secret_dir.c_str());
  21397. });
  21398. Server svr;
  21399. svr.set_mount_point("/", served_dir);
  21400. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  21401. auto se2 = detail::scope_exit([&] {
  21402. svr.stop();
  21403. listen_thread.join();
  21404. });
  21405. svr.wait_until_ready();
  21406. Client cli("localhost", PORT);
  21407. // Symlink pointing outside base dir should be blocked
  21408. auto res = cli.Get("/escape/secret.txt");
  21409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21410. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  21411. }
  21412. #endif
  21413. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  21414. // "GET /smuggled" request), reads the first response, and only then sends the
  21415. // embedded request as the body. Returns how many times /smuggled ran.
  21416. //
  21417. // The body is sent AFTER receiving the first response (as in the original
  21418. // PoC) so that the stream_line_reader cannot buffer it together with the
  21419. // headers of the first request.
  21420. static int count_smuggled_requests(const std::string &outer_head,
  21421. std::string &first_response) {
  21422. Server svr;
  21423. svr.set_mount_point("/", "./www");
  21424. std::atomic<int> smuggled_count(0);
  21425. svr.Get("/smuggled", [&](const Request &, Response &res) {
  21426. smuggled_count++;
  21427. res.set_content("oops", "text/plain");
  21428. });
  21429. svr.Post("/post", [&](const Request &req, Response &res) {
  21430. res.set_content(req.body, "text/plain");
  21431. });
  21432. auto port = svr.bind_to_any_port("localhost");
  21433. thread t = thread([&] { svr.listen_after_bind(); });
  21434. auto se = detail::scope_exit([&] {
  21435. svr.stop();
  21436. t.join();
  21437. });
  21438. svr.wait_until_ready();
  21439. auto error = Error::Success;
  21440. auto sock = detail::create_client_socket(
  21441. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  21442. /*connection_timeout_sec=*/2, 0,
  21443. /*read_timeout_sec=*/2, 0,
  21444. /*write_timeout_sec=*/2, 0, std::string(), error);
  21445. EXPECT_NE(INVALID_SOCKET, sock);
  21446. if (sock == INVALID_SOCKET) { return -1; }
  21447. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21448. // The "smuggled" request will be sent as the body of the outer request
  21449. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  21450. "Host: localhost\r\n"
  21451. "Connection: close\r\n"
  21452. "\r\n";
  21453. auto head = outer_head;
  21454. auto len = std::to_string(smuggled.size());
  21455. for (auto pos = head.find("{len}"); pos != std::string::npos;
  21456. pos = head.find("{len}", pos + len.size())) {
  21457. head.replace(pos, 5, len);
  21458. }
  21459. // Step 1: Send only the outer request headers (no body yet)
  21460. auto sent = send(sock, head.data(), head.size(), 0);
  21461. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  21462. // Step 2: Read the first response
  21463. char buf[4096];
  21464. for (;;) {
  21465. auto n = recv(sock, buf, sizeof(buf), 0);
  21466. if (n <= 0) break;
  21467. first_response.append(buf, static_cast<size_t>(n));
  21468. // Stop once we have a complete response (headers + body)
  21469. auto hdr_end = first_response.find("\r\n\r\n");
  21470. if (hdr_end != std::string::npos) {
  21471. // Check for Content-Length to know when the body is complete
  21472. auto cl_pos = first_response.find("Content-Length:");
  21473. if (cl_pos != std::string::npos) {
  21474. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  21475. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  21476. auto cl = std::stoul(
  21477. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  21478. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  21479. } else {
  21480. break; // No Content-Length, assume headers-only response
  21481. }
  21482. }
  21483. }
  21484. // Step 3: Now send the body, which looks like a new HTTP request. On a
  21485. // vulnerable server the keep-alive loop reads this as a second request. The
  21486. // server may already have closed the connection, so the result is ignored.
  21487. send(sock, smuggled.data(), smuggled.size(), 0);
  21488. // Half-close so that a server which drained the body sees EOF and closes,
  21489. // instead of the read below waiting for the read timeout.
  21490. #ifdef _WIN32
  21491. ::shutdown(sock, SD_SEND);
  21492. #else
  21493. ::shutdown(sock, SHUT_WR);
  21494. #endif
  21495. // Step 4: Read until the server closes the connection
  21496. for (;;) {
  21497. auto n = recv(sock, buf, sizeof(buf), 0);
  21498. if (n <= 0) break;
  21499. }
  21500. return smuggled_count.load();
  21501. }
  21502. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  21503. // A GET request with Content-Length to a static file handler must have its
  21504. // body drained before the keep-alive connection is reused. Otherwise the
  21505. // unread body bytes are interpreted as the next HTTP request.
  21506. std::string first_response;
  21507. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  21508. "Host: localhost\r\n"
  21509. "Content-Length: {len}\r\n"
  21510. "\r\n",
  21511. first_response));
  21512. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  21513. }
  21514. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  21515. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  21516. // be answered with 400 and the connection closed. Treating it as "no body"
  21517. // leaves the body to be parsed as the next request.
  21518. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  21519. const char *targets[] = {
  21520. "GET /file", // handler that never reads the body
  21521. "GET /not-found", // no handler matches (404)
  21522. "POST /post", // handler that reads the body
  21523. };
  21524. for (auto target : targets) {
  21525. for (auto value : values) {
  21526. std::string first_response;
  21527. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  21528. " HTTP/1.1\r\n"
  21529. "Host: localhost\r\n"
  21530. "Content-Length: " +
  21531. value + "\r\n\r\n",
  21532. first_response))
  21533. << target << " with Content-Length: " << value;
  21534. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  21535. << target << " with Content-Length: " << value;
  21536. }
  21537. }
  21538. }
  21539. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  21540. // A 400 for an unparseable request line leaves the rest of the message
  21541. // unread, so the connection must be closed rather than reused.
  21542. std::string first_response;
  21543. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  21544. "Host: localhost\r\n"
  21545. "Content-Length: {len}\r\n"
  21546. "\r\n",
  21547. first_response));
  21548. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  21549. }
  21550. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  21551. // Same as above for a header block that fails to parse.
  21552. std::string first_response;
  21553. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  21554. "Host: localhost\r\n"
  21555. "Bad Header\r\n"
  21556. "Content-Length: {len}\r\n"
  21557. "\r\n",
  21558. first_response));
  21559. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  21560. }
  21561. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  21562. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  21563. // server must not read another request on that connection, even when the
  21564. // request had no body to drain.
  21565. std::string first_response;
  21566. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  21567. "Host: localhost\r\n"
  21568. "\r\n",
  21569. first_response));
  21570. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  21571. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  21572. }
  21573. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21574. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  21575. // must be rejected with 400 Bad Request.
  21576. Server svr;
  21577. svr.Post("/test", [&](const Request &, Response &res) {
  21578. res.set_content("ok", "text/plain");
  21579. });
  21580. thread t = thread([&] { svr.listen(HOST, PORT); });
  21581. auto se = detail::scope_exit([&] {
  21582. svr.stop();
  21583. t.join();
  21584. ASSERT_FALSE(svr.is_running());
  21585. });
  21586. svr.wait_until_ready();
  21587. // Exact "chunked"
  21588. {
  21589. auto req = "POST /test HTTP/1.1\r\n"
  21590. "Host: localhost\r\n"
  21591. "Content-Length: 5\r\n"
  21592. "Transfer-Encoding: chunked\r\n"
  21593. "Connection: close\r\n"
  21594. "\r\n"
  21595. "hello";
  21596. std::string response;
  21597. ASSERT_TRUE(send_request(1, req, &response));
  21598. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21599. response.substr(0, response.find("\r\n")));
  21600. }
  21601. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  21602. {
  21603. auto req = "POST /test HTTP/1.1\r\n"
  21604. "Host: localhost\r\n"
  21605. "Content-Length: 5\r\n"
  21606. "Transfer-Encoding: gzip, chunked\r\n"
  21607. "Connection: close\r\n"
  21608. "\r\n"
  21609. "hello";
  21610. std::string response;
  21611. ASSERT_TRUE(send_request(1, req, &response));
  21612. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21613. response.substr(0, response.find("\r\n")));
  21614. }
  21615. }
  21616. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  21617. Server svr;
  21618. svr.Post("/test", [&](const Request &, Response &res) {
  21619. res.set_content("ok", "text/plain");
  21620. });
  21621. thread t = thread([&] { svr.listen(HOST, PORT); });
  21622. auto se = detail::scope_exit([&] {
  21623. svr.stop();
  21624. t.join();
  21625. ASSERT_FALSE(svr.is_running());
  21626. });
  21627. svr.wait_until_ready();
  21628. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  21629. // length cannot be determined, so the server must answer 400 and close
  21630. // rather than treat the request as bodyless and leave the body in the
  21631. // socket for the next request to pick up.
  21632. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  21633. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  21634. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  21635. std::string response;
  21636. ASSERT_TRUE(send_request(1, req, &response));
  21637. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21638. response.substr(0, response.find("\r\n")))
  21639. << transfer_encoding;
  21640. }
  21641. // RFC 9110 5.3: the codings may also be split across several
  21642. // Transfer-Encoding lines, which combine in the order they were received.
  21643. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  21644. // just like the single-line "chunked, gzip" above.
  21645. {
  21646. auto req = "POST /test HTTP/1.1\r\n"
  21647. "Host: localhost\r\n"
  21648. "Transfer-Encoding: chunked\r\n"
  21649. "Transfer-Encoding: gzip\r\n"
  21650. "\r\n"
  21651. "0\r\n\r\n";
  21652. std::string response;
  21653. ASSERT_TRUE(send_request(1, req, &response));
  21654. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21655. response.substr(0, response.find("\r\n")));
  21656. }
  21657. // A sequence ending in chunked stays valid.
  21658. auto req = "POST /test HTTP/1.1\r\n"
  21659. "Host: localhost\r\n"
  21660. "Transfer-Encoding: gzip, chunked\r\n"
  21661. "Connection: close\r\n"
  21662. "\r\n"
  21663. "0\r\n\r\n";
  21664. std::string response;
  21665. ASSERT_TRUE(send_request(1, req, &response));
  21666. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  21667. // ...including when it is spread over several lines.
  21668. auto split_req = "POST /test HTTP/1.1\r\n"
  21669. "Host: localhost\r\n"
  21670. "Transfer-Encoding: gzip\r\n"
  21671. "Transfer-Encoding: chunked\r\n"
  21672. "Connection: close\r\n"
  21673. "\r\n"
  21674. "0\r\n\r\n";
  21675. std::string split_response;
  21676. ASSERT_TRUE(send_request(1, split_req, &split_response));
  21677. EXPECT_EQ("HTTP/1.1 200 OK",
  21678. split_response.substr(0, split_response.find("\r\n")));
  21679. }
  21680. // Regression for issue #2450: a DELETE without Content-Length on a
  21681. // keep-alive connection must not let the post-response drain consume the
  21682. // next request's bytes.
  21683. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  21684. Server svr;
  21685. std::atomic<int> delete_count(0);
  21686. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  21687. delete_count++;
  21688. res.status = StatusCode::NoContent_204;
  21689. });
  21690. auto port = svr.bind_to_any_port(HOST);
  21691. thread t = thread([&] { svr.listen_after_bind(); });
  21692. auto se = detail::scope_exit([&] {
  21693. svr.stop();
  21694. t.join();
  21695. });
  21696. svr.wait_until_ready();
  21697. auto error = Error::Success;
  21698. auto sock = detail::create_client_socket(
  21699. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21700. /*connection_timeout_sec=*/2, 0,
  21701. /*read_timeout_sec=*/2, 0,
  21702. /*write_timeout_sec=*/2, 0, std::string(), error);
  21703. ASSERT_NE(INVALID_SOCKET, sock);
  21704. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21705. auto send_request_and_read_response = [&](const std::string &req,
  21706. std::string &out) -> bool {
  21707. auto sent = send(sock, req.data(), req.size(), 0);
  21708. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  21709. char buf[4096];
  21710. for (;;) {
  21711. auto n = recv(sock, buf, sizeof(buf), 0);
  21712. if (n <= 0) { return !out.empty(); }
  21713. out.append(buf, static_cast<size_t>(n));
  21714. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  21715. }
  21716. };
  21717. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  21718. "Host: localhost\r\n"
  21719. "\r\n";
  21720. std::string resp1;
  21721. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  21722. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  21723. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  21724. "Host: localhost\r\n"
  21725. "Connection: close\r\n"
  21726. "\r\n";
  21727. std::string resp2;
  21728. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  21729. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  21730. EXPECT_EQ(2, delete_count.load());
  21731. }
  21732. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  21733. Server svr;
  21734. svr.Post("/ingest", [&](const Request &, Response &res,
  21735. const ContentReader &content_reader) {
  21736. auto consumed = content_reader([](const char *, size_t) { return false; });
  21737. EXPECT_FALSE(consumed);
  21738. res.status = StatusCode::Conflict_409;
  21739. res.set_header("Connection", "close");
  21740. });
  21741. auto port = svr.bind_to_any_port(HOST);
  21742. thread t = thread([&] { svr.listen_after_bind(); });
  21743. auto se = detail::scope_exit([&] {
  21744. svr.stop();
  21745. t.join();
  21746. });
  21747. svr.wait_until_ready();
  21748. auto error = Error::Success;
  21749. auto sock = detail::create_client_socket(
  21750. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21751. /*connection_timeout_sec=*/2, 0,
  21752. /*read_timeout_sec=*/1, 0,
  21753. /*write_timeout_sec=*/2, 0, std::string(), error);
  21754. ASSERT_NE(INVALID_SOCKET, sock);
  21755. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21756. std::string request = "POST /ingest HTTP/1.1\r\n"
  21757. "Host: localhost\r\n"
  21758. "Transfer-Encoding: chunked\r\n"
  21759. "\r\n"
  21760. "4\r\n"
  21761. "data\r\n";
  21762. auto sent = send(sock, request.data(), request.size(), 0);
  21763. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  21764. std::string response;
  21765. ssize_t received = 0;
  21766. do {
  21767. char buf[4096];
  21768. received = recv(sock, buf, sizeof(buf), 0);
  21769. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  21770. } while (received > 0);
  21771. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  21772. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  21773. EXPECT_EQ(0, received);
  21774. }
  21775. namespace no_proxy_test {
  21776. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  21777. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  21778. // calling listen().
  21779. class ScopedServer {
  21780. public:
  21781. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  21782. ~ScopedServer() {
  21783. svr_.stop();
  21784. if (th_.joinable()) { th_.join(); }
  21785. }
  21786. Server &svr() { return svr_; }
  21787. int port() const { return port_; }
  21788. void listen() {
  21789. th_ = std::thread([this] { svr_.listen_after_bind(); });
  21790. svr_.wait_until_ready();
  21791. }
  21792. private:
  21793. Server svr_;
  21794. std::thread th_;
  21795. int port_ = 0;
  21796. };
  21797. class ProxyAndTargetServers {
  21798. public:
  21799. ProxyAndTargetServers() {
  21800. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  21801. proxy_hits_++;
  21802. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  21803. res.set_content("via-proxy", "text/plain");
  21804. });
  21805. target_.Get(".*", [this](const Request &req, Response &res) {
  21806. target_hits_++;
  21807. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  21808. res.set_content("direct", "text/plain");
  21809. });
  21810. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  21811. target_port_ = target_.bind_to_any_port("127.0.0.1");
  21812. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  21813. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  21814. proxy_mock_.wait_until_ready();
  21815. target_.wait_until_ready();
  21816. }
  21817. ~ProxyAndTargetServers() {
  21818. proxy_mock_.stop();
  21819. target_.stop();
  21820. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  21821. if (target_thread_.joinable()) { target_thread_.join(); }
  21822. }
  21823. Server &proxy_mock() { return proxy_mock_; }
  21824. Server &target() { return target_; }
  21825. int proxy_port() const { return proxy_port_; }
  21826. int target_port() const { return target_port_; }
  21827. int proxy_hits() const { return proxy_hits_.load(); }
  21828. int target_hits() const { return target_hits_.load(); }
  21829. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  21830. void reset_counters() {
  21831. proxy_hits_ = 0;
  21832. target_hits_ = 0;
  21833. last_had_proxy_authz_ = false;
  21834. }
  21835. private:
  21836. Server proxy_mock_;
  21837. Server target_;
  21838. std::thread proxy_thread_;
  21839. std::thread target_thread_;
  21840. int proxy_port_ = 0;
  21841. int target_port_ = 0;
  21842. std::atomic<int> proxy_hits_{0};
  21843. std::atomic<int> target_hits_{0};
  21844. std::atomic<bool> last_had_proxy_authz_{false};
  21845. };
  21846. inline std::unique_ptr<Client> make_client(const std::string &host,
  21847. ProxyAndTargetServers &s) {
  21848. auto cli = detail::make_unique<Client>(host, s.target_port());
  21849. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  21850. cli->set_proxy("127.0.0.1", s.proxy_port());
  21851. return cli;
  21852. }
  21853. } // namespace no_proxy_test
  21854. using no_proxy_test::make_client;
  21855. using no_proxy_test::ProxyAndTargetServers;
  21856. TEST(NoProxyTest, ExactHostnameBypasses) {
  21857. ProxyAndTargetServers s;
  21858. auto cli = make_client("example.com", s);
  21859. cli->set_no_proxy({"example.com"});
  21860. auto res = cli->Get("/");
  21861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21862. EXPECT_EQ(0, s.proxy_hits());
  21863. EXPECT_EQ(1, s.target_hits());
  21864. }
  21865. TEST(NoProxyTest, SubdomainBypasses) {
  21866. ProxyAndTargetServers s;
  21867. auto cli = make_client("foo.example.com", s);
  21868. cli->set_no_proxy({"example.com"});
  21869. auto res = cli->Get("/");
  21870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21871. EXPECT_EQ(0, s.proxy_hits());
  21872. EXPECT_EQ(1, s.target_hits());
  21873. }
  21874. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  21875. // Regression guard: "evilexample.com" must not be considered a subdomain
  21876. // of "example.com". Without the dot-boundary rule, a naive endsWith
  21877. // check would let traffic bypass the proxy and leak credentials direct
  21878. // to the attacker host.
  21879. ProxyAndTargetServers s;
  21880. auto cli = make_client("evilexample.com", s);
  21881. cli->set_no_proxy({"example.com"});
  21882. auto res = cli->Get("/");
  21883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21884. EXPECT_GE(s.proxy_hits(), 1);
  21885. EXPECT_EQ(0, s.target_hits());
  21886. }
  21887. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  21888. ProxyAndTargetServers s;
  21889. auto cli = make_client("example.com.evil.com", s);
  21890. cli->set_no_proxy({"example.com"});
  21891. auto res = cli->Get("/");
  21892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21893. EXPECT_GE(s.proxy_hits(), 1);
  21894. EXPECT_EQ(0, s.target_hits());
  21895. }
  21896. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  21897. ProxyAndTargetServers s;
  21898. auto cli = make_client("example.com", s);
  21899. cli->set_no_proxy({".example.com"});
  21900. auto res = cli->Get("/");
  21901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21902. EXPECT_EQ(0, s.proxy_hits());
  21903. EXPECT_EQ(1, s.target_hits());
  21904. }
  21905. TEST(NoProxyTest, CaseInsensitiveHostname) {
  21906. ProxyAndTargetServers s;
  21907. auto cli = make_client("Example.COM", s);
  21908. cli->set_no_proxy({"EXAMPLE.com"});
  21909. auto res = cli->Get("/");
  21910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21911. EXPECT_EQ(0, s.proxy_hits());
  21912. EXPECT_EQ(1, s.target_hits());
  21913. }
  21914. TEST(NoProxyTest, TrailingDotIsNormalized) {
  21915. ProxyAndTargetServers s;
  21916. auto cli = make_client("example.com.", s);
  21917. cli->set_no_proxy({"example.com"});
  21918. auto res = cli->Get("/");
  21919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21920. EXPECT_EQ(0, s.proxy_hits());
  21921. EXPECT_EQ(1, s.target_hits());
  21922. }
  21923. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  21924. // Trailing dots must be normalized on BOTH sides — host and entry.
  21925. // An implementation that only strips the host-side trailing dot would
  21926. // fail to match host "example.com" against entry "example.com." because
  21927. // a literal substring search would compare 11 chars against 12.
  21928. ProxyAndTargetServers s;
  21929. auto cli = make_client("example.com", s);
  21930. cli->set_no_proxy({"example.com."});
  21931. auto res = cli->Get("/");
  21932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21933. EXPECT_EQ(0, s.proxy_hits());
  21934. EXPECT_EQ(1, s.target_hits());
  21935. }
  21936. TEST(NoProxyTest, WildcardBypassesEverything) {
  21937. ProxyAndTargetServers s;
  21938. auto cli = make_client("anything.invalid.test", s);
  21939. cli->set_no_proxy({"*"});
  21940. auto res = cli->Get("/");
  21941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21942. EXPECT_EQ(0, s.proxy_hits());
  21943. EXPECT_EQ(1, s.target_hits());
  21944. }
  21945. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  21946. ProxyAndTargetServers s;
  21947. Client cli("127.0.0.1", s.target_port());
  21948. cli.set_proxy("127.0.0.1", s.proxy_port());
  21949. cli.set_no_proxy({"127.0.0.1"});
  21950. auto res = cli.Get("/");
  21951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21952. EXPECT_EQ(0, s.proxy_hits());
  21953. EXPECT_EQ(1, s.target_hits());
  21954. }
  21955. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  21956. ProxyAndTargetServers s;
  21957. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  21958. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  21959. cli.set_proxy("127.0.0.1", s.proxy_port());
  21960. cli.set_no_proxy({"::1"});
  21961. auto res = cli.Get("/");
  21962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21963. EXPECT_EQ(0, s.proxy_hits());
  21964. EXPECT_EQ(1, s.target_hits());
  21965. }
  21966. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  21967. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  21968. // must still be recognized as IPv6 for CIDR matching. Implementations
  21969. // that detect IPv6 only when the host begins with '[' would parse the
  21970. // host as a hostname and miss the match.
  21971. ProxyAndTargetServers s;
  21972. Client cli("fe80::1", s.target_port());
  21973. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  21974. cli.set_proxy("127.0.0.1", s.proxy_port());
  21975. cli.set_no_proxy({"fe80::/10"});
  21976. auto res = cli.Get("/");
  21977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21978. EXPECT_EQ(0, s.proxy_hits());
  21979. EXPECT_EQ(1, s.target_hits());
  21980. }
  21981. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  21982. ProxyAndTargetServers s;
  21983. Client cli("::1", s.target_port());
  21984. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  21985. cli.set_proxy("127.0.0.1", s.proxy_port());
  21986. cli.set_no_proxy({"[::1]"});
  21987. auto res = cli.Get("/");
  21988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21989. EXPECT_EQ(0, s.proxy_hits());
  21990. EXPECT_EQ(1, s.target_hits());
  21991. }
  21992. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  21993. ProxyAndTargetServers s;
  21994. Client cli("fe80::1", s.target_port());
  21995. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  21996. cli.set_proxy("127.0.0.1", s.proxy_port());
  21997. cli.set_no_proxy({"[fe80::]/10"});
  21998. auto res = cli.Get("/");
  21999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22000. EXPECT_EQ(0, s.proxy_hits());
  22001. EXPECT_EQ(1, s.target_hits());
  22002. }
  22003. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  22004. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  22005. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  22006. // tricks via address-family conversion.
  22007. ProxyAndTargetServers s;
  22008. Client cli("::ffff:127.0.0.1", s.target_port());
  22009. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  22010. cli.set_proxy("127.0.0.1", s.proxy_port());
  22011. cli.set_no_proxy({"127.0.0.1"});
  22012. auto res = cli.Get("/");
  22013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22014. EXPECT_GE(s.proxy_hits(), 1);
  22015. EXPECT_EQ(0, s.target_hits());
  22016. }
  22017. TEST(NoProxyTest, IPv4CidrMatch) {
  22018. ProxyAndTargetServers s;
  22019. Client cli("127.0.0.1", s.target_port());
  22020. cli.set_proxy("127.0.0.1", s.proxy_port());
  22021. cli.set_no_proxy({"127.0.0.0/8"});
  22022. auto res = cli.Get("/");
  22023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22024. EXPECT_EQ(0, s.proxy_hits());
  22025. EXPECT_EQ(1, s.target_hits());
  22026. }
  22027. TEST(NoProxyTest, IPv4CidrNonMatch) {
  22028. ProxyAndTargetServers s;
  22029. Client cli("127.0.0.1", s.target_port());
  22030. cli.set_proxy("127.0.0.1", s.proxy_port());
  22031. cli.set_no_proxy({"10.0.0.0/8"});
  22032. auto res = cli.Get("/");
  22033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22034. EXPECT_GE(s.proxy_hits(), 1);
  22035. EXPECT_EQ(0, s.target_hits());
  22036. }
  22037. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  22038. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  22039. // IPv4 target matches.
  22040. ProxyAndTargetServers s;
  22041. Client cli("127.0.0.1", s.target_port());
  22042. cli.set_proxy("127.0.0.1", s.proxy_port());
  22043. cli.set_no_proxy({"0.0.0.0/0"});
  22044. auto res = cli.Get("/");
  22045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22046. EXPECT_EQ(0, s.proxy_hits());
  22047. EXPECT_EQ(1, s.target_hits());
  22048. }
  22049. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  22050. ProxyAndTargetServers s;
  22051. Client cli("127.0.0.1", s.target_port());
  22052. cli.set_proxy("127.0.0.1", s.proxy_port());
  22053. cli.set_no_proxy({"127.0.0.1"});
  22054. auto res = cli.Get("/");
  22055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22056. EXPECT_EQ(0, s.proxy_hits());
  22057. EXPECT_EQ(1, s.target_hits());
  22058. }
  22059. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  22060. ProxyAndTargetServers s;
  22061. Client cli("127.0.0.1", s.target_port());
  22062. cli.set_proxy("127.0.0.1", s.proxy_port());
  22063. cli.set_no_proxy({"127.0.0.0/33"});
  22064. auto res = cli.Get("/");
  22065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22066. EXPECT_GE(s.proxy_hits(), 1);
  22067. EXPECT_EQ(0, s.target_hits());
  22068. }
  22069. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  22070. // Empty prefix after the slash must be rejected, not silently treated as /32.
  22071. ProxyAndTargetServers s;
  22072. Client cli("127.0.0.1", s.target_port());
  22073. cli.set_proxy("127.0.0.1", s.proxy_port());
  22074. cli.set_no_proxy({"127.0.0.1/"});
  22075. auto res = cli.Get("/");
  22076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22077. EXPECT_GE(s.proxy_hits(), 1);
  22078. EXPECT_EQ(0, s.target_hits());
  22079. }
  22080. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  22081. ProxyAndTargetServers s;
  22082. auto cli = make_client("internal.corp", s);
  22083. cli->set_proxy_basic_auth("u", "p");
  22084. cli->set_no_proxy({"internal.corp"});
  22085. auto res = cli->Get("/");
  22086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22087. EXPECT_EQ(1, s.target_hits());
  22088. EXPECT_EQ(0, s.proxy_hits());
  22089. EXPECT_FALSE(s.last_had_proxy_authz())
  22090. << "Proxy-Authorization must not be sent direct to the target";
  22091. }
  22092. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  22093. ProxyAndTargetServers s;
  22094. auto cli = make_client("public.example", s);
  22095. cli->set_proxy_basic_auth("u", "p");
  22096. cli->set_no_proxy({"internal.corp"}); // does not match
  22097. auto res = cli->Get("/");
  22098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22099. EXPECT_GE(s.proxy_hits(), 1);
  22100. EXPECT_TRUE(s.last_had_proxy_authz());
  22101. }
  22102. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  22103. ProxyAndTargetServers s;
  22104. auto cli = make_client("anything.test", s);
  22105. auto res = cli->Get("/");
  22106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22107. EXPECT_GE(s.proxy_hits(), 1);
  22108. EXPECT_EQ(0, s.target_hits());
  22109. }
  22110. TEST(NoProxyTest, PortSpecificEntryRejected) {
  22111. ProxyAndTargetServers s;
  22112. auto cli = make_client("example.com", s);
  22113. cli->set_no_proxy({"example.com:8080"});
  22114. auto res = cli->Get("/");
  22115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22116. EXPECT_GE(s.proxy_hits(), 1);
  22117. EXPECT_EQ(0, s.target_hits());
  22118. }
  22119. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  22120. ProxyAndTargetServers s;
  22121. auto cli = make_client("anything.test", s);
  22122. cli->set_no_proxy({"", " ", "\t"});
  22123. auto res = cli->Get("/");
  22124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22125. EXPECT_GE(s.proxy_hits(), 1);
  22126. EXPECT_EQ(0, s.target_hits());
  22127. }
  22128. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  22129. // An entry with leading/trailing whitespace must still match — env-style
  22130. // values are commonly pasted with stray spaces and an implementation
  22131. // that feeds the raw token directly to inet_pton would fail to match
  22132. // valid CIDRs because of the spaces.
  22133. ProxyAndTargetServers s;
  22134. Client cli("127.0.0.1", s.target_port());
  22135. cli.set_proxy("127.0.0.1", s.proxy_port());
  22136. cli.set_no_proxy({" 127.0.0.0/8 "});
  22137. auto res = cli.Get("/");
  22138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22139. EXPECT_EQ(0, s.proxy_hits());
  22140. EXPECT_EQ(1, s.target_hits());
  22141. }
  22142. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  22143. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  22144. // go direct and must NOT carry Proxy-Authorization.
  22145. std::atomic<int> proxy_hits{0};
  22146. std::atomic<int> target_hits{0};
  22147. std::atomic<bool> target_saw_authz{false};
  22148. no_proxy_test::ScopedServer proxy_mock, target;
  22149. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  22150. proxy_hits++;
  22151. res.status = 302;
  22152. res.set_header("Location", "http://127.0.0.1:" +
  22153. std::to_string(target.port()) + "/landed");
  22154. });
  22155. target.svr().Get(".*", [&](const Request &req, Response &res) {
  22156. target_hits++;
  22157. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  22158. res.set_content("direct", "text/plain");
  22159. });
  22160. proxy_mock.listen();
  22161. target.listen();
  22162. Client cli("public.example", target.port());
  22163. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22164. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22165. cli.set_proxy_basic_auth("u", "p");
  22166. cli.set_no_proxy({"127.0.0.1"});
  22167. cli.set_follow_location(true);
  22168. auto res = cli.Get("/redir");
  22169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22170. EXPECT_GE(proxy_hits.load(), 1);
  22171. EXPECT_GE(target_hits.load(), 1);
  22172. EXPECT_FALSE(target_saw_authz.load());
  22173. }
  22174. #ifdef CPPHTTPLIB_SSL_ENABLED
  22175. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  22176. // Direct origin replying 407 must not trigger the digest retry; otherwise
  22177. // proxy creds would be sent to the (possibly hostile) origin.
  22178. std::atomic<int> target_hits{0};
  22179. std::atomic<bool> target_saw_proxy_authz{false};
  22180. no_proxy_test::ScopedServer target;
  22181. target.svr().Get(".*", [&](const Request &req, Response &res) {
  22182. target_hits++;
  22183. if (req.has_header("Proxy-Authorization")) {
  22184. target_saw_proxy_authz = true;
  22185. }
  22186. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22187. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  22188. "nonce=\"abc\", algorithm=MD5");
  22189. });
  22190. target.listen();
  22191. // The proxy address is set to the target's port: the bypass MUST kick in;
  22192. // if it doesn't, the test still routes "via proxy" to the same server and
  22193. // the Proxy-Authorization assertion below catches the leak.
  22194. Client cli("evil.example", target.port());
  22195. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  22196. cli.set_proxy("127.0.0.1", target.port());
  22197. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22198. cli.set_no_proxy({"evil.example"});
  22199. auto res = cli.Get("/x");
  22200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22201. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22202. EXPECT_EQ(1, target_hits.load());
  22203. EXPECT_FALSE(target_saw_proxy_authz.load());
  22204. }
  22205. #endif
  22206. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  22207. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  22208. std::atomic<int> proxy_hits{0};
  22209. std::atomic<int> bypass_hits{0};
  22210. std::atomic<bool> proxy_saw_c_url{false};
  22211. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  22212. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  22213. proxy_hits++;
  22214. if (req.path.find("/start") != std::string::npos) {
  22215. res.status = 302;
  22216. res.set_header("Location", "http://127.0.0.1:" +
  22217. std::to_string(bypass_server.port()) +
  22218. "/middle");
  22219. return;
  22220. }
  22221. if (req.path.find("/end") != std::string::npos) {
  22222. proxy_saw_c_url = true;
  22223. res.set_content("c-via-proxy", "text/plain");
  22224. return;
  22225. }
  22226. res.set_content("unexpected", "text/plain");
  22227. });
  22228. // public.example's "advertised" port is arbitrary (the request never lands
  22229. // there — it goes through the proxy), but use a dynamic value to stay
  22230. // friendly with sharded parallel runs.
  22231. int public_port = bypass_server.port();
  22232. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  22233. bypass_hits++;
  22234. res.status = 302;
  22235. res.set_header("Location", "http://public.example:" +
  22236. std::to_string(public_port) + "/end");
  22237. });
  22238. proxy_mock.listen();
  22239. bypass_server.listen();
  22240. Client cli("public.example", public_port);
  22241. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22242. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22243. cli.set_no_proxy({"127.0.0.1"});
  22244. cli.set_follow_location(true);
  22245. auto res = cli.Get("/start");
  22246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22247. EXPECT_EQ(StatusCode::OK_200, res->status);
  22248. EXPECT_EQ("c-via-proxy", res->body);
  22249. EXPECT_GE(proxy_hits.load(), 2);
  22250. EXPECT_GE(bypass_hits.load(), 1);
  22251. EXPECT_TRUE(proxy_saw_c_url.load());
  22252. }
  22253. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  22254. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  22255. // request reconnects to the correct endpoint.
  22256. std::atomic<int> proxy_hits{0};
  22257. std::atomic<int> target_hits{0};
  22258. no_proxy_test::ScopedServer proxy_mock, target;
  22259. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  22260. proxy_hits++;
  22261. res.set_content("via-proxy", "text/plain");
  22262. });
  22263. target.svr().Get(".*", [&](const Request &, Response &res) {
  22264. target_hits++;
  22265. res.set_content("direct", "text/plain");
  22266. });
  22267. proxy_mock.listen();
  22268. target.listen();
  22269. Client cli("public.example", target.port());
  22270. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22271. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22272. cli.set_keep_alive(true);
  22273. auto res1 = cli.Get("/a");
  22274. ASSERT_TRUE(res1);
  22275. EXPECT_EQ("via-proxy", res1->body);
  22276. EXPECT_EQ(1, proxy_hits.load());
  22277. EXPECT_EQ(0, target_hits.load());
  22278. cli.set_no_proxy({"public.example"});
  22279. auto res2 = cli.Get("/b");
  22280. ASSERT_TRUE(res2);
  22281. EXPECT_EQ("direct", res2->body);
  22282. EXPECT_EQ(1, proxy_hits.load());
  22283. EXPECT_EQ(1, target_hits.load());
  22284. }
  22285. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  22286. namespace proxy_tunnel_test {
  22287. // SSLServer counterpart to no_proxy_test::ScopedServer.
  22288. class ScopedSSLServer {
  22289. public:
  22290. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  22291. port_ = svr_.bind_to_any_port("127.0.0.1");
  22292. }
  22293. ~ScopedSSLServer() {
  22294. svr_.stop();
  22295. if (th_.joinable()) { th_.join(); }
  22296. }
  22297. SSLServer &svr() { return svr_; }
  22298. int port() const { return port_; }
  22299. void listen() {
  22300. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22301. svr_.wait_until_ready();
  22302. }
  22303. private:
  22304. SSLServer svr_;
  22305. std::thread th_;
  22306. int port_ = 0;
  22307. };
  22308. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  22309. class ScopedConnectProxy {
  22310. public:
  22311. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  22312. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  22313. if (listen_fd_ < 0) { return; }
  22314. int yes = 1;
  22315. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  22316. sockaddr_in a{};
  22317. a.sin_family = AF_INET;
  22318. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  22319. a.sin_port = 0;
  22320. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  22321. return;
  22322. }
  22323. socklen_t alen = sizeof(a);
  22324. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  22325. 0) {
  22326. return;
  22327. }
  22328. port_ = ntohs(a.sin_port);
  22329. if (::listen(listen_fd_, 1) != 0) { return; }
  22330. th_ = std::thread([this] { run(); });
  22331. }
  22332. ~ScopedConnectProxy() {
  22333. stop_ = true;
  22334. if (listen_fd_ >= 0) {
  22335. ::shutdown(listen_fd_, SHUT_RDWR);
  22336. ::close(listen_fd_);
  22337. }
  22338. if (th_.joinable()) { th_.join(); }
  22339. }
  22340. int port() const { return port_; }
  22341. int connect_hits() const { return connect_hits_.load(); }
  22342. // Head of the last CONNECT request, as the proxy saw it on the wire.
  22343. std::string connect_request() const {
  22344. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  22345. return connect_request_;
  22346. }
  22347. private:
  22348. void run() {
  22349. while (!stop_.load()) {
  22350. fd_set rfds;
  22351. FD_ZERO(&rfds);
  22352. FD_SET(listen_fd_, &rfds);
  22353. timeval tv{0, 100 * 1000};
  22354. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  22355. if (sel <= 0) { continue; }
  22356. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  22357. if (client_fd < 0) { continue; }
  22358. std::string req;
  22359. char buf[2048];
  22360. while (req.find("\r\n\r\n") == std::string::npos) {
  22361. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  22362. if (n <= 0) { break; }
  22363. req.append(buf, static_cast<size_t>(n));
  22364. }
  22365. if (req.compare(0, 7, "CONNECT") != 0) {
  22366. ::close(client_fd);
  22367. continue;
  22368. }
  22369. connect_hits_++;
  22370. {
  22371. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  22372. connect_request_ = req;
  22373. }
  22374. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  22375. ::send(client_fd, ok, std::strlen(ok), 0);
  22376. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  22377. sockaddr_in o{};
  22378. o.sin_family = AF_INET;
  22379. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  22380. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  22381. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  22382. 0) {
  22383. ::close(client_fd);
  22384. ::close(origin_fd);
  22385. continue;
  22386. }
  22387. auto forward = [](int from, int to) {
  22388. char b[8192];
  22389. for (;;) {
  22390. ssize_t n = ::recv(from, b, sizeof(b), 0);
  22391. if (n <= 0) { break; }
  22392. ssize_t off = 0;
  22393. while (off < n) {
  22394. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  22395. if (s <= 0) {
  22396. off = n;
  22397. break;
  22398. }
  22399. off += s;
  22400. }
  22401. }
  22402. ::shutdown(to, SHUT_WR);
  22403. };
  22404. std::thread t1([&] { forward(client_fd, origin_fd); });
  22405. std::thread t2([&] { forward(origin_fd, client_fd); });
  22406. t1.join();
  22407. t2.join();
  22408. ::close(client_fd);
  22409. ::close(origin_fd);
  22410. }
  22411. }
  22412. int forward_port_ = -1;
  22413. int listen_fd_ = -1;
  22414. int port_ = 0;
  22415. std::thread th_;
  22416. std::atomic<bool> stop_{false};
  22417. std::atomic<int> connect_hits_{0};
  22418. mutable std::mutex connect_request_mutex_;
  22419. std::string connect_request_;
  22420. };
  22421. // Sends one request through the CONNECT proxy to the TLS origin with a
  22422. // credential configured for each hop, and checks that each credential reaches
  22423. // only the hop it was configured for: the proxy's on the CONNECT request, the
  22424. // origin's (every header in origin_headers) on the tunnelled request.
  22425. void CredentialsStayWithTheirHop(
  22426. const std::function<void(SSLClient &)> &set_credentials,
  22427. const std::string &scheme,
  22428. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  22429. std::atomic<int> origin_hits{0};
  22430. std::atomic<bool> origin_saw_proxy_authz{false};
  22431. std::atomic<bool> origin_saw_headers{false};
  22432. ScopedSSLServer origin;
  22433. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22434. origin_hits++;
  22435. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  22436. origin_saw_headers =
  22437. std::all_of(origin_headers.begin(), origin_headers.end(),
  22438. [&](const std::string &h) { return req.has_header(h); });
  22439. res.set_content("ok", "text/plain");
  22440. });
  22441. origin.listen();
  22442. ScopedConnectProxy proxy(origin.port());
  22443. ASSERT_NE(0, proxy.port());
  22444. // Pinned to 127.0.0.1 for the same reason as the test below.
  22445. SSLClient cli("127.0.0.1", origin.port());
  22446. cli.enable_server_certificate_verification(false);
  22447. cli.set_proxy("127.0.0.1", proxy.port());
  22448. set_credentials(cli);
  22449. auto res = cli.Get("/x");
  22450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22451. EXPECT_EQ(StatusCode::OK_200, res->status);
  22452. EXPECT_EQ(1, origin_hits.load());
  22453. EXPECT_EQ(1, proxy.connect_hits());
  22454. EXPECT_TRUE(origin_saw_headers.load());
  22455. EXPECT_FALSE(origin_saw_proxy_authz.load())
  22456. << "Proxy-Authorization must not be sent inside the tunnel";
  22457. auto connect_req = proxy.connect_request();
  22458. EXPECT_NE(std::string::npos,
  22459. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  22460. for (const auto &h : origin_headers) {
  22461. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  22462. << h << " must not be sent to the proxy on CONNECT";
  22463. }
  22464. }
  22465. } // namespace proxy_tunnel_test
  22466. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  22467. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22468. [](SSLClient &cli) {
  22469. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22470. cli.set_basic_auth("origin-user", "origin-pass");
  22471. },
  22472. "Basic");
  22473. }
  22474. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  22475. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22476. [](SSLClient &cli) {
  22477. cli.set_proxy_bearer_token_auth("proxy-token");
  22478. cli.set_bearer_token_auth("origin-token");
  22479. },
  22480. "Bearer");
  22481. }
  22482. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  22483. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22484. [](SSLClient &cli) {
  22485. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22486. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  22487. {"Cookie", "sid=origin-session"},
  22488. {"X-Api-Key", "origin-key"}});
  22489. },
  22490. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  22491. }
  22492. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  22493. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  22494. // retry; otherwise proxy creds would be sent to the origin.
  22495. std::atomic<int> origin_hits{0};
  22496. std::atomic<bool> origin_saw_proxy_authz{false};
  22497. proxy_tunnel_test::ScopedSSLServer origin;
  22498. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22499. origin_hits++;
  22500. if (req.has_header("Proxy-Authorization")) {
  22501. origin_saw_proxy_authz = true;
  22502. }
  22503. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22504. res.set_header("Proxy-Authenticate",
  22505. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  22506. "algorithm=MD5");
  22507. });
  22508. origin.listen();
  22509. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  22510. ASSERT_NE(0, proxy.port());
  22511. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  22512. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  22513. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  22514. // and answer with its own status, making this test flaky.
  22515. SSLClient cli("127.0.0.1", origin.port());
  22516. cli.enable_server_certificate_verification(false);
  22517. cli.set_proxy("127.0.0.1", proxy.port());
  22518. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22519. auto res = cli.Get("/x");
  22520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22521. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22522. EXPECT_EQ(1, origin_hits.load());
  22523. EXPECT_FALSE(origin_saw_proxy_authz.load());
  22524. EXPECT_EQ(1, proxy.connect_hits());
  22525. }
  22526. #endif