test.cc 936 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definition is linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. } // namespace tls
  68. } // namespace httplib
  69. #endif
  70. using namespace std;
  71. using namespace httplib;
  72. const char *HOST = "localhost";
  73. static int get_base_port() {
  74. const char *shard = getenv("GTEST_SHARD_INDEX");
  75. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  76. }
  77. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  78. // New standalone tests MUST use svr.bind_to_any_port() instead.
  79. const int PORT = get_base_port();
  80. const string LONG_QUERY_VALUE = string(25000, '@');
  81. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  82. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  83. const string TOO_LONG_QUERY_URL =
  84. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  85. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  86. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  87. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  88. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  89. return file.name == key;
  90. });
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return *it;
  93. #else
  94. if (it != items.end()) { return *it; }
  95. throw std::runtime_error("invalid multipart form data name error");
  96. #endif
  97. }
  98. static void read_file(const std::string &path, std::string &out) {
  99. std::ifstream fs(path, std::ios_base::binary);
  100. if (!fs) {
  101. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  102. return;
  103. #else
  104. throw std::runtime_error("File not found: " + path);
  105. #endif
  106. }
  107. fs.seekg(0, std::ios_base::end);
  108. auto size = fs.tellg();
  109. fs.seekg(0);
  110. out.resize(static_cast<size_t>(size));
  111. fs.read(&out[0], static_cast<std::streamsize>(size));
  112. }
  113. class UnixSocketTest : public ::testing::Test {
  114. protected:
  115. void TearDown() override { std::remove(pathname_.c_str()); }
  116. void client_GET(const std::string &addr) {
  117. httplib::Client cli{addr};
  118. cli.set_address_family(AF_UNIX);
  119. ASSERT_TRUE(cli.is_valid());
  120. const auto &result = cli.Get(pattern_);
  121. ASSERT_TRUE(result) << "error: " << result.error();
  122. const auto &resp = result.value();
  123. EXPECT_EQ(resp.status, StatusCode::OK_200);
  124. EXPECT_EQ(resp.body, content_);
  125. }
  126. static std::string make_sock_path() {
  127. const char *shard = getenv("GTEST_SHARD_INDEX");
  128. return shard ? std::string("./httplib-server-") + shard + ".sock"
  129. : "./httplib-server.sock";
  130. }
  131. const std::string pathname_{make_sock_path()};
  132. const std::string pattern_{"/hi"};
  133. const std::string content_{"Hello World!"};
  134. };
  135. TEST_F(UnixSocketTest, pathname) {
  136. httplib::Server svr;
  137. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  138. res.set_content(content_, "text/plain");
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. }
  152. #if defined(__linux__) || \
  153. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  154. TEST_F(UnixSocketTest, PeerPid) {
  155. httplib::Server svr;
  156. std::string remote_port_val;
  157. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. remote_port_val = std::to_string(req.remote_port);
  160. });
  161. std::thread t{[&] {
  162. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  163. }};
  164. auto se = detail::scope_exit([&] {
  165. svr.stop();
  166. t.join();
  167. ASSERT_FALSE(svr.is_running());
  168. });
  169. svr.wait_until_ready();
  170. ASSERT_TRUE(svr.is_running());
  171. client_GET(pathname_);
  172. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  173. }
  174. #endif
  175. #ifdef __linux__
  176. TEST_F(UnixSocketTest, abstract) {
  177. constexpr char svr_path[]{"\x00httplib-server.sock"};
  178. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  179. httplib::Server svr;
  180. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  181. res.set_content(content_, "text/plain");
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(abstract_addr);
  194. }
  195. #endif
  196. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  197. httplib::Server svr;
  198. std::string received_host_header;
  199. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  200. // Capture the Host header sent by the client
  201. auto host_iter = req.headers.find("Host");
  202. if (host_iter != req.headers.end()) {
  203. received_host_header = host_iter->second;
  204. }
  205. res.set_content(content_, "text/plain");
  206. });
  207. std::thread t{[&] {
  208. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  209. }};
  210. auto se = detail::scope_exit([&] {
  211. svr.stop();
  212. t.join();
  213. ASSERT_FALSE(svr.is_running());
  214. });
  215. svr.wait_until_ready();
  216. ASSERT_TRUE(svr.is_running());
  217. // Test that Host header is automatically set to "localhost" for Unix socket
  218. // connections
  219. httplib::Client cli{pathname_};
  220. cli.set_address_family(AF_UNIX);
  221. ASSERT_TRUE(cli.is_valid());
  222. const auto &result = cli.Get(pattern_);
  223. ASSERT_TRUE(result) << "error: " << result.error();
  224. const auto &resp = result.value();
  225. EXPECT_EQ(resp.status, StatusCode::OK_200);
  226. EXPECT_EQ(resp.body, content_);
  227. // Verify that Host header was automatically set to "localhost"
  228. EXPECT_EQ(received_host_header, "localhost");
  229. }
  230. #ifndef _WIN32
  231. TEST(SocketStream, wait_writable_UNIX) {
  232. int fds[2];
  233. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  234. const auto asSocketStream = [&](socket_t fd,
  235. std::function<bool(Stream &)> func) {
  236. return detail::process_client_socket(
  237. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  238. };
  239. asSocketStream(fds[0], [&](Stream &s0) {
  240. EXPECT_EQ(s0.socket(), fds[0]);
  241. EXPECT_TRUE(s0.wait_writable());
  242. EXPECT_TRUE(s0.is_peer_alive());
  243. EXPECT_EQ(0, close(fds[1]));
  244. EXPECT_FALSE(s0.is_peer_alive());
  245. return true;
  246. });
  247. EXPECT_EQ(0, close(fds[0]));
  248. }
  249. TEST(SocketStream, wait_writable_INET) {
  250. sockaddr_in addr;
  251. memset(&addr, 0, sizeof(addr));
  252. addr.sin_family = AF_INET;
  253. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  254. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  255. int disconnected_svr_sock = -1;
  256. std::thread svr{[&] {
  257. const int s = socket(AF_INET, SOCK_STREAM, 0);
  258. ASSERT_LE(0, s);
  259. // PORT + 1 is shared with the SSL redirect tests and with
  260. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  261. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  262. // because that happens on a worker thread the ASSERT does not stop the
  263. // test: it runs on and fails at the disconnected_svr_sock check instead.
  264. default_socket_options(s);
  265. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  266. ASSERT_EQ(0, listen(s, 1));
  267. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  268. ASSERT_EQ(0, close(s));
  269. }};
  270. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  271. std::thread cli{[&] {
  272. const int s = socket(AF_INET, SOCK_STREAM, 0);
  273. ASSERT_LE(0, s);
  274. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  275. ASSERT_EQ(0, close(s));
  276. }};
  277. cli.join();
  278. svr.join();
  279. ASSERT_NE(disconnected_svr_sock, -1);
  280. const auto asSocketStream = [&](socket_t fd,
  281. std::function<bool(Stream &)> func) {
  282. return detail::process_client_socket(
  283. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  284. };
  285. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  286. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  287. // wait_writable() returns true because select_write() only checks if the
  288. // send buffer has space. Peer disconnection is detected later by send().
  289. EXPECT_TRUE(ss.wait_writable());
  290. return true;
  291. });
  292. ASSERT_EQ(0, close(disconnected_svr_sock));
  293. }
  294. #endif // #ifndef _WIN32
  295. TEST(SetSocketOptTest, TcpNoDelay) {
  296. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  297. ASSERT_NE(sock, INVALID_SOCKET);
  298. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  299. int val = 0;
  300. socklen_t len = sizeof(val);
  301. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  302. reinterpret_cast<char *>(&val), &len));
  303. EXPECT_NE(val, 0);
  304. detail::close_socket(sock);
  305. }
  306. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  307. // accept() reports failures through WSAGetLastError() on Windows and through
  308. // errno everywhere else. Asking the wrong one is what made the accept loop
  309. // treat every recoverable failure as fatal on Windows.
  310. struct Classification {
  311. bool resource;
  312. bool transient;
  313. };
  314. auto classify = [](int err) {
  315. #ifdef _WIN32
  316. WSASetLastError(err);
  317. #else
  318. errno = err;
  319. #endif
  320. // Read both before asserting: an assertion may clobber the error slot.
  321. Classification c;
  322. c.resource = detail::is_accept_resource_error();
  323. c.transient = detail::is_accept_transient_error();
  324. return c;
  325. };
  326. #ifdef _WIN32
  327. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  328. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  329. WSAECONNRESET, WSAECONNABORTED};
  330. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  331. #else
  332. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  333. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  334. ECONNABORTED};
  335. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  336. #endif
  337. for (auto err : resource_errors) {
  338. const auto c = classify(err);
  339. EXPECT_TRUE(c.resource) << "error " << err;
  340. EXPECT_FALSE(c.transient) << "error " << err;
  341. }
  342. for (auto err : transient_errors) {
  343. const auto c = classify(err);
  344. EXPECT_TRUE(c.transient) << "error " << err;
  345. EXPECT_FALSE(c.resource) << "error " << err;
  346. }
  347. for (auto err : fatal_errors) {
  348. const auto c = classify(err);
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. EXPECT_FALSE(c.transient) << "error " << err;
  351. }
  352. #ifdef _WIN32
  353. WSASetLastError(0);
  354. #else
  355. errno = 0;
  356. #endif
  357. }
  358. TEST(ClientTest, MoveConstructible) {
  359. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  360. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  361. }
  362. TEST(ClientTest, MoveAssignable) {
  363. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  365. }
  366. #ifdef _WIN32
  367. TEST(StartupTest, WSAStartup) {
  368. WSADATA wsaData;
  369. int ret = WSAStartup(0x0002, &wsaData);
  370. ASSERT_EQ(0, ret);
  371. }
  372. #endif
  373. TEST(DecodePathTest, PercentCharacter) {
  374. EXPECT_EQ(
  375. decode_path_component(
  376. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  377. U8("descrip=Gastos áéíóúñÑ 6"));
  378. }
  379. TEST(DecodePathTest, PercentCharacterNUL) {
  380. string expected;
  381. expected.push_back('x');
  382. expected.push_back('\0');
  383. expected.push_back('x');
  384. EXPECT_EQ(decode_path_component("x%00x"), expected);
  385. }
  386. TEST(DecodePathTest, UnicodeEncoding) {
  387. // %u0041 = 'A' (1-byte UTF-8)
  388. EXPECT_EQ("A", decode_path_component("%u0041"));
  389. // %u00E9 = 'é' (2-byte UTF-8)
  390. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  391. // %u3042 = 'あ' (3-byte UTF-8)
  392. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  393. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  394. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  395. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  396. // neighbours)
  397. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  398. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  399. }
  400. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  401. // A sign or whitespace inside the two-character escape window must not be
  402. // accepted as a valid percent-encoding; the sequence is passed through
  403. // literally, matching decode_uri_component / decode_path_component.
  404. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  405. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  406. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  407. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  408. // Well-formed escapes still decode.
  409. EXPECT_EQ("-", decode_query_component("%2D", false));
  410. EXPECT_EQ("A", decode_query_component("%41", false));
  411. }
  412. TEST(SanitizeFilenameTest, VariousPatterns) {
  413. // Path traversal
  414. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  415. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  416. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  417. // Normal and edge cases
  418. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  419. EXPECT_EQ("filename.txt",
  420. httplib::sanitize_filename("/path/to/filename.txt"));
  421. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  422. EXPECT_EQ("", httplib::sanitize_filename(".."));
  423. EXPECT_EQ("", httplib::sanitize_filename(""));
  424. // Null bytes stripped
  425. EXPECT_EQ("safe.txt",
  426. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  427. // Whitespace-only rejected
  428. EXPECT_EQ("", httplib::sanitize_filename(" "));
  429. }
  430. // Forward declaration (see the base64_encode note below): split builds move the
  431. // definition into httplib.cc, so re-declaring it here lets the test link.
  432. namespace httplib {
  433. namespace detail {
  434. bool is_chunked_transfer_encoding(const Headers &headers);
  435. } // namespace detail
  436. } // namespace httplib
  437. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  438. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  439. auto make = [](std::initializer_list<const char *> lines) {
  440. Headers h;
  441. for (auto te : lines) {
  442. if (te) { h.emplace("Transfer-Encoding", te); }
  443. }
  444. return h;
  445. };
  446. // Sole coding, matched case-insensitively.
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  450. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  454. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  457. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  458. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  459. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  460. // were received, into one list. Headers preserves that order, so the answer
  461. // is decided by the last coding of the last line and the order the lines
  462. // arrived in is significant.
  463. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  464. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  465. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  466. // The split can fall anywhere in the list.
  467. EXPECT_TRUE(
  468. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  469. EXPECT_FALSE(
  470. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  471. // A trailing line naming no coding leaves the list ending in nothing, so it
  472. // must not inherit the chunked from the line before it.
  473. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  474. }
  475. // Forward declarations (see the base64_encode note below).
  476. namespace httplib {
  477. namespace detail {
  478. bool parse_status_line(const char *line, std::string &version, int &status,
  479. std::string &reason);
  480. std::string file_extension(const std::string &path);
  481. std::string
  482. find_content_type(const std::string &path,
  483. const std::map<std::string, std::string> &user_data,
  484. const std::string &default_content_type);
  485. bool can_compress_content_type(const std::string &content_type);
  486. bool is_prohibited_header_name(const std::string &name);
  487. #ifdef CPPHTTPLIB_SSL_ENABLED
  488. bool match_hostname(const std::string &pattern, const std::string &hostname);
  489. #endif
  490. } // namespace detail
  491. } // namespace httplib
  492. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  493. struct {
  494. const char *line;
  495. const char *version;
  496. int status;
  497. const char *reason;
  498. } cases[] = {
  499. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  500. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  501. // The reason phrase may be empty, or left out along with its space.
  502. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  503. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  504. };
  505. for (const auto &c : cases) {
  506. std::string version;
  507. int status = 0;
  508. std::string reason = "unset";
  509. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  510. << c.line;
  511. EXPECT_EQ(c.version, version);
  512. EXPECT_EQ(c.status, status);
  513. EXPECT_EQ(c.reason, reason);
  514. }
  515. }
  516. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  517. const char *lines[] = {
  518. "HTTP/2 200 OK\r\n",
  519. "HTTP/1.2 200 OK\r\n",
  520. "HTTP/1.1 20 OK\r\n",
  521. "HTTP/1.1 2000 OK\r\n",
  522. "HTTP/1.1 2x0 OK\r\n",
  523. "HTTP/1.1 200 OK\r\n",
  524. "HTTP/1.1 200OK\r\n",
  525. "HTTP/1.1 200 O\rK\r\n",
  526. "HTTP/1.1 200 OK",
  527. "HTTP/1.1 200 OK\r\nX",
  528. "",
  529. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  530. "HTTP/1.1 200 OK\n",
  531. #endif
  532. };
  533. for (auto line : lines) {
  534. std::string version;
  535. int status = 0;
  536. std::string reason;
  537. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  538. << line;
  539. }
  540. }
  541. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  542. // Long enough to overflow the stack when matched with std::regex.
  543. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  544. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  545. std::string version;
  546. int status = 0;
  547. std::string reason;
  548. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  549. EXPECT_EQ(200, status);
  550. EXPECT_EQ(long_reason, reason);
  551. }
  552. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  553. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  554. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  555. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  556. EXPECT_EQ("", detail::file_extension("noext"));
  557. EXPECT_EQ("", detail::file_extension("a."));
  558. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  559. EXPECT_EQ("", detail::file_extension("a.b-c"));
  560. // Long enough to overflow the stack when matched with std::regex.
  561. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  562. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  563. }
  564. #ifdef CPPHTTPLIB_SSL_ENABLED
  565. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  566. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  567. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  568. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  569. // A wildcard needs two labels after it, in the leftmost label only
  570. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  571. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  572. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  573. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  574. EXPECT_FALSE(
  575. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  576. // No name may have an empty label
  577. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  578. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  579. }
  580. #endif
  581. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  582. detail::case_ignore::hash hash;
  583. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  584. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  585. // Long enough to overflow the stack if hashed one call per character.
  586. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  587. }
  588. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  589. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  590. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  591. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  592. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  593. // Same 26-bit hash as html, svg and js.
  594. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  595. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  596. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  597. }
  598. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  599. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  600. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  601. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  602. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  603. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  604. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  605. // Same 26-bit hash as application/json.
  606. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  607. }
  608. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  609. Request req;
  610. req.set_header("Content-Type", "Multipart/Form-Data; boundary=x");
  611. EXPECT_TRUE(req.is_multipart_form_data());
  612. }
  613. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  614. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  615. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  616. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  617. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  618. // Same 26-bit hash as REMOTE_ADDR.
  619. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  620. }
  621. // Forward declaration: in split builds split.py strips `inline` and moves the
  622. // definition into httplib.cc, so detail::base64_encode is not visible from the
  623. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  624. // in both header-only and split builds.
  625. namespace httplib {
  626. namespace detail {
  627. std::string base64_encode(const std::string &in);
  628. } // namespace detail
  629. } // namespace httplib
  630. TEST(Base64EncodeTest, KnownAnswers) {
  631. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  632. // where the accumulator's top bit is already set before the next shift.
  633. EXPECT_EQ("", detail::base64_encode(""));
  634. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  635. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  636. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  637. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  638. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  639. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  640. // High bytes keep the top bit set across several rounds.
  641. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  642. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  643. }
  644. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  645. string unescapedCharacters = "-_.!~*'()";
  646. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  647. }
  648. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  649. string reservedCharacters = ";,/?:@&=+$";
  650. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  651. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  652. }
  653. TEST(ClientQueryOrder, PreserveOrder) {
  654. // This test reproduces Issue #2259: client may reorder query parameters
  655. // when sending a GET request. The expected behavior is that the client
  656. // preserves the original query string order when the caller supplied it
  657. // as part of the path.
  658. Server svr;
  659. svr.Get("/", [&](const Request &req, Response &res) {
  660. // Echo back the raw target so the test can assert ordering
  661. res.set_content(req.target, "text/plain");
  662. });
  663. std::thread t{[&] { svr.listen(HOST, PORT); }};
  664. auto se = detail::scope_exit([&] {
  665. svr.stop();
  666. t.join();
  667. ASSERT_FALSE(svr.is_running());
  668. });
  669. svr.wait_until_ready();
  670. Client cli(HOST, PORT);
  671. ASSERT_TRUE(cli.is_valid());
  672. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  673. auto res = cli.Get(original);
  674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  675. // Expect the echoed target to exactly match the original path (order
  676. // preserved)
  677. EXPECT_EQ(res->body, original);
  678. }
  679. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  680. string chineseCharacters = U8("中国語");
  681. string russianCharacters = U8("дом");
  682. string brazilianCharacters = U8("óculos");
  683. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  684. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  685. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  686. "%D0%B4%D0%BE%D0%BC");
  687. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  688. }
  689. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  690. string unescapedCharacters = "-_.!~*'()";
  691. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  692. }
  693. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  694. string reservedCharacters = ";,/?:@&=+$";
  695. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  696. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  697. }
  698. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  699. string chineseCharacters = U8("中国語");
  700. string russianCharacters = U8("дом");
  701. string brazilianCharacters = U8("óculos");
  702. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  703. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  704. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  705. "%D0%B4%D0%BE%D0%BC");
  706. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  707. }
  708. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  709. // Issue #2082 use case: encoding path component with ampersand
  710. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  711. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  712. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  713. }
  714. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  715. string unescapedCharacters = "-_.!~*'()";
  716. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  717. }
  718. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  719. string reservedCharacters = ";,/?:@&=+$#";
  720. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  721. }
  722. TEST(EncodeUriTest, TestUTF8Characters) {
  723. string chineseCharacters = U8("中国語");
  724. string russianCharacters = U8("дом");
  725. string brazilianCharacters = U8("óculos");
  726. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  727. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  728. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  729. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  730. }
  731. TEST(EncodeUriTest, TestCompleteUri) {
  732. string uri =
  733. "https://example.com/path/to/resource?query=value&param=test#fragment";
  734. EXPECT_EQ(
  735. httplib::encode_uri(uri),
  736. "https://example.com/path/to/resource?query=value&param=test#fragment");
  737. }
  738. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  739. string uri =
  740. "https://example.com/path with spaces/file name.html?q=hello world";
  741. EXPECT_EQ(httplib::encode_uri(uri),
  742. "https://example.com/path%20with%20spaces/"
  743. "file%20name.html?q=hello%20world");
  744. }
  745. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  746. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  747. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  748. }
  749. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  750. string unescapedCharacters = "-_.!~*'()";
  751. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  752. }
  753. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  754. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  755. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  756. string encodedBrazilian = "%C3%B3culos";
  757. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  758. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  759. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  760. }
  761. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  762. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  763. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  764. "Piri Tommy Villiers - on & on");
  765. }
  766. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  767. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  768. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  769. }
  770. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  771. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  772. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  773. }
  774. TEST(DecodeUriTest, TestUTF8Characters) {
  775. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  776. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  777. string encodedBrazilian = "%C3%B3culos";
  778. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  779. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  780. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  781. }
  782. TEST(DecodeUriTest, TestCompleteUri) {
  783. string encodedUri = "https://example.com/path%20with%20spaces/"
  784. "file%20name.html?q=hello%20world";
  785. EXPECT_EQ(
  786. httplib::decode_uri(encodedUri),
  787. "https://example.com/path with spaces/file name.html?q=hello world");
  788. }
  789. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  790. string original =
  791. "https://example.com/path with spaces/file name.html?q=hello world";
  792. string encoded = httplib::encode_uri(original);
  793. string decoded = httplib::decode_uri(encoded);
  794. EXPECT_EQ(decoded, original);
  795. }
  796. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  797. // decode_uri is the inverse of encode_uri: an escaped reserved character
  798. // stays encoded so it is not promoted into a real delimiter, while
  799. // non-reserved escapes still decode (like JS decodeURI).
  800. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  801. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  802. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  803. "%3F%3A%40%26%3D%2B%24%2C%3B");
  804. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  805. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  806. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  807. "http://example.com/a%2Fb");
  808. // decode_uri_component still decodes the reserved character.
  809. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  810. }
  811. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  812. string original = "Piri Tommy Villiers - on & on";
  813. string encoded = httplib::encode_uri_component(original);
  814. string decoded = httplib::decode_uri_component(encoded);
  815. EXPECT_EQ(decoded, original);
  816. }
  817. TEST(TrimTests, TrimStringTests) {
  818. EXPECT_EQ("abc", detail::trim_copy("abc"));
  819. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  820. EXPECT_TRUE(detail::trim_copy("").empty());
  821. }
  822. TEST(AsciiTest, LocaleIndependentClassification) {
  823. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  824. // which consult the global C locale: std::isalnum(0xC5) can return true
  825. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  826. // helpers must classify every byte by the ASCII grammar alone.
  827. for (int i = 0; i < 256; i++) {
  828. auto c = static_cast<char>(i);
  829. auto is_digit = i >= '0' && i <= '9';
  830. auto is_upper = i >= 'A' && i <= 'Z';
  831. auto is_lower = i >= 'a' && i <= 'z';
  832. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  833. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  834. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  835. << "byte " << i;
  836. }
  837. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  838. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  839. // Non-ASCII bytes must be percent-encoded, never passed through as
  840. // alphanumeric.
  841. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  842. }
  843. TEST(FromCharsTest, Double) {
  844. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  845. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  846. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  847. auto parse = [](const std::string &s, double &v) {
  848. return detail::from_chars(s.data(), s.data() + s.size(), v);
  849. };
  850. double v = -1.0;
  851. // Representative quality values.
  852. EXPECT_EQ(parse("0", v).ec, std::errc{});
  853. EXPECT_DOUBLE_EQ(v, 0.0);
  854. EXPECT_EQ(parse("1", v).ec, std::errc{});
  855. EXPECT_DOUBLE_EQ(v, 1.0);
  856. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  857. EXPECT_DOUBLE_EQ(v, 0.8);
  858. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  859. EXPECT_DOUBLE_EQ(v, 0.001);
  860. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  861. EXPECT_DOUBLE_EQ(v, 1.0);
  862. // A missing integer or fractional part is tolerated.
  863. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  864. EXPECT_DOUBLE_EQ(v, 0.5);
  865. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  866. EXPECT_DOUBLE_EQ(v, 5.0);
  867. // Values outside [0, 1] still parse; the caller range-checks them.
  868. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  869. EXPECT_DOUBLE_EQ(v, 123.456);
  870. // Stops at the first byte that is not part of the number and reports where.
  871. std::string trailing = "0.9, text/html";
  872. auto r = parse(trailing, v);
  873. EXPECT_EQ(r.ec, std::errc{});
  874. EXPECT_DOUBLE_EQ(v, 0.9);
  875. EXPECT_EQ(*r.ptr, ',');
  876. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  877. // outright, and an 'e'/'E' simply ends the number.
  878. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  879. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  880. std::string exp_input = "1.5e3";
  881. r = parse(exp_input, v);
  882. EXPECT_EQ(r.ec, std::errc{});
  883. EXPECT_DOUBLE_EQ(v, 1.5);
  884. EXPECT_EQ(*r.ptr, 'e');
  885. // Invalid inputs.
  886. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  887. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  888. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  889. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  890. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  891. // Pathological but well-formed inputs must stay bounded (no overflow, no
  892. // out-of-bounds table access) and stay within [0, 1] for the caller.
  893. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  894. std::errc{});
  895. EXPECT_DOUBLE_EQ(v, 0.0);
  896. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  897. std::errc{});
  898. EXPECT_GE(v, 0.0);
  899. EXPECT_LE(v, 1.0);
  900. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  901. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  902. }
  903. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  904. // Simple case without quality values
  905. std::vector<std::string> result1;
  906. EXPECT_TRUE(detail::parse_accept_header(
  907. "text/html,application/json,text/plain", result1));
  908. EXPECT_EQ(result1.size(), 3U);
  909. EXPECT_EQ(result1[0], "text/html");
  910. EXPECT_EQ(result1[1], "application/json");
  911. EXPECT_EQ(result1[2], "text/plain");
  912. // With quality values
  913. std::vector<std::string> result2;
  914. EXPECT_TRUE(detail::parse_accept_header(
  915. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  916. EXPECT_EQ(result2.size(), 3U);
  917. EXPECT_EQ(result2[0], "application/json"); // highest q value
  918. EXPECT_EQ(result2[1], "text/html");
  919. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  920. }
  921. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  922. // Mixed with and without quality values
  923. std::vector<std::string> result;
  924. EXPECT_TRUE(detail::parse_accept_header(
  925. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  926. EXPECT_EQ(result.size(), 3U);
  927. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  928. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  929. EXPECT_EQ(result[2], "application/json"); // q=0.5
  930. }
  931. TEST(ParseAcceptHeaderTest, EdgeCases) {
  932. // Empty header
  933. std::vector<std::string> empty_result;
  934. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  935. EXPECT_TRUE(empty_result.empty());
  936. // Single type
  937. std::vector<std::string> single_result;
  938. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  939. EXPECT_EQ(single_result.size(), 1U);
  940. EXPECT_EQ(single_result[0], "application/json");
  941. // Wildcard types
  942. std::vector<std::string> wildcard_result;
  943. EXPECT_TRUE(detail::parse_accept_header(
  944. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  945. EXPECT_EQ(wildcard_result.size(), 3U);
  946. EXPECT_EQ(wildcard_result[0], "application/json");
  947. EXPECT_EQ(wildcard_result[1], "text/*");
  948. EXPECT_EQ(wildcard_result[2], "*/*");
  949. }
  950. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  951. // Common browser Accept header
  952. std::vector<std::string> browser_result;
  953. EXPECT_TRUE(
  954. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  955. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  956. browser_result));
  957. EXPECT_EQ(browser_result.size(), 6U);
  958. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  959. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  960. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  961. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  962. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  963. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  964. // API client header
  965. std::vector<std::string> api_result;
  966. EXPECT_TRUE(detail::parse_accept_header(
  967. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  968. api_result));
  969. EXPECT_EQ(api_result.size(), 3U);
  970. EXPECT_EQ(api_result[0], "application/json");
  971. EXPECT_EQ(api_result[1], "application/xml");
  972. EXPECT_EQ(api_result[2], "text/plain");
  973. }
  974. TEST(ParseAcceptHeaderTest, SpecialCases) {
  975. // Quality value with 3 decimal places
  976. std::vector<std::string> decimal_result;
  977. EXPECT_TRUE(detail::parse_accept_header(
  978. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  979. EXPECT_EQ(decimal_result.size(), 2U);
  980. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  981. EXPECT_EQ(decimal_result[1], "text/html");
  982. // Zero quality (should still be included but with lowest priority)
  983. std::vector<std::string> zero_q_result;
  984. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  985. zero_q_result));
  986. EXPECT_EQ(zero_q_result.size(), 2U);
  987. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  988. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  989. // No spaces around commas
  990. std::vector<std::string> no_space_result;
  991. EXPECT_TRUE(detail::parse_accept_header(
  992. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  993. no_space_result));
  994. EXPECT_EQ(no_space_result.size(), 3U);
  995. EXPECT_EQ(no_space_result[0], "text/html");
  996. EXPECT_EQ(no_space_result[1], "application/json");
  997. EXPECT_EQ(no_space_result[2], "text/plain");
  998. }
  999. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1000. // Quality values always use '.' as the decimal separator, so parsing must
  1001. // not depend on the process locale. An embedding application may have
  1002. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1003. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1004. std::string saved = cur ? cur : "C";
  1005. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1006. "fr_FR.UTF-8"};
  1007. bool switched = false;
  1008. for (const auto loc : comma_locales) {
  1009. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1010. std::localeconv()->decimal_point[0] == ',') {
  1011. switched = true;
  1012. break;
  1013. }
  1014. }
  1015. if (!switched) {
  1016. std::setlocale(LC_NUMERIC, saved.c_str());
  1017. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1018. }
  1019. // The higher-weighted type appears later in the list, so a correct parse
  1020. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1021. // sensitive parse reads both weights as 0 and leaves the original order.
  1022. std::vector<std::string> result;
  1023. EXPECT_TRUE(detail::parse_accept_header(
  1024. "application/json;q=0.1,text/html;q=0.9", result));
  1025. ASSERT_EQ(result.size(), 2U);
  1026. EXPECT_EQ(result[0], "text/html");
  1027. EXPECT_EQ(result[1], "application/json");
  1028. std::setlocale(LC_NUMERIC, saved.c_str());
  1029. }
  1030. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1031. std::vector<std::string> result;
  1032. // Invalid quality value (> 1.0)
  1033. EXPECT_FALSE(
  1034. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1035. // Invalid quality value (< 0.0)
  1036. EXPECT_FALSE(
  1037. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1038. // Invalid quality value (not a number)
  1039. EXPECT_FALSE(detail::parse_accept_header(
  1040. "text/html;q=invalid,application/json", result));
  1041. // A valid numeric prefix does not make the entire quality value valid.
  1042. EXPECT_FALSE(detail::parse_accept_header(
  1043. "text/html;q=0.5junk,application/json", result));
  1044. // Empty quality value
  1045. EXPECT_FALSE(
  1046. detail::parse_accept_header("text/html;q=,application/json", result));
  1047. // Invalid media type format (no slash and not wildcard)
  1048. EXPECT_FALSE(
  1049. detail::parse_accept_header("invalidtype,application/json", result));
  1050. // Valid cases should still work
  1051. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1052. EXPECT_EQ(result.size(), 1U);
  1053. EXPECT_EQ(result[0], "*/*");
  1054. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1055. EXPECT_EQ(result.size(), 1U);
  1056. EXPECT_EQ(result[0], "*");
  1057. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1058. EXPECT_EQ(result.size(), 1U);
  1059. EXPECT_EQ(result[0], "text/*");
  1060. }
  1061. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1062. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1063. // and must not be answered with 400 Bad Request.
  1064. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1065. struct {
  1066. const char *value;
  1067. std::vector<std::string> expected;
  1068. } cases[] = {
  1069. {",application/json", {"application/json"}},
  1070. {"text/html,", {"text/html"}},
  1071. {"text/html,,*/*", {"text/html", "*/*"}},
  1072. // An empty element may be spelled with whitespace in it
  1073. {"text/html, , application/json", {"text/html", "application/json"}},
  1074. // Nothing but empty elements is an empty list, which means the same
  1075. // thing as no Accept header at all
  1076. {",,,", {}},
  1077. // Quality values still apply across ignored empty elements
  1078. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1079. };
  1080. for (const auto &c : cases) {
  1081. std::vector<std::string> result;
  1082. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1083. << "value: " << c.value;
  1084. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1085. }
  1086. // An invalid entry is still rejected when empty elements surround it
  1087. std::vector<std::string> result;
  1088. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1089. }
  1090. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1091. // or ';' inside one does not end the list element or the parameter. Section
  1092. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1093. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1094. struct {
  1095. const char *value;
  1096. std::vector<std::string> expected;
  1097. } cases[] = {
  1098. {"text/html;profile=\"a,b\",application/json",
  1099. {"text/html", "application/json"}},
  1100. // A "q=" inside a quoted value is not the weight
  1101. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1102. {"text/html", "application/json"}},
  1103. // The weight after a quoted value still applies
  1104. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1105. {"application/json", "text/html"}},
  1106. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1107. {"application/json", "text/html"}},
  1108. {"text/html;profile=\"a\\\"b\",application/json",
  1109. {"text/html", "application/json"}},
  1110. // An escaped backslash does not escape the '"' after it
  1111. {"text/html;profile=\"a\\\\\",application/json",
  1112. {"text/html", "application/json"}},
  1113. };
  1114. for (const auto &c : cases) {
  1115. std::vector<std::string> result;
  1116. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1117. << "value: " << c.value;
  1118. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1119. }
  1120. }
  1121. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1122. Server svr;
  1123. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1124. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1125. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1126. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1127. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1128. res.set_content("ok", "text/plain");
  1129. });
  1130. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1131. EXPECT_TRUE(false);
  1132. res.set_content("bad request", "text/plain");
  1133. });
  1134. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1135. auto se = detail::scope_exit([&] {
  1136. svr.stop();
  1137. listen_thread.join();
  1138. ASSERT_FALSE(svr.is_running());
  1139. });
  1140. svr.wait_until_ready();
  1141. Client cli("localhost", PORT);
  1142. {
  1143. auto res = cli.Get(
  1144. "/accept_ok",
  1145. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1147. EXPECT_EQ(StatusCode::OK_200, res->status);
  1148. }
  1149. {
  1150. auto res = cli.Get("/accept_bad_request",
  1151. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1153. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1154. }
  1155. }
  1156. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1157. Server svr;
  1158. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1159. res.set_content("ok", "text/plain");
  1160. });
  1161. std::atomic<int> start_count{0};
  1162. std::atomic<bool> running_when_called{false};
  1163. svr.set_start_handler([&]() {
  1164. running_when_called = svr.is_running();
  1165. start_count++;
  1166. });
  1167. auto port = svr.bind_to_any_port(HOST);
  1168. std::thread t([&]() { svr.listen_after_bind(); });
  1169. auto se = detail::scope_exit([&] {
  1170. svr.stop();
  1171. t.join();
  1172. ASSERT_FALSE(svr.is_running());
  1173. });
  1174. svr.wait_until_ready();
  1175. // A successful request proves the accept loop is running, which the start
  1176. // handler precedes; so by now the handler must have run exactly once.
  1177. Client cli(HOST, port);
  1178. cli.set_connection_timeout(std::chrono::seconds(5));
  1179. auto res = cli.Get("/");
  1180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1181. EXPECT_EQ(StatusCode::OK_200, res->status);
  1182. EXPECT_EQ(1, start_count.load());
  1183. EXPECT_TRUE(running_when_called.load());
  1184. }
  1185. TEST(DivideTest, DivideStringTests) {
  1186. auto divide = [](const std::string &str, char d) {
  1187. std::string lhs;
  1188. std::string rhs;
  1189. detail::divide(str, d,
  1190. [&](const char *lhs_data, std::size_t lhs_size,
  1191. const char *rhs_data, std::size_t rhs_size) {
  1192. lhs.assign(lhs_data, lhs_size);
  1193. rhs.assign(rhs_data, rhs_size);
  1194. });
  1195. return std::make_pair(std::move(lhs), std::move(rhs));
  1196. };
  1197. {
  1198. const auto res = divide("", '=');
  1199. EXPECT_EQ(res.first, "");
  1200. EXPECT_EQ(res.second, "");
  1201. }
  1202. {
  1203. const auto res = divide("=", '=');
  1204. EXPECT_EQ(res.first, "");
  1205. EXPECT_EQ(res.second, "");
  1206. }
  1207. {
  1208. const auto res = divide(" ", '=');
  1209. EXPECT_EQ(res.first, " ");
  1210. EXPECT_EQ(res.second, "");
  1211. }
  1212. {
  1213. const auto res = divide("a", '=');
  1214. EXPECT_EQ(res.first, "a");
  1215. EXPECT_EQ(res.second, "");
  1216. }
  1217. {
  1218. const auto res = divide("a=", '=');
  1219. EXPECT_EQ(res.first, "a");
  1220. EXPECT_EQ(res.second, "");
  1221. }
  1222. {
  1223. const auto res = divide("=b", '=');
  1224. EXPECT_EQ(res.first, "");
  1225. EXPECT_EQ(res.second, "b");
  1226. }
  1227. {
  1228. const auto res = divide("a=b", '=');
  1229. EXPECT_EQ(res.first, "a");
  1230. EXPECT_EQ(res.second, "b");
  1231. }
  1232. {
  1233. const auto res = divide("a=b=", '=');
  1234. EXPECT_EQ(res.first, "a");
  1235. EXPECT_EQ(res.second, "b=");
  1236. }
  1237. {
  1238. const auto res = divide("a=b=c", '=');
  1239. EXPECT_EQ(res.first, "a");
  1240. EXPECT_EQ(res.second, "b=c");
  1241. }
  1242. }
  1243. TEST(SplitTest, ParseQueryString) {
  1244. string s = "key1=val1&key2=val2&key3=val3";
  1245. Params dic;
  1246. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1247. [&](const char *b, const char *e) {
  1248. string key, val;
  1249. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1250. if (key.empty()) {
  1251. key.assign(b2, e2);
  1252. } else {
  1253. val.assign(b2, e2);
  1254. }
  1255. });
  1256. dic.emplace(key, val);
  1257. });
  1258. EXPECT_EQ("val1", dic.find("key1")->second);
  1259. EXPECT_EQ("val2", dic.find("key2")->second);
  1260. EXPECT_EQ("val3", dic.find("key3")->second);
  1261. }
  1262. TEST(SplitTest, ParseInvalidQueryTests) {
  1263. {
  1264. string s = " ";
  1265. Params dict;
  1266. detail::parse_query_text(s, dict);
  1267. EXPECT_TRUE(dict.empty());
  1268. }
  1269. {
  1270. string s = " = =";
  1271. Params dict;
  1272. detail::parse_query_text(s, dict);
  1273. EXPECT_TRUE(dict.empty());
  1274. }
  1275. }
  1276. TEST(ParseQueryTest, ParseQueryString) {
  1277. {
  1278. std::string s = "key1=val1&key2=val2&key3=val3";
  1279. Params dic;
  1280. detail::parse_query_text(s, dic);
  1281. EXPECT_EQ("val1", dic.find("key1")->second);
  1282. EXPECT_EQ("val2", dic.find("key2")->second);
  1283. EXPECT_EQ("val3", dic.find("key3")->second);
  1284. }
  1285. {
  1286. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1287. Params dic;
  1288. detail::parse_query_text(s, dic);
  1289. EXPECT_EQ("", dic.find("key1")->second);
  1290. EXPECT_EQ("val1", dic.find("key2")->second);
  1291. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1292. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1293. }
  1294. }
  1295. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1296. Params dic;
  1297. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1298. dic.emplace("key1", "val1");
  1299. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1300. dic.emplace("key2", "val2");
  1301. dic.emplace("key3", "val3");
  1302. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1303. }
  1304. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1305. Params params;
  1306. params.emplace("a", "1");
  1307. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1308. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1309. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1310. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1311. // Long enough to overflow the stack when matched with std::regex.
  1312. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1313. EXPECT_EQ("/p?" + long_query + "&a=1",
  1314. append_query_params("/p?" + long_query, params));
  1315. }
  1316. // Joins every entry of a Headers or Params into "key=value " so a whole
  1317. // traversal can be compared in one assertion. Both are instantiations of the
  1318. // same insertion-ordered container, so one helper serves both.
  1319. template <typename Map> static std::string entries_to_string(const Map &m) {
  1320. std::string s;
  1321. for (const auto &entry : m) {
  1322. s += entry.first + "=" + entry.second + " ";
  1323. }
  1324. return s;
  1325. }
  1326. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1327. // Params used to be a std::multimap, which sorted by name and handed the
  1328. // caller's query back alphabetised. A client signing its query string could
  1329. // not reproduce the order it asked for.
  1330. Params dic;
  1331. dic.emplace("zulu", "1");
  1332. dic.emplace("alpha", "2");
  1333. dic.emplace("mike", "3");
  1334. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1335. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1336. }
  1337. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1338. Params dic;
  1339. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1340. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1341. }
  1342. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1343. Request req;
  1344. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1345. req.params);
  1346. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1347. EXPECT_EQ("first", req.get_param_value("tag"));
  1348. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1349. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1350. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1351. EXPECT_EQ("", req.get_param_value("tag", 3));
  1352. }
  1353. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1354. // Params shares its container with Headers, which matches field names
  1355. // case-insensitively. Parameter names must not pick that up.
  1356. Params dic;
  1357. dic.emplace("Key", "upper");
  1358. dic.emplace("key", "lower");
  1359. EXPECT_EQ(2U, dic.size());
  1360. EXPECT_EQ(1U, dic.count("Key"));
  1361. EXPECT_EQ(1U, dic.count("key"));
  1362. EXPECT_EQ("upper", dic.find("Key")->second);
  1363. EXPECT_EQ("lower", dic.find("key")->second);
  1364. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1365. }
  1366. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1367. Server svr;
  1368. std::string order;
  1369. svr.Get("/order", [&](const Request &req, Response &res) {
  1370. order = entries_to_string(req.params);
  1371. res.set_content("ok", "text/plain");
  1372. });
  1373. auto port = svr.bind_to_any_port(HOST);
  1374. thread t = thread([&] { svr.listen_after_bind(); });
  1375. auto se = detail::scope_exit([&] {
  1376. svr.stop();
  1377. t.join();
  1378. ASSERT_FALSE(svr.is_running());
  1379. });
  1380. svr.wait_until_ready();
  1381. Client cli(HOST, port);
  1382. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1383. ASSERT_TRUE(res);
  1384. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1385. }
  1386. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1387. Server svr;
  1388. std::string field_order, file_order;
  1389. svr.Post("/order", [&](const Request &req, Response &res) {
  1390. for (const auto &field : req.form.fields) {
  1391. field_order += field.first + "=" + field.second.content + " ";
  1392. }
  1393. for (const auto &file : req.form.files) {
  1394. file_order += file.first + "=" + file.second.filename + " ";
  1395. }
  1396. res.set_content("ok", "text/plain");
  1397. });
  1398. auto port = svr.bind_to_any_port(HOST);
  1399. thread t = thread([&] { svr.listen_after_bind(); });
  1400. auto se = detail::scope_exit([&] {
  1401. svr.stop();
  1402. t.join();
  1403. ASSERT_FALSE(svr.is_running());
  1404. });
  1405. svr.wait_until_ready();
  1406. UploadFormDataItems items = {
  1407. {"zulu", "1", "", ""},
  1408. {"alpha", "2", "", ""},
  1409. {"mike", "3", "", ""},
  1410. {"zebra", "z", "z.txt", "text/plain"},
  1411. {"apple", "a", "a.txt", "text/plain"},
  1412. };
  1413. Client cli(HOST, port);
  1414. auto res = cli.Post("/order", items);
  1415. ASSERT_TRUE(res);
  1416. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1417. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1418. }
  1419. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1420. Server svr;
  1421. std::vector<std::string> values;
  1422. std::string first, second, out_of_range, order;
  1423. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1424. values = req.form.get_fields("tag");
  1425. first = req.form.get_field("tag", 0);
  1426. second = req.form.get_field("tag", 1);
  1427. out_of_range = req.form.get_field("tag", 2);
  1428. for (const auto &field : req.form.fields) {
  1429. order += field.first + "=" + field.second.content + " ";
  1430. }
  1431. res.set_content("ok", "text/plain");
  1432. });
  1433. auto port = svr.bind_to_any_port(HOST);
  1434. thread t = thread([&] { svr.listen_after_bind(); });
  1435. auto se = detail::scope_exit([&] {
  1436. svr.stop();
  1437. t.join();
  1438. ASSERT_FALSE(svr.is_running());
  1439. });
  1440. svr.wait_until_ready();
  1441. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1442. // not adjacent in the container.
  1443. UploadFormDataItems items = {
  1444. {"tag", "first", "", ""},
  1445. {"other", "x", "", ""},
  1446. {"tag", "second", "", ""},
  1447. };
  1448. Client cli(HOST, port);
  1449. auto res = cli.Post("/repeated", items);
  1450. ASSERT_TRUE(res);
  1451. ASSERT_EQ(2U, values.size());
  1452. EXPECT_EQ("first", values[0]);
  1453. EXPECT_EQ("second", values[1]);
  1454. EXPECT_EQ("first", first);
  1455. EXPECT_EQ("second", second);
  1456. // std::multimap already kept entries sharing a name in insertion order, so
  1457. // everything above passes without this change too. The whole traversal is
  1458. // what tells the two apart: sorting by name would hoist "other" to the front
  1459. // and the two "tag" parts would end up adjacent.
  1460. EXPECT_EQ("tag=first other=x tag=second ", order);
  1461. // Advancing past the last entry of a name used to run off the container;
  1462. // the container's saturating increment makes it return the default instead.
  1463. EXPECT_EQ("", out_of_range);
  1464. }
  1465. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1466. // Server::read_content() keeps a FormFields::iterator alive across the
  1467. // content callbacks that fill the part it points at. The container is
  1468. // vector-backed, so a later emplace can reallocate and invalidate an older
  1469. // iterator; 64 parts grow the vector through seven reallocations, which
  1470. // checks that every part's content still lands in its own entry.
  1471. const size_t part_count = 64;
  1472. // One formula for both the parts sent and the values expected back, so the
  1473. // two cannot drift apart.
  1474. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1475. auto content_of = [](size_t i) {
  1476. return std::string(64, static_cast<char>('a' + (i % 26)));
  1477. };
  1478. Server svr;
  1479. std::vector<std::pair<std::string, std::string>> received;
  1480. svr.Post("/many", [&](const Request &req, Response &res) {
  1481. for (const auto &field : req.form.fields) {
  1482. received.emplace_back(field.first, field.second.content);
  1483. }
  1484. res.set_content("ok", "text/plain");
  1485. });
  1486. auto port = svr.bind_to_any_port(HOST);
  1487. thread t = thread([&] { svr.listen_after_bind(); });
  1488. auto se = detail::scope_exit([&] {
  1489. svr.stop();
  1490. t.join();
  1491. ASSERT_FALSE(svr.is_running());
  1492. });
  1493. svr.wait_until_ready();
  1494. UploadFormDataItems items;
  1495. for (size_t i = 0; i < part_count; i++) {
  1496. items.push_back({name_of(i), content_of(i), "", ""});
  1497. }
  1498. Client cli(HOST, port);
  1499. auto res = cli.Post("/many", items);
  1500. ASSERT_TRUE(res);
  1501. ASSERT_EQ(part_count, received.size());
  1502. for (size_t i = 0; i < part_count; i++) {
  1503. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1504. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1505. }
  1506. }
  1507. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1508. string content_type = "multipart/form-data; boundary=something";
  1509. string boundary;
  1510. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1511. EXPECT_TRUE(ret);
  1512. EXPECT_EQ(boundary, "something");
  1513. }
  1514. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1515. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1516. string boundary;
  1517. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1518. EXPECT_TRUE(ret);
  1519. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1520. }
  1521. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1522. string content_type =
  1523. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1524. string boundary;
  1525. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1526. EXPECT_TRUE(ret);
  1527. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1528. }
  1529. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1530. string content_type =
  1531. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1532. string boundary;
  1533. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1534. EXPECT_TRUE(ret);
  1535. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1536. }
  1537. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1538. const string boundary(70, 'a');
  1539. string content_type = "multipart/form-data; boundary=" + boundary;
  1540. string parsed;
  1541. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1542. EXPECT_TRUE(ret);
  1543. EXPECT_EQ(parsed, boundary);
  1544. }
  1545. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1546. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1547. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1548. string parsed;
  1549. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1550. EXPECT_FALSE(ret);
  1551. }
  1552. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1553. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1554. // is 72 characters on the wire and still valid.
  1555. const string boundary(70, 'a');
  1556. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1557. string parsed;
  1558. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1559. EXPECT_EQ(parsed, boundary);
  1560. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1561. parsed.clear();
  1562. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1563. }
  1564. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1565. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1566. // The parameter parser must not treat that '=' as the key/value separator.
  1567. string content_type =
  1568. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1569. "charset=UTF-8";
  1570. string parsed;
  1571. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1572. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1573. }
  1574. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1575. // A ';' inside the quoted-string is part of the value, not a parameter
  1576. // separator, so it must not truncate the boundary.
  1577. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1578. string parsed;
  1579. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1580. EXPECT_EQ(parsed, "a;b");
  1581. }
  1582. TEST(ParseDispositionParamsTest, QuotedValues) {
  1583. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1584. // ';' and '=' are ordinary characters inside one.
  1585. struct {
  1586. const char *value;
  1587. std::vector<std::pair<const char *, const char *>> expected;
  1588. } cases[] = {
  1589. {"name=\"file1\"; filename=\"a.txt\"",
  1590. {{"name", "file1"}, {"filename", "a.txt"}}},
  1591. // Whitespace around '=' and ';' is still trimmed
  1592. {"name=\"file2\" ;filename = \"a.html\"",
  1593. {{"name", "file2"}, {"filename", "a.html"}}},
  1594. // '=' inside the value used to leave only the text after the last one
  1595. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1596. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1597. {"name=\"x=y\"", {{"name", "x=y"}}},
  1598. // ';' inside the value used to truncate the pair and leave a bogus one
  1599. {"name=\"file3\"; filename=\"a;b.txt\"",
  1600. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1601. // An unquoted value keeps working, and so does filename*
  1602. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1603. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1604. // A parameter with no key is dropped rather than turned into one whose
  1605. // key is the value
  1606. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1607. // An escaped quote does not end the value
  1608. {"name=\"a\\\"; filename=evil.php\"",
  1609. {{"name", "a\"; filename=evil.php"}}},
  1610. // Other backslashes, as in a Windows path, are kept
  1611. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1612. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1613. };
  1614. for (const auto &c : cases) {
  1615. Params params;
  1616. detail::parse_disposition_params(c.value, params);
  1617. for (const auto &kv : c.expected) {
  1618. auto it = params.find(kv.first);
  1619. ASSERT_NE(it, params.end())
  1620. << "value: " << c.value << ", key: " << kv.first;
  1621. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1622. }
  1623. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1624. }
  1625. }
  1626. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1627. Server svr;
  1628. std::string filename;
  1629. std::string content;
  1630. svr.Post("/upload", [&](const Request &req, Response &) {
  1631. const auto &file = req.form.get_file("file");
  1632. filename = file.filename;
  1633. content = file.content;
  1634. });
  1635. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1636. auto se = detail::scope_exit([&] {
  1637. svr.stop();
  1638. thread.join();
  1639. ASSERT_FALSE(svr.is_running());
  1640. });
  1641. svr.wait_until_ready();
  1642. std::string body = "--B\r\n"
  1643. "Content-Disposition: form-data; name=\"file\"; "
  1644. "filename=\"a.txt\"\r\n"
  1645. "Content-Type: text/plain\r\n"
  1646. "\r\n"
  1647. "hello\r\n"
  1648. "--B--\r\n";
  1649. Client cli(HOST, PORT);
  1650. auto res = cli.Post(
  1651. "/upload",
  1652. [&](size_t offset, DataSink &sink) {
  1653. if (offset < body.size()) {
  1654. sink.write(&body[offset], 1);
  1655. } else {
  1656. sink.done();
  1657. }
  1658. return true;
  1659. },
  1660. "multipart/form-data; boundary=B");
  1661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1662. EXPECT_EQ(StatusCode::OK_200, res->status);
  1663. EXPECT_EQ("a.txt", filename);
  1664. EXPECT_EQ("hello", content);
  1665. }
  1666. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1667. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1668. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1669. Server svr;
  1670. std::string field_value, file_name, file_filename;
  1671. bool has_field = false, has_file = false;
  1672. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1673. has_field = req.form.has_field("x=y");
  1674. field_value = req.form.get_field("x=y");
  1675. has_file = req.form.has_file("file1");
  1676. const auto &file = req.form.get_file("file1");
  1677. file_name = file.name;
  1678. file_filename = file.filename;
  1679. res.set_content("ok", "text/plain");
  1680. });
  1681. auto port = svr.bind_to_any_port(HOST);
  1682. thread t = thread([&] { svr.listen_after_bind(); });
  1683. auto se = detail::scope_exit([&] {
  1684. svr.stop();
  1685. t.join();
  1686. ASSERT_FALSE(svr.is_running());
  1687. });
  1688. svr.wait_until_ready();
  1689. UploadFormDataItems items = {
  1690. {"x=y", "field-value", "", ""},
  1691. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1692. };
  1693. Client cli(HOST, port);
  1694. auto res = cli.Post("/quoted", items);
  1695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1696. ASSERT_EQ(StatusCode::OK_200, res->status);
  1697. EXPECT_TRUE(has_field);
  1698. EXPECT_EQ("field-value", field_value);
  1699. EXPECT_TRUE(has_file);
  1700. EXPECT_EQ("file1", file_name);
  1701. EXPECT_EQ("a;b=report.pdf", file_filename);
  1702. }
  1703. TEST(GetHeaderValueTest, DefaultValue) {
  1704. Headers headers = {{"Dummy", "Dummy"}};
  1705. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1706. EXPECT_STREQ("text/plain", val);
  1707. }
  1708. TEST(GetHeaderValueTest, DefaultValueInt) {
  1709. Headers headers = {{"Dummy", "Dummy"}};
  1710. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1711. EXPECT_EQ(100ull, val);
  1712. }
  1713. TEST(GetHeaderValueTest, RegularValue) {
  1714. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1715. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1716. EXPECT_STREQ("text/html", val);
  1717. }
  1718. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1719. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1720. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1721. EXPECT_STREQ("text/html", val);
  1722. }
  1723. TEST(GetHeaderValueTest, SetContent) {
  1724. Response res;
  1725. res.set_content("html", "text/html");
  1726. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1727. res.set_content("text", "text/plain");
  1728. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1729. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1730. }
  1731. TEST(GetHeaderValueTest, RegularValueInt) {
  1732. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1733. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1734. EXPECT_EQ(100ull, val);
  1735. }
  1736. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1737. Headers headers = {{"Content-Length", "x"}};
  1738. auto is_invalid_value = false;
  1739. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1740. is_invalid_value);
  1741. EXPECT_EQ(0ull, val);
  1742. EXPECT_TRUE(is_invalid_value);
  1743. }
  1744. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1745. // An all-digit value that overflows size_t must be reported as invalid, not
  1746. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1747. // a large length to a small one on 32-bit builds, leaving the framing length
  1748. // wrong while is_invalid_value stayed false.
  1749. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1750. auto is_invalid_value = false;
  1751. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1752. is_invalid_value);
  1753. EXPECT_TRUE(is_invalid_value);
  1754. // A well-formed length is unaffected.
  1755. Headers ok = {{"Content-Length", "1234"}};
  1756. is_invalid_value = false;
  1757. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1758. is_invalid_value);
  1759. EXPECT_EQ(1234ull, val);
  1760. EXPECT_FALSE(is_invalid_value);
  1761. }
  1762. TEST(GetHeaderValueTest, Range) {
  1763. {
  1764. Headers headers = {make_range_header({{1, -1}})};
  1765. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1766. EXPECT_STREQ("bytes=1-", val);
  1767. }
  1768. {
  1769. Headers headers = {make_range_header({{-1, 1}})};
  1770. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1771. EXPECT_STREQ("bytes=-1", val);
  1772. }
  1773. {
  1774. Headers headers = {make_range_header({{1, 10}})};
  1775. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1776. EXPECT_STREQ("bytes=1-10", val);
  1777. }
  1778. {
  1779. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1780. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1781. EXPECT_STREQ("bytes=1-10, 100-", val);
  1782. }
  1783. {
  1784. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1785. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1786. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1787. }
  1788. {
  1789. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1790. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1791. EXPECT_STREQ("bytes=0-0, -1", val);
  1792. }
  1793. }
  1794. TEST(BearerTokenAuthTest, SchemeValidation) {
  1795. // A value shorter than "Bearer " must not throw from the fixed-length
  1796. // substr, and a non-Bearer scheme must not be reported as a token.
  1797. struct {
  1798. const char *value;
  1799. const char *expected;
  1800. } cases[] = {
  1801. {"x", ""},
  1802. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1803. {"Bearer abc123", "abc123"},
  1804. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1805. };
  1806. for (const auto &c : cases) {
  1807. Request req;
  1808. req.set_header("Authorization", c.value);
  1809. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1810. }
  1811. }
  1812. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1813. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1814. // to depend on the standard library (libstdc++ handed back duplicates in
  1815. // reverse insertion order, libc++ in insertion order).
  1816. Request req;
  1817. req.set_header("Accept-Encoding", "gzip");
  1818. req.set_header("Accept-Encoding", "deflate");
  1819. req.set_header("Accept-Encoding", "br");
  1820. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1821. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1822. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1823. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1824. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1825. }
  1826. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1827. Request req;
  1828. req.set_header("X-Test", "only");
  1829. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1830. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1831. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1832. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1833. }
  1834. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1835. Request req;
  1836. req.set_header("X-First", "1");
  1837. req.set_header("X-Test", "2");
  1838. req.params.emplace("first", "1");
  1839. req.params.emplace("test", "2");
  1840. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1841. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1842. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1843. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1844. // The second one is negative when read as a signed value
  1845. const auto max_id = (std::numeric_limits<size_t>::max)();
  1846. for (auto id : {max_id / 2, max_id}) {
  1847. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1848. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1849. EXPECT_EQ("", req.get_param_value("test", id));
  1850. EXPECT_EQ("", req.form.get_field("test", id));
  1851. EXPECT_EQ("", req.form.get_file("test", id).content);
  1852. }
  1853. }
  1854. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1855. Headers headers;
  1856. headers.emplace("Host", "example.com");
  1857. headers.emplace("Accept-Encoding", "gzip");
  1858. headers.emplace("User-Agent", "test");
  1859. headers.emplace("Accept-Encoding", "deflate");
  1860. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1861. "Accept-Encoding=deflate ",
  1862. entries_to_string(headers));
  1863. }
  1864. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1865. Headers headers = {{"Content-Type", "text/html"},
  1866. {"CONTENT-TYPE", "text/xml"}};
  1867. EXPECT_EQ(2U, headers.count("content-type"));
  1868. auto it = headers.find("content-type");
  1869. ASSERT_TRUE(it != headers.end());
  1870. EXPECT_EQ("text/html", it->second);
  1871. }
  1872. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1873. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1874. // drop only those fields and leave everything positioned between them.
  1875. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1876. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1877. auto rng = headers.equal_range("a");
  1878. headers.erase(rng.first, rng.second);
  1879. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1880. }
  1881. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1882. Headers headers = {
  1883. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1884. EXPECT_EQ(3U, headers.erase("A"));
  1885. EXPECT_EQ(0U, headers.count("A"));
  1886. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1887. }
  1888. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1889. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1890. headers.emplace_front("Host", "example.com");
  1891. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1892. entries_to_string(headers));
  1893. }
  1894. TEST(ParseHeaderValueTest, Range) {
  1895. {
  1896. Ranges ranges;
  1897. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1898. EXPECT_TRUE(ret);
  1899. EXPECT_EQ(1u, ranges.size());
  1900. EXPECT_EQ(1u, ranges[0].first);
  1901. EXPECT_EQ(-1, ranges[0].second);
  1902. }
  1903. {
  1904. Ranges ranges;
  1905. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1906. EXPECT_TRUE(ret);
  1907. EXPECT_EQ(1u, ranges.size());
  1908. EXPECT_EQ(-1, ranges[0].first);
  1909. EXPECT_EQ(1u, ranges[0].second);
  1910. }
  1911. {
  1912. Ranges ranges;
  1913. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1914. EXPECT_TRUE(ret);
  1915. EXPECT_EQ(1u, ranges.size());
  1916. EXPECT_EQ(1u, ranges[0].first);
  1917. EXPECT_EQ(10u, ranges[0].second);
  1918. }
  1919. {
  1920. Ranges ranges;
  1921. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1922. EXPECT_FALSE(ret);
  1923. }
  1924. {
  1925. Ranges ranges;
  1926. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1927. EXPECT_TRUE(ret);
  1928. EXPECT_EQ(2u, ranges.size());
  1929. EXPECT_EQ(1u, ranges[0].first);
  1930. EXPECT_EQ(10u, ranges[0].second);
  1931. EXPECT_EQ(100u, ranges[1].first);
  1932. EXPECT_EQ(-1, ranges[1].second);
  1933. }
  1934. {
  1935. Ranges ranges;
  1936. auto ret =
  1937. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1938. EXPECT_TRUE(ret);
  1939. EXPECT_EQ(3u, ranges.size());
  1940. EXPECT_EQ(1u, ranges[0].first);
  1941. EXPECT_EQ(10u, ranges[0].second);
  1942. EXPECT_EQ(100u, ranges[1].first);
  1943. EXPECT_EQ(200u, ranges[1].second);
  1944. EXPECT_EQ(300u, ranges[2].first);
  1945. EXPECT_EQ(400u, ranges[2].second);
  1946. }
  1947. {
  1948. Ranges ranges;
  1949. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1950. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1951. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1952. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1953. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1954. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1955. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1956. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1957. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1958. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1959. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1960. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1961. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1962. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1963. EXPECT_FALSE(
  1964. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1965. EXPECT_TRUE(ranges.empty());
  1966. }
  1967. {
  1968. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1969. // remainder of the representation, so it stays accepted.
  1970. Ranges ranges;
  1971. auto ret =
  1972. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1973. EXPECT_TRUE(ret);
  1974. ASSERT_EQ(1u, ranges.size());
  1975. EXPECT_EQ(0, ranges[0].first);
  1976. EXPECT_EQ(-1, ranges[0].second);
  1977. }
  1978. // RFC 9110 14.1: range unit names are case-insensitive.
  1979. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1980. Ranges ranges;
  1981. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1982. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1983. }
  1984. }
  1985. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1986. Request req;
  1987. req.set_header("Accept-Encoding", "gzip");
  1988. Response res;
  1989. res.set_header("Content-Type", "text/plain");
  1990. auto ret = detail::encoding_type(req, res);
  1991. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1992. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1993. #else
  1994. EXPECT_TRUE(ret == detail::EncodingType::None);
  1995. #endif
  1996. }
  1997. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1998. Request req;
  1999. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2000. Response res;
  2001. res.set_header("Content-Type", "text/plain");
  2002. auto ret = detail::encoding_type(req, res);
  2003. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2004. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2005. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2006. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2007. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2008. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2009. #else
  2010. EXPECT_TRUE(ret == detail::EncodingType::None);
  2011. #endif
  2012. }
  2013. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2014. Request req;
  2015. req.set_header("Accept-Encoding",
  2016. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2017. Response res;
  2018. res.set_header("Content-Type", "text/plain");
  2019. auto ret = detail::encoding_type(req, res);
  2020. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2021. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2022. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2023. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2024. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2025. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2026. #else
  2027. EXPECT_TRUE(ret == detail::EncodingType::None);
  2028. #endif
  2029. }
  2030. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2031. // All supported encodings rejected with q=0 should return None
  2032. Request req;
  2033. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2034. Response res;
  2035. res.set_header("Content-Type", "text/plain");
  2036. auto ret = detail::encoding_type(req, res);
  2037. EXPECT_TRUE(ret == detail::EncodingType::None);
  2038. }
  2039. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2040. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2041. Request req;
  2042. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2043. Response res;
  2044. res.set_header("Content-Type", "text/plain");
  2045. auto ret = detail::encoding_type(req, res);
  2046. EXPECT_TRUE(ret == detail::EncodingType::None);
  2047. }
  2048. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2049. Request req;
  2050. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2051. Response res;
  2052. res.set_header("Content-Type", "text/plain");
  2053. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2054. }
  2055. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2056. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2057. Request req;
  2058. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2059. Response res;
  2060. res.set_header("Content-Type", "text/plain");
  2061. auto ret = detail::encoding_type(req, res);
  2062. EXPECT_TRUE(ret == detail::EncodingType::None);
  2063. }
  2064. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2065. // RFC 7231: Accept-Encoding values are case-insensitive
  2066. Request req;
  2067. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2068. Response res;
  2069. res.set_header("Content-Type", "text/plain");
  2070. auto ret = detail::encoding_type(req, res);
  2071. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2072. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2073. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2074. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2075. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2076. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2077. #else
  2078. EXPECT_TRUE(ret == detail::EncodingType::None);
  2079. #endif
  2080. }
  2081. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2082. // q value should determine priority, not hardcoded order
  2083. Request req;
  2084. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2085. Response res;
  2086. res.set_header("Content-Type", "text/plain");
  2087. auto ret = detail::encoding_type(req, res);
  2088. // gzip has highest q=1.0, so it should be selected even though
  2089. // br and zstd are also supported
  2090. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2091. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2092. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2093. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2094. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2095. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2096. #else
  2097. EXPECT_TRUE(ret == detail::EncodingType::None);
  2098. #endif
  2099. }
  2100. TEST(BufferStreamTest, read) {
  2101. detail::BufferStream strm1;
  2102. Stream &strm = strm1;
  2103. EXPECT_EQ(5, strm.write("hello"));
  2104. char buf[512];
  2105. EXPECT_EQ(2, strm.read(buf, 2));
  2106. EXPECT_EQ('h', buf[0]);
  2107. EXPECT_EQ('e', buf[1]);
  2108. EXPECT_EQ(2, strm.read(buf, 2));
  2109. EXPECT_EQ('l', buf[0]);
  2110. EXPECT_EQ('l', buf[1]);
  2111. EXPECT_EQ(1, strm.read(buf, 1));
  2112. EXPECT_EQ('o', buf[0]);
  2113. EXPECT_EQ(0, strm.read(buf, 1));
  2114. }
  2115. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2116. auto host = "www.httpwatch.com";
  2117. auto ip = hosted_at(host);
  2118. EXPECT_EQ("23.96.13.243", ip);
  2119. std::vector<std::string> addrs;
  2120. hosted_at(host, addrs);
  2121. EXPECT_EQ(1u, addrs.size());
  2122. }
  2123. #if 0 // It depends on each test environment...
  2124. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2125. auto host = "www.youtube.com";
  2126. std::vector<std::string> addrs;
  2127. hosted_at(host, addrs);
  2128. EXPECT_EQ(20u, addrs.size());
  2129. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2130. EXPECT_TRUE(it != addrs.end());
  2131. }
  2132. #endif
  2133. class ChunkedEncodingTest : public ::testing::Test {
  2134. protected:
  2135. ChunkedEncodingTest()
  2136. : cli_(HOST, PORT)
  2137. #ifdef CPPHTTPLIB_SSL_ENABLED
  2138. ,
  2139. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2140. #endif
  2141. {
  2142. cli_.set_connection_timeout(2);
  2143. #ifdef CPPHTTPLIB_SSL_ENABLED
  2144. cli_.enable_server_certificate_verification(false);
  2145. #endif
  2146. }
  2147. virtual void SetUp() {
  2148. read_file("./image.jpg", image_data_);
  2149. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2150. res.set_content("Hello World!", "text/plain");
  2151. });
  2152. svr_.Get(
  2153. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2154. res.set_chunked_content_provider(
  2155. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2156. size_t remaining = image_data_.size() - offset;
  2157. if (remaining == 0) {
  2158. sink.done();
  2159. } else {
  2160. constexpr size_t CHUNK_SIZE = 1024;
  2161. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2162. sink.write(&image_data_[offset], send_size);
  2163. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2164. }
  2165. return true;
  2166. });
  2167. });
  2168. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2169. svr_.wait_until_ready();
  2170. }
  2171. virtual void TearDown() {
  2172. svr_.stop();
  2173. if (!request_threads_.empty()) {
  2174. std::this_thread::sleep_for(std::chrono::seconds(1));
  2175. for (auto &t : request_threads_) {
  2176. t.join();
  2177. }
  2178. }
  2179. t_.join();
  2180. }
  2181. #ifdef CPPHTTPLIB_SSL_ENABLED
  2182. SSLClient cli_;
  2183. SSLServer svr_;
  2184. #else
  2185. Client cli_;
  2186. Server svr_;
  2187. #endif
  2188. thread t_;
  2189. std::vector<thread> request_threads_;
  2190. std::string image_data_;
  2191. };
  2192. TEST_F(ChunkedEncodingTest, NormalGet) {
  2193. auto res = cli_.Get("/chunked");
  2194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2195. std::string out;
  2196. read_file("./image.jpg", out);
  2197. EXPECT_EQ(StatusCode::OK_200, res->status);
  2198. EXPECT_EQ(out, res->body);
  2199. }
  2200. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2201. std::string body;
  2202. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2203. body.append(data, data_length);
  2204. return true;
  2205. });
  2206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2207. std::string out;
  2208. read_file("./image.jpg", out);
  2209. EXPECT_EQ(StatusCode::OK_200, res->status);
  2210. EXPECT_EQ(out, body);
  2211. }
  2212. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2213. std::string body;
  2214. auto res = cli_.Get(
  2215. "/chunked",
  2216. [&](const Response &response) {
  2217. EXPECT_EQ(StatusCode::OK_200, response.status);
  2218. return true;
  2219. },
  2220. [&](const char *data, size_t data_length) {
  2221. body.append(data, data_length);
  2222. return true;
  2223. });
  2224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2225. std::string out;
  2226. read_file("./image.jpg", out);
  2227. EXPECT_EQ(StatusCode::OK_200, res->status);
  2228. EXPECT_EQ(out, body);
  2229. }
  2230. TEST(RangeTest, FromHTTPBin_Online) {
  2231. auto host = "httpbingo.org";
  2232. auto path = std::string{"/range/32"};
  2233. #ifdef CPPHTTPLIB_SSL_ENABLED
  2234. auto port = 443;
  2235. SSLClient cli(host, port);
  2236. #else
  2237. auto port = 80;
  2238. Client cli(host, port);
  2239. #endif
  2240. cli.set_connection_timeout(5);
  2241. {
  2242. auto res = cli.Get(path);
  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. {
  2248. Headers headers = {make_range_header({{1, -1}})};
  2249. auto res = cli.Get(path, headers);
  2250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2251. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2252. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2253. }
  2254. {
  2255. Headers headers = {make_range_header({{1, 10}})};
  2256. auto res = cli.Get(path, headers);
  2257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2258. EXPECT_EQ("bcdefghijk", res->body);
  2259. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2260. }
  2261. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2262. // entire resource, while the original httpbin returned 200. Both are
  2263. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2264. {
  2265. Headers headers = {make_range_header({{0, 31}})};
  2266. auto res = cli.Get(path, headers);
  2267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2268. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2269. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2270. res->status == StatusCode::PartialContent_206);
  2271. }
  2272. {
  2273. Headers headers = {make_range_header({{0, -1}})};
  2274. auto res = cli.Get(path, headers);
  2275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2276. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2277. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2278. res->status == StatusCode::PartialContent_206);
  2279. }
  2280. // go-httpbin returns 206 with clamped range for over-range requests,
  2281. // while the original httpbin returned 416. Both behaviors are observed
  2282. // in real servers, so we only verify the request succeeds.
  2283. {
  2284. Headers headers = {make_range_header({{0, 32}})};
  2285. auto res = cli.Get(path, headers);
  2286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2287. }
  2288. }
  2289. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2290. auto host = "unresolvableaddress.local";
  2291. auto path = std::string{"/"};
  2292. #ifdef CPPHTTPLIB_SSL_ENABLED
  2293. auto port = 443;
  2294. SSLClient cli(host, port);
  2295. #else
  2296. auto port = 80;
  2297. Client cli(host, port);
  2298. #endif
  2299. cli.set_connection_timeout(1);
  2300. {
  2301. auto res = cli.Get(path);
  2302. ASSERT_FALSE(res);
  2303. }
  2304. std::this_thread::sleep_for(std::chrono::seconds(8));
  2305. }
  2306. #if defined(__linux__) && defined(__GLIBC__) && \
  2307. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2308. // Forward declaration: in split builds split.py strips `inline` and moves the
  2309. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2310. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2311. // against the symbol in both header-only and split builds.
  2312. namespace httplib {
  2313. namespace detail {
  2314. int getaddrinfo_with_timeout(const char *node, const char *service,
  2315. const struct addrinfo *hints,
  2316. struct addrinfo **res, time_t timeout_sec);
  2317. } // namespace detail
  2318. } // namespace httplib
  2319. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2320. //
  2321. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2322. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2323. // gai_suspend() call hits the connection timeout the function calls
  2324. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2325. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2326. // still alive and still references the now-destroyed stack frame.
  2327. //
  2328. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2329. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2330. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2331. // and runs them in a container.
  2332. namespace {
  2333. bool should_run_issue_2431_tests() {
  2334. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2335. return v && *v && std::string(v) != "0";
  2336. }
  2337. std::string unique_unresolvable_host(int n) {
  2338. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2339. // glibc still asks the configured nameserver — which is exactly the path
  2340. // we want to exercise. A unique label per call avoids the resolver cache.
  2341. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2342. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2343. std::to_string(n) + ".invalid";
  2344. }
  2345. } // namespace
  2346. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2347. if (!should_run_issue_2431_tests()) {
  2348. GTEST_SKIP()
  2349. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2350. }
  2351. for (int i = 0; i < 8; ++i) {
  2352. struct addrinfo hints;
  2353. memset(&hints, 0, sizeof(hints));
  2354. hints.ai_family = AF_UNSPEC;
  2355. hints.ai_socktype = SOCK_STREAM;
  2356. auto host = unique_unresolvable_host(i);
  2357. struct addrinfo *result = nullptr;
  2358. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2359. &result, /*timeout_sec=*/1);
  2360. if (rc == 0 && result) { freeaddrinfo(result); }
  2361. }
  2362. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2363. // stack region they still believe holds their gaicb.
  2364. std::this_thread::sleep_for(std::chrono::seconds(3));
  2365. }
  2366. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2367. if (!should_run_issue_2431_tests()) {
  2368. GTEST_SKIP()
  2369. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2370. }
  2371. std::atomic<bool> stop{false};
  2372. std::vector<std::thread> threads;
  2373. for (int t = 0; t < 8; ++t) {
  2374. threads.emplace_back([t, &stop] {
  2375. int i = 0;
  2376. while (!stop.load(std::memory_order_relaxed)) {
  2377. struct addrinfo hints;
  2378. memset(&hints, 0, sizeof(hints));
  2379. hints.ai_family = AF_UNSPEC;
  2380. hints.ai_socktype = SOCK_STREAM;
  2381. auto host = unique_unresolvable_host(t * 100000 + i++);
  2382. struct addrinfo *result = nullptr;
  2383. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2384. &result, /*timeout_sec=*/1);
  2385. if (rc == 0 && result) { freeaddrinfo(result); }
  2386. }
  2387. });
  2388. }
  2389. std::this_thread::sleep_for(std::chrono::seconds(8));
  2390. stop.store(true, std::memory_order_relaxed);
  2391. for (auto &th : threads) {
  2392. th.join();
  2393. }
  2394. std::this_thread::sleep_for(std::chrono::seconds(3));
  2395. }
  2396. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2397. if (!should_run_issue_2431_tests()) {
  2398. GTEST_SKIP()
  2399. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2400. }
  2401. std::atomic<bool> stop{false};
  2402. std::vector<std::thread> threads;
  2403. for (int t = 0; t < 8; ++t) {
  2404. threads.emplace_back([t, &stop] {
  2405. int i = 0;
  2406. while (!stop.load(std::memory_order_relaxed)) {
  2407. auto host = unique_unresolvable_host(t * 100000 + i++);
  2408. Client cli(host, 80);
  2409. cli.set_connection_timeout(1, 0);
  2410. cli.set_read_timeout(1, 0);
  2411. cli.set_write_timeout(1, 0);
  2412. (void)cli.Get("/");
  2413. }
  2414. });
  2415. }
  2416. std::this_thread::sleep_for(std::chrono::seconds(8));
  2417. stop.store(true, std::memory_order_relaxed);
  2418. for (auto &th : threads) {
  2419. th.join();
  2420. }
  2421. std::this_thread::sleep_for(std::chrono::seconds(3));
  2422. }
  2423. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2424. TEST(ConnectionErrorTest, InvalidHost) {
  2425. auto host = "-abcde.com";
  2426. #ifdef CPPHTTPLIB_SSL_ENABLED
  2427. auto port = 443;
  2428. SSLClient cli(host, port);
  2429. #else
  2430. auto port = 80;
  2431. Client cli(host, port);
  2432. #endif
  2433. cli.set_connection_timeout(std::chrono::seconds(2));
  2434. auto res = cli.Get("/");
  2435. ASSERT_TRUE(!res);
  2436. EXPECT_EQ(Error::Connection, res.error());
  2437. }
  2438. TEST(ConnectionErrorTest, InvalidHost2) {
  2439. auto host = "httpcan.org/";
  2440. #ifdef CPPHTTPLIB_SSL_ENABLED
  2441. SSLClient cli(host);
  2442. #else
  2443. Client cli(host);
  2444. #endif
  2445. cli.set_connection_timeout(std::chrono::seconds(2));
  2446. auto res = cli.Get("/");
  2447. ASSERT_TRUE(!res);
  2448. EXPECT_EQ(Error::Connection, res.error());
  2449. }
  2450. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2451. auto host = "httpcan.org/";
  2452. #ifdef CPPHTTPLIB_SSL_ENABLED
  2453. SSLClient cli(host);
  2454. #else
  2455. Client cli(host);
  2456. #endif
  2457. cli.set_connection_timeout(std::chrono::seconds(2));
  2458. auto res = cli.Get("/");
  2459. ASSERT_TRUE(!res);
  2460. stringstream s;
  2461. s << "error code: " << res.error();
  2462. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2463. }
  2464. TEST(ConnectionErrorTest, InvalidPort) {
  2465. auto host = "localhost";
  2466. auto port = 44380;
  2467. #ifdef CPPHTTPLIB_SSL_ENABLED
  2468. SSLClient cli(host, port);
  2469. #else
  2470. Client cli(host, port);
  2471. #endif
  2472. cli.set_connection_timeout(std::chrono::seconds(2));
  2473. auto res = cli.Get("/");
  2474. ASSERT_TRUE(!res);
  2475. EXPECT_TRUE(Error::Connection == res.error() ||
  2476. Error::ConnectionTimeout == res.error());
  2477. }
  2478. TEST(ConnectionErrorTest, Timeout_Online) {
  2479. auto host = "google.com";
  2480. #ifdef CPPHTTPLIB_SSL_ENABLED
  2481. auto port = 44380;
  2482. SSLClient cli(host, port);
  2483. #else
  2484. auto port = 8080;
  2485. Client cli(host, port);
  2486. #endif
  2487. cli.set_connection_timeout(std::chrono::seconds(2));
  2488. // only probe one address type so that the error reason
  2489. // correlates to the timed-out IPv4, not the unsupported
  2490. // IPv6 connection attempt
  2491. cli.set_address_family(AF_INET);
  2492. auto res = cli.Get("/");
  2493. ASSERT_TRUE(!res);
  2494. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2495. }
  2496. TEST(CancelTest, NoCancel_Online) {
  2497. auto host = "httpbingo.org";
  2498. auto path = std::string{"/range/32"};
  2499. #ifdef CPPHTTPLIB_SSL_ENABLED
  2500. auto port = 443;
  2501. SSLClient cli(host, port);
  2502. #else
  2503. auto port = 80;
  2504. Client cli(host, port);
  2505. #endif
  2506. cli.set_connection_timeout(std::chrono::seconds(5));
  2507. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2509. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2510. EXPECT_EQ(StatusCode::OK_200, res->status);
  2511. }
  2512. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2513. // Use /bytes with a large payload so that the DownloadProgress callback
  2514. // (which only fires for Content-Length responses) is invoked before the
  2515. // entire body is received, giving cancellation a chance to fire.
  2516. auto host = "httpbingo.org";
  2517. auto path = std::string{"/bytes/524288"};
  2518. #ifdef CPPHTTPLIB_SSL_ENABLED
  2519. auto port = 443;
  2520. SSLClient cli(host, port);
  2521. #else
  2522. auto port = 80;
  2523. Client cli(host, port);
  2524. #endif
  2525. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2526. cli.set_connection_timeout(std::chrono::seconds(5));
  2527. ASSERT_TRUE(!res);
  2528. EXPECT_EQ(Error::Canceled, res.error());
  2529. }
  2530. TEST(CancelTest, WithCancelLargePayload_Online) {
  2531. auto host = "httpbingo.org";
  2532. auto path = std::string{"/bytes/524288"};
  2533. #ifdef CPPHTTPLIB_SSL_ENABLED
  2534. auto port = 443;
  2535. SSLClient cli(host, port);
  2536. #else
  2537. auto port = 80;
  2538. Client cli(host, port);
  2539. #endif
  2540. cli.set_connection_timeout(std::chrono::seconds(5));
  2541. uint32_t count = 0;
  2542. auto res =
  2543. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2544. ASSERT_TRUE(!res);
  2545. EXPECT_EQ(Error::Canceled, res.error());
  2546. }
  2547. TEST(CancelTest, NoCancelPost) {
  2548. Server svr;
  2549. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2550. res.set_content("Hello World!", "text/plain");
  2551. });
  2552. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2553. auto se = detail::scope_exit([&] {
  2554. svr.stop();
  2555. thread.join();
  2556. ASSERT_FALSE(svr.is_running());
  2557. });
  2558. svr.wait_until_ready();
  2559. Client cli(HOST, PORT);
  2560. cli.set_connection_timeout(std::chrono::seconds(5));
  2561. auto res =
  2562. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2563. "application/json", [](uint64_t, uint64_t) { return true; });
  2564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2565. EXPECT_EQ("Hello World!", res->body);
  2566. EXPECT_EQ(StatusCode::OK_200, res->status);
  2567. }
  2568. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2569. Server svr;
  2570. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2571. res.set_content("Hello World!", "text/plain");
  2572. });
  2573. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2574. auto se = detail::scope_exit([&] {
  2575. svr.stop();
  2576. thread.join();
  2577. ASSERT_FALSE(svr.is_running());
  2578. });
  2579. svr.wait_until_ready();
  2580. Client cli(HOST, PORT);
  2581. cli.set_connection_timeout(std::chrono::seconds(5));
  2582. auto res =
  2583. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2584. "application/json", [](uint64_t, uint64_t) { return false; });
  2585. ASSERT_TRUE(!res);
  2586. EXPECT_EQ(Error::Canceled, res.error());
  2587. }
  2588. TEST(CancelTest, WithCancelLargePayloadPost) {
  2589. Server svr;
  2590. svr.set_payload_max_length(200 * 1024 * 1024);
  2591. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2592. res.set_content(LARGE_DATA, "text/plain");
  2593. });
  2594. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2595. auto se = detail::scope_exit([&] {
  2596. svr.stop();
  2597. thread.join();
  2598. ASSERT_FALSE(svr.is_running());
  2599. });
  2600. svr.wait_until_ready();
  2601. Client cli(HOST, PORT);
  2602. cli.set_payload_max_length(200 * 1024 * 1024);
  2603. cli.set_connection_timeout(std::chrono::seconds(5));
  2604. auto res =
  2605. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2606. "application/json", [](uint64_t, uint64_t) { return false; });
  2607. ASSERT_TRUE(!res);
  2608. EXPECT_EQ(Error::Canceled, res.error());
  2609. }
  2610. TEST(CancelTest, NoCancelPut) {
  2611. Server svr;
  2612. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2613. res.set_content("Hello World!", "text/plain");
  2614. });
  2615. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2616. auto se = detail::scope_exit([&] {
  2617. svr.stop();
  2618. thread.join();
  2619. ASSERT_FALSE(svr.is_running());
  2620. });
  2621. svr.wait_until_ready();
  2622. Client cli(HOST, PORT);
  2623. cli.set_connection_timeout(std::chrono::seconds(5));
  2624. auto res =
  2625. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2626. "application/json", [](uint64_t, uint64_t) { return true; });
  2627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2628. EXPECT_EQ("Hello World!", res->body);
  2629. EXPECT_EQ(StatusCode::OK_200, res->status);
  2630. }
  2631. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2632. Server svr;
  2633. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2634. res.set_content("Hello World!", "text/plain");
  2635. });
  2636. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2637. auto se = detail::scope_exit([&] {
  2638. svr.stop();
  2639. thread.join();
  2640. ASSERT_FALSE(svr.is_running());
  2641. });
  2642. svr.wait_until_ready();
  2643. Client cli(HOST, PORT);
  2644. cli.set_connection_timeout(std::chrono::seconds(5));
  2645. auto res =
  2646. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2647. "application/json", [](uint64_t, uint64_t) { return false; });
  2648. ASSERT_TRUE(!res);
  2649. EXPECT_EQ(Error::Canceled, res.error());
  2650. }
  2651. TEST(CancelTest, WithCancelLargePayloadPut) {
  2652. Server svr;
  2653. svr.set_payload_max_length(200 * 1024 * 1024);
  2654. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2655. res.set_content(LARGE_DATA, "text/plain");
  2656. });
  2657. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2658. auto se = detail::scope_exit([&] {
  2659. svr.stop();
  2660. thread.join();
  2661. ASSERT_FALSE(svr.is_running());
  2662. });
  2663. svr.wait_until_ready();
  2664. Client cli(HOST, PORT);
  2665. cli.set_payload_max_length(200 * 1024 * 1024);
  2666. cli.set_connection_timeout(std::chrono::seconds(5));
  2667. auto res =
  2668. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2669. "application/json", [](uint64_t, uint64_t) { return false; });
  2670. ASSERT_TRUE(!res);
  2671. EXPECT_EQ(Error::Canceled, res.error());
  2672. }
  2673. TEST(CancelTest, NoCancelPatch) {
  2674. Server svr;
  2675. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2676. res.set_content("Hello World!", "text/plain");
  2677. });
  2678. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2679. auto se = detail::scope_exit([&] {
  2680. svr.stop();
  2681. thread.join();
  2682. ASSERT_FALSE(svr.is_running());
  2683. });
  2684. svr.wait_until_ready();
  2685. Client cli(HOST, PORT);
  2686. cli.set_connection_timeout(std::chrono::seconds(5));
  2687. auto res =
  2688. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2689. "application/json", [](uint64_t, uint64_t) { return true; });
  2690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2691. EXPECT_EQ("Hello World!", res->body);
  2692. EXPECT_EQ(StatusCode::OK_200, res->status);
  2693. }
  2694. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2695. Server svr;
  2696. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2697. res.set_content("Hello World!", "text/plain");
  2698. });
  2699. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2700. auto se = detail::scope_exit([&] {
  2701. svr.stop();
  2702. thread.join();
  2703. ASSERT_FALSE(svr.is_running());
  2704. });
  2705. svr.wait_until_ready();
  2706. Client cli(HOST, PORT);
  2707. cli.set_connection_timeout(std::chrono::seconds(5));
  2708. auto res =
  2709. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2710. "application/json", [](uint64_t, uint64_t) { return false; });
  2711. ASSERT_TRUE(!res);
  2712. EXPECT_EQ(Error::Canceled, res.error());
  2713. }
  2714. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2715. Server svr;
  2716. svr.set_payload_max_length(200 * 1024 * 1024);
  2717. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2718. res.set_content(LARGE_DATA, "text/plain");
  2719. });
  2720. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2721. auto se = detail::scope_exit([&] {
  2722. svr.stop();
  2723. thread.join();
  2724. ASSERT_FALSE(svr.is_running());
  2725. });
  2726. svr.wait_until_ready();
  2727. Client cli(HOST, PORT);
  2728. cli.set_payload_max_length(200 * 1024 * 1024);
  2729. cli.set_connection_timeout(std::chrono::seconds(5));
  2730. auto res =
  2731. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2732. "application/json", [](uint64_t, uint64_t) { return false; });
  2733. ASSERT_TRUE(!res);
  2734. EXPECT_EQ(Error::Canceled, res.error());
  2735. }
  2736. TEST(CancelTest, NoCancelDelete) {
  2737. Server svr;
  2738. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2739. res.set_content("Hello World!", "text/plain");
  2740. });
  2741. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2742. auto se = detail::scope_exit([&] {
  2743. svr.stop();
  2744. thread.join();
  2745. ASSERT_FALSE(svr.is_running());
  2746. });
  2747. svr.wait_until_ready();
  2748. Client cli(HOST, PORT);
  2749. cli.set_connection_timeout(std::chrono::seconds(5));
  2750. auto res =
  2751. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2752. "application/json", [](uint64_t, uint64_t) { return true; });
  2753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2754. EXPECT_EQ("Hello World!", res->body);
  2755. EXPECT_EQ(StatusCode::OK_200, res->status);
  2756. }
  2757. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2758. Server svr;
  2759. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2760. res.set_content("Hello World!", "text/plain");
  2761. });
  2762. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2763. auto se = detail::scope_exit([&] {
  2764. svr.stop();
  2765. thread.join();
  2766. ASSERT_FALSE(svr.is_running());
  2767. });
  2768. svr.wait_until_ready();
  2769. Client cli(HOST, PORT);
  2770. cli.set_connection_timeout(std::chrono::seconds(5));
  2771. auto res =
  2772. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2773. "application/json", [](uint64_t, uint64_t) { return false; });
  2774. ASSERT_TRUE(!res);
  2775. EXPECT_EQ(Error::Canceled, res.error());
  2776. }
  2777. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2778. Server svr;
  2779. svr.set_payload_max_length(200 * 1024 * 1024);
  2780. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2781. res.set_content(LARGE_DATA, "text/plain");
  2782. });
  2783. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2784. auto se = detail::scope_exit([&] {
  2785. svr.stop();
  2786. thread.join();
  2787. ASSERT_FALSE(svr.is_running());
  2788. });
  2789. svr.wait_until_ready();
  2790. Client cli(HOST, PORT);
  2791. cli.set_payload_max_length(200 * 1024 * 1024);
  2792. cli.set_connection_timeout(std::chrono::seconds(5));
  2793. auto res =
  2794. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2795. "application/json", [](uint64_t, uint64_t) { return false; });
  2796. ASSERT_TRUE(!res);
  2797. EXPECT_EQ(Error::Canceled, res.error());
  2798. }
  2799. static std::string remove_whitespace(const std::string &input) {
  2800. std::string output;
  2801. output.reserve(input.size());
  2802. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2803. [](unsigned char c) { return !std::isspace(c); });
  2804. return output;
  2805. }
  2806. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2807. auto host = "httpbingo.org";
  2808. auto path = std::string{"/basic-auth/hello/world"};
  2809. #ifdef CPPHTTPLIB_SSL_ENABLED
  2810. auto port = 443;
  2811. SSLClient cli(host, port);
  2812. #else
  2813. auto port = 80;
  2814. Client cli(host, port);
  2815. #endif
  2816. {
  2817. auto res = cli.Get(path);
  2818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2819. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2820. }
  2821. {
  2822. auto res = cli.Get(
  2823. path, Headers{make_basic_authentication_header("hello", "world")});
  2824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2825. auto body = remove_whitespace(res->body);
  2826. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2827. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2828. EXPECT_EQ(StatusCode::OK_200, res->status);
  2829. }
  2830. {
  2831. cli.set_basic_auth("hello", "world");
  2832. auto res = cli.Get(path);
  2833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2834. auto body = remove_whitespace(res->body);
  2835. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2836. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2837. EXPECT_EQ(StatusCode::OK_200, res->status);
  2838. }
  2839. {
  2840. cli.set_basic_auth("hello", "bad");
  2841. auto res = cli.Get(path);
  2842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2843. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2844. }
  2845. {
  2846. cli.set_basic_auth("bad", "world");
  2847. auto res = cli.Get(path);
  2848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2849. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2850. }
  2851. }
  2852. #ifdef CPPHTTPLIB_SSL_ENABLED
  2853. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2854. auto host = "httpbingo.org";
  2855. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2856. auto paths = std::vector<std::string>{
  2857. "/digest-auth/auth/hello/world/MD5",
  2858. "/digest-auth/auth/hello/world/SHA-256",
  2859. };
  2860. auto port = 443;
  2861. SSLClient cli(host, port);
  2862. {
  2863. auto res = cli.Get(unauth_path);
  2864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2865. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2866. }
  2867. {
  2868. cli.set_digest_auth("hello", "world");
  2869. for (const auto &path : paths) {
  2870. auto res = cli.Get(path.c_str());
  2871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2872. auto body = remove_whitespace(res->body);
  2873. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2874. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2875. EXPECT_EQ(StatusCode::OK_200, res->status);
  2876. }
  2877. cli.set_digest_auth("hello", "bad");
  2878. for (const auto &path : paths) {
  2879. auto res = cli.Get(path.c_str());
  2880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2881. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2882. }
  2883. }
  2884. }
  2885. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2886. // comma-separated list of challenges, and each challenge may itself carry a
  2887. // comma-separated auth-param list, so a server can legally offer Basic
  2888. // before Digest, either as two field lines or packed into one. Runs one 401
  2889. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2890. // value() joins them in receipt order) and checks that the retry carries a
  2891. // well-formed Digest Authorization header naming expected_realm.
  2892. static void
  2893. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2894. const std::string &expected_realm) {
  2895. std::atomic<int> hits{0};
  2896. Server svr;
  2897. svr.Get("/x", [&](const Request &req, Response &res) {
  2898. if (++hits == 1) {
  2899. res.status = StatusCode::Unauthorized_401;
  2900. for (const auto &challenge : challenges) {
  2901. res.set_header("WWW-Authenticate", challenge);
  2902. }
  2903. } else {
  2904. auto authorization = req.get_header_value("Authorization");
  2905. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2906. EXPECT_NE(std::string::npos,
  2907. authorization.find("realm=\"" + expected_realm + "\""));
  2908. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2909. res.set_content("ok", "text/plain");
  2910. }
  2911. });
  2912. auto port = svr.bind_to_any_port(HOST);
  2913. std::thread t([&]() { svr.listen_after_bind(); });
  2914. auto se = detail::scope_exit([&] {
  2915. svr.stop();
  2916. t.join();
  2917. });
  2918. svr.wait_until_ready();
  2919. Client cli(HOST, port);
  2920. cli.set_digest_auth("hello", "world");
  2921. auto res = cli.Get("/x");
  2922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2923. EXPECT_EQ(2, hits.load());
  2924. }
  2925. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2926. static const char *kDigestChallenge =
  2927. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2928. "algorithm=MD5";
  2929. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2930. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2931. "testrealm");
  2932. }
  2933. // Same challenge list with the schemes in the opposite order, to make sure
  2934. // the fix above didn't just special-case "Basic first".
  2935. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2936. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2937. "testrealm");
  2938. }
  2939. // A comma inside a quoted auth-param value must not be mistaken for the
  2940. // separator between two challenges (or two auth-params).
  2941. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2942. run_digest_challenge_list_test(
  2943. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2944. "algorithm=MD5"},
  2945. "test,realm");
  2946. }
  2947. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2948. // make_digest_authentication_header() dereferences both unconditionally, so
  2949. // a server sending a challenge missing either one must not be treated as
  2950. // usable -- doing so used to crash the client with std::out_of_range.
  2951. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2952. Server svr;
  2953. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2954. res.status = StatusCode::Unauthorized_401;
  2955. res.set_header("WWW-Authenticate", challenge);
  2956. });
  2957. auto port = svr.bind_to_any_port(HOST);
  2958. std::thread t([&]() { svr.listen_after_bind(); });
  2959. auto se = detail::scope_exit([&] {
  2960. svr.stop();
  2961. t.join();
  2962. });
  2963. svr.wait_until_ready();
  2964. Client cli(HOST, port);
  2965. cli.set_digest_auth("hello", "world");
  2966. auto res = cli.Get("/x");
  2967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2968. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2969. }
  2970. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2971. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2972. }
  2973. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2974. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2975. }
  2976. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2977. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2978. }
  2979. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2980. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2981. // when storing the values, so the header builder has to re-escape them (and
  2982. // keep algorithm a bare token); otherwise the value breaks out of its
  2983. // quoted-string and injects extra auth-params into the client's Authorization.
  2984. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2985. std::atomic<int> hits{0};
  2986. std::string authorization;
  2987. Server svr;
  2988. svr.Get("/x", [&](const Request &req, Response &res) {
  2989. if (++hits == 1) {
  2990. res.status = StatusCode::Unauthorized_401;
  2991. // On the wire the quotes embedded in the values are backslash-escaped.
  2992. res.set_header("WWW-Authenticate",
  2993. "Digest realm=\"testrealm\", "
  2994. "nonce=\"n\\\"; injected=\\\"x\", "
  2995. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2996. } else {
  2997. authorization = req.get_header_value("Authorization");
  2998. res.set_content("ok", "text/plain");
  2999. }
  3000. });
  3001. auto port = svr.bind_to_any_port(HOST);
  3002. std::thread t([&]() { svr.listen_after_bind(); });
  3003. auto se = detail::scope_exit([&] {
  3004. svr.stop();
  3005. t.join();
  3006. });
  3007. svr.wait_until_ready();
  3008. Client cli(HOST, port);
  3009. cli.set_digest_auth("hello", "world");
  3010. auto res = cli.Get("/x");
  3011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3012. EXPECT_EQ(2, hits.load());
  3013. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3014. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3015. // inside its quoted-string rather than starting an "injected" auth-param.
  3016. EXPECT_NE(std::string::npos,
  3017. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3018. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3019. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3020. }
  3021. #endif
  3022. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3023. auto host = "google.com";
  3024. auto another_host = "example.com";
  3025. auto wrong_ip = "0.0.0.0";
  3026. #ifdef CPPHTTPLIB_SSL_ENABLED
  3027. SSLClient cli(host);
  3028. #else
  3029. Client cli(host);
  3030. #endif
  3031. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3032. auto res = cli.Get("/");
  3033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3034. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3035. }
  3036. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3037. auto host = "google.com";
  3038. auto wrong_ip = "0.0.0.0";
  3039. #ifdef CPPHTTPLIB_SSL_ENABLED
  3040. SSLClient cli(host);
  3041. #else
  3042. Client cli(host);
  3043. #endif
  3044. cli.set_hostname_addr_map({{host, wrong_ip}});
  3045. auto res = cli.Get("/");
  3046. ASSERT_TRUE(!res);
  3047. EXPECT_EQ(Error::Connection, res.error());
  3048. }
  3049. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3050. // A mapped value that is not an IP literal must be resolved. "localhost"
  3051. // resolves from the hosts file, so this test needs no external DNS.
  3052. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3053. auto host = "target.invalid";
  3054. Server svr;
  3055. std::string received_host;
  3056. svr.Get("/hi", [&](const Request &req, Response &res) {
  3057. received_host = req.get_header_value("Host");
  3058. res.set_content("Hello World!", "text/plain");
  3059. });
  3060. auto port = svr.bind_to_any_port(HOST);
  3061. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3062. auto se = detail::scope_exit([&] {
  3063. svr.stop();
  3064. thread.join();
  3065. ASSERT_FALSE(svr.is_running());
  3066. });
  3067. svr.wait_until_ready();
  3068. Client cli(host, port);
  3069. cli.set_hostname_addr_map({{host, HOST}});
  3070. auto res = cli.Get("/hi");
  3071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3072. EXPECT_EQ(StatusCode::OK_200, res->status);
  3073. // The mapping only redirects the connection; the identity stays host_.
  3074. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3075. }
  3076. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3077. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3078. auto host = "target.invalid";
  3079. Server svr;
  3080. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3081. res.set_content("Hello World!", "text/plain");
  3082. });
  3083. auto port = svr.bind_to_any_port("127.0.0.1");
  3084. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3085. auto se = detail::scope_exit([&] {
  3086. svr.stop();
  3087. thread.join();
  3088. ASSERT_FALSE(svr.is_running());
  3089. });
  3090. svr.wait_until_ready();
  3091. Client cli(host, port);
  3092. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3093. auto res = cli.Get("/hi");
  3094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3095. EXPECT_EQ(StatusCode::OK_200, res->status);
  3096. }
  3097. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3098. // An empty mapped value must leave host_ as the connection target. Without
  3099. // that guard the empty value would become the host argument, getaddrinfo
  3100. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3101. // loopback - silently connecting somewhere the caller never asked for.
  3102. // The server listens on loopback, so such a fallback would succeed and is
  3103. // therefore observable as a failure of this test.
  3104. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3105. Server svr;
  3106. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3107. res.set_content("Hello World!", "text/plain");
  3108. });
  3109. auto port = svr.bind_to_any_port(HOST);
  3110. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3111. auto se = detail::scope_exit([&] {
  3112. svr.stop();
  3113. thread.join();
  3114. ASSERT_FALSE(svr.is_running());
  3115. });
  3116. svr.wait_until_ready();
  3117. Client cli(blackhole, port);
  3118. cli.set_hostname_addr_map({{blackhole, ""}});
  3119. cli.set_connection_timeout(1);
  3120. auto res = cli.Get("/hi");
  3121. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3122. }
  3123. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3124. auto host = "httpbingo.org";
  3125. auto path = std::string{"/absolute-redirect/3"};
  3126. #ifdef CPPHTTPLIB_SSL_ENABLED
  3127. SSLClient cli(host);
  3128. #else
  3129. Client cli(host);
  3130. #endif
  3131. cli.set_follow_location(true);
  3132. auto res = cli.Get(path);
  3133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3134. EXPECT_EQ(StatusCode::OK_200, res->status);
  3135. }
  3136. TEST(RedirectTest, Redirect_Online) {
  3137. auto host = "httpbingo.org";
  3138. auto path = std::string{"/redirect/3"};
  3139. #ifdef CPPHTTPLIB_SSL_ENABLED
  3140. SSLClient cli(host);
  3141. #else
  3142. Client cli(host);
  3143. #endif
  3144. cli.set_follow_location(true);
  3145. auto res = cli.Get(path);
  3146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3147. EXPECT_EQ(StatusCode::OK_200, res->status);
  3148. }
  3149. TEST(RelativeRedirectTest, Redirect_Online) {
  3150. auto host = "httpbingo.org";
  3151. auto path = std::string{"/relative-redirect/3"};
  3152. #ifdef CPPHTTPLIB_SSL_ENABLED
  3153. SSLClient cli(host);
  3154. #else
  3155. Client cli(host);
  3156. #endif
  3157. cli.set_follow_location(true);
  3158. auto res = cli.Get(path);
  3159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3160. EXPECT_EQ(StatusCode::OK_200, res->status);
  3161. }
  3162. TEST(TooManyRedirectTest, Redirect_Online) {
  3163. auto host = "httpbingo.org";
  3164. auto path = std::string{"/redirect/21"};
  3165. #ifdef CPPHTTPLIB_SSL_ENABLED
  3166. SSLClient cli(host);
  3167. #else
  3168. Client cli(host);
  3169. #endif
  3170. cli.set_follow_location(true);
  3171. auto res = cli.Get(path);
  3172. ASSERT_TRUE(!res);
  3173. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3174. }
  3175. #ifdef CPPHTTPLIB_SSL_ENABLED
  3176. TEST(YahooRedirectTest, Redirect_Online) {
  3177. Client cli("yahoo.com");
  3178. auto res = cli.Get("/");
  3179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3180. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3181. cli.set_follow_location(true);
  3182. res = cli.Get("/");
  3183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3184. EXPECT_EQ(StatusCode::OK_200, res->status);
  3185. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3186. }
  3187. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3188. #define REDIR_HOST "httpbingo.org"
  3189. #define REDIR_PATH "/redirect-to"
  3190. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3191. SSLClient cli(REDIR_HOST);
  3192. cli.set_follow_location(true);
  3193. auto res =
  3194. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3196. EXPECT_EQ(StatusCode::OK_200, res->status);
  3197. }
  3198. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3199. SSLClient cli(REDIR_HOST);
  3200. cli.set_follow_location(true);
  3201. Params params;
  3202. params.emplace("url", "http://example.com");
  3203. params.emplace("status_code", "302");
  3204. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3206. EXPECT_EQ(StatusCode::OK_200, res->status);
  3207. }
  3208. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3209. SSLClient cli(REDIR_HOST);
  3210. cli.set_follow_location(true);
  3211. Params params;
  3212. params.emplace("url", "http://example.com");
  3213. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3215. EXPECT_EQ(StatusCode::OK_200, res->status);
  3216. }
  3217. TEST(UrlWithSpace, Redirect_Online) {
  3218. SSLClient cli("edge.forgecdn.net");
  3219. cli.set_follow_location(true);
  3220. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3222. EXPECT_EQ(StatusCode::OK_200, res->status);
  3223. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3224. }
  3225. #endif
  3226. #if !defined(_WIN32) && !defined(_WIN64)
  3227. TEST(ReceiveSignals, Signal) {
  3228. auto setupSignalHandlers = []() {
  3229. struct sigaction act;
  3230. sigemptyset(&act.sa_mask);
  3231. act.sa_flags = SA_SIGINFO;
  3232. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3233. switch (sig) {
  3234. case SIGINT:
  3235. default: break;
  3236. }
  3237. };
  3238. ::sigaction(SIGINT, &act, nullptr);
  3239. };
  3240. Server svr;
  3241. int port = 0;
  3242. auto thread = std::thread([&]() {
  3243. setupSignalHandlers();
  3244. port = svr.bind_to_any_port(HOST);
  3245. svr.listen_after_bind();
  3246. });
  3247. auto se = detail::scope_exit([&] {
  3248. svr.stop();
  3249. thread.join();
  3250. ASSERT_FALSE(svr.is_running());
  3251. });
  3252. svr.wait_until_ready();
  3253. ASSERT_TRUE(svr.is_running());
  3254. pthread_kill(thread.native_handle(), SIGINT);
  3255. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3256. ASSERT_TRUE(svr.is_running());
  3257. }
  3258. #endif
  3259. TEST(RedirectToDifferentPort, Redirect) {
  3260. Server svr1;
  3261. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3262. res.set_content("Hello World!", "text/plain");
  3263. });
  3264. int svr1_port = 0;
  3265. auto thread1 = std::thread([&]() {
  3266. svr1_port = svr1.bind_to_any_port(HOST);
  3267. svr1.listen_after_bind();
  3268. });
  3269. Server svr2;
  3270. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3271. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3272. });
  3273. int svr2_port = 0;
  3274. auto thread2 = std::thread([&]() {
  3275. svr2_port = svr2.bind_to_any_port(HOST);
  3276. svr2.listen_after_bind();
  3277. });
  3278. auto se = detail::scope_exit([&] {
  3279. svr2.stop();
  3280. thread2.join();
  3281. svr1.stop();
  3282. thread1.join();
  3283. ASSERT_FALSE(svr2.is_running());
  3284. ASSERT_FALSE(svr1.is_running());
  3285. });
  3286. svr1.wait_until_ready();
  3287. svr2.wait_until_ready();
  3288. Client cli("localhost", svr2_port);
  3289. cli.set_follow_location(true);
  3290. auto res = cli.Get("/2");
  3291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3292. EXPECT_EQ(StatusCode::OK_200, res->status);
  3293. EXPECT_EQ("Hello World!", res->body);
  3294. }
  3295. // GET /redir on one server redirects to /target on another port, so the
  3296. // client follows it with a new client.
  3297. static Result
  3298. GetThroughRedirectToDifferentPort(Server::Handler target,
  3299. const std::function<void(Client &)> &setup,
  3300. const Headers &headers = Headers()) {
  3301. Server target_svr;
  3302. target_svr.Get("/target", target);
  3303. int target_port = 0;
  3304. auto target_thread = std::thread([&]() {
  3305. target_port = target_svr.bind_to_any_port(HOST);
  3306. target_svr.listen_after_bind();
  3307. });
  3308. Server origin_svr;
  3309. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3310. res.set_redirect(
  3311. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3312. });
  3313. int origin_port = 0;
  3314. auto origin_thread = std::thread([&]() {
  3315. origin_port = origin_svr.bind_to_any_port(HOST);
  3316. origin_svr.listen_after_bind();
  3317. });
  3318. auto se = detail::scope_exit([&] {
  3319. origin_svr.stop();
  3320. origin_thread.join();
  3321. target_svr.stop();
  3322. target_thread.join();
  3323. });
  3324. target_svr.wait_until_ready();
  3325. origin_svr.wait_until_ready();
  3326. Client cli("localhost", origin_port);
  3327. cli.set_follow_location(true);
  3328. setup(cli);
  3329. return cli.Get("/redir", headers);
  3330. }
  3331. static void
  3332. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3333. std::string captured_authorization;
  3334. auto result = GetThroughRedirectToDifferentPort(
  3335. [&](const Request &req, Response &res) {
  3336. captured_authorization = req.get_header_value("Authorization");
  3337. res.set_content("OK", "text/plain");
  3338. },
  3339. set_auth);
  3340. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3341. EXPECT_EQ(StatusCode::OK_200, result->status);
  3342. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3343. EXPECT_TRUE(captured_authorization.empty());
  3344. }
  3345. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3346. TestDoNotForwardCredentialsOnRedirect(
  3347. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3348. }
  3349. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3350. TestDoNotForwardCredentialsOnRedirect(
  3351. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3352. }
  3353. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3354. std::string captured_cookie;
  3355. auto result = GetThroughRedirectToDifferentPort(
  3356. [&](const Request &req, Response &res) {
  3357. captured_cookie = req.get_header_value("Cookie");
  3358. res.set_content("OK", "text/plain");
  3359. },
  3360. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3361. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3362. EXPECT_EQ(StatusCode::OK_200, result->status);
  3363. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3364. EXPECT_TRUE(captured_cookie.empty());
  3365. }
  3366. TEST(RedirectToSamePort, ForwardCookie) {
  3367. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3368. // header so that ordinary session flows keep working.
  3369. Server svr;
  3370. std::string captured_cookie;
  3371. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3372. res.set_redirect("/target", 302);
  3373. });
  3374. svr.Get("/target", [&](const Request &req, Response &res) {
  3375. captured_cookie = req.get_header_value("Cookie");
  3376. res.set_content("OK", "text/plain");
  3377. });
  3378. auto port = svr.bind_to_any_port(HOST);
  3379. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3380. auto se = detail::scope_exit([&] {
  3381. svr.stop();
  3382. thread.join();
  3383. ASSERT_FALSE(svr.is_running());
  3384. });
  3385. svr.wait_until_ready();
  3386. Client cli(HOST, port);
  3387. cli.set_follow_location(true);
  3388. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3389. auto res = cli.Get("/redir", headers);
  3390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3391. EXPECT_EQ(StatusCode::OK_200, res->status);
  3392. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3393. }
  3394. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3395. std::string authorization;
  3396. std::string trace_id;
  3397. auto result = GetThroughRedirectToDifferentPort(
  3398. [&](const Request &req, Response &res) {
  3399. authorization = req.get_header_value("Authorization");
  3400. trace_id = req.get_header_value("X-Trace-Id");
  3401. res.set_content("OK", "text/plain");
  3402. },
  3403. [](Client &cli) {
  3404. cli.set_default_headers(
  3405. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3406. });
  3407. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3408. EXPECT_EQ(StatusCode::OK_200, result->status);
  3409. // Like a header given with the request, a default one goes along unless it
  3410. // carries credentials (RFC 9110 15.4).
  3411. EXPECT_TRUE(authorization.empty());
  3412. EXPECT_EQ("42", trace_id);
  3413. }
  3414. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3415. auto result = GetThroughRedirectToDifferentPort(
  3416. [](const Request &, Response &res) {
  3417. res.set_content(std::string(2048, 'x'), "text/plain");
  3418. },
  3419. [](Client &cli) { cli.set_payload_max_length(1024); });
  3420. EXPECT_FALSE(result);
  3421. }
  3422. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3423. auto result = GetThroughRedirectToDifferentPort(
  3424. [](const Request &req, Response &res) {
  3425. // Answer after a second, or once the client gives up.
  3426. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3427. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3428. }
  3429. res.set_content("late", "text/plain");
  3430. },
  3431. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3432. ASSERT_FALSE(result);
  3433. EXPECT_EQ(Error::Read, result.error());
  3434. }
  3435. #ifdef CPPHTTPLIB_SSL_ENABLED
  3436. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3437. auto result = GetThroughRedirectToDifferentPort(
  3438. [](const Request &, Response &res) {
  3439. res.status = StatusCode::Unauthorized_401;
  3440. res.set_header("WWW-Authenticate",
  3441. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3442. },
  3443. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3444. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3445. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3446. }
  3447. #endif
  3448. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3449. Server svr;
  3450. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3451. // Port number that overflows int — should not crash
  3452. res.set_redirect("http://localhost:99999999999999999999/target");
  3453. });
  3454. auto port = svr.bind_to_any_port(HOST);
  3455. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3456. auto se = detail::scope_exit([&] {
  3457. svr.stop();
  3458. thread.join();
  3459. ASSERT_FALSE(svr.is_running());
  3460. });
  3461. svr.wait_until_ready();
  3462. Client cli(HOST, port);
  3463. cli.set_follow_location(true);
  3464. auto res = cli.Get("/redir");
  3465. // Should fail gracefully, not crash (no valid response due to bad port)
  3466. EXPECT_FALSE(res);
  3467. }
  3468. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3469. Server svr;
  3470. auto port = svr.bind_to_any_port(HOST);
  3471. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3472. // The server's own port followed by junk must not be followed
  3473. res.set_redirect("http://" + std::string(HOST) + ":" +
  3474. std::to_string(port) + "junk/target");
  3475. });
  3476. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3477. res.set_content("target", "text/plain");
  3478. });
  3479. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3480. auto se = detail::scope_exit([&] {
  3481. svr.stop();
  3482. thread.join();
  3483. ASSERT_FALSE(svr.is_running());
  3484. });
  3485. svr.wait_until_ready();
  3486. Client cli(HOST, port);
  3487. cli.set_follow_location(true);
  3488. auto res = cli.Get("/redir");
  3489. EXPECT_FALSE(res);
  3490. }
  3491. TEST(RedirectFromPageWithContent, Redirect) {
  3492. Server svr;
  3493. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3494. res.set_content("___", "text/plain");
  3495. res.set_redirect("/2");
  3496. });
  3497. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3498. res.set_content("Hello World!", "text/plain");
  3499. });
  3500. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3501. auto se = detail::scope_exit([&] {
  3502. svr.stop();
  3503. th.join();
  3504. ASSERT_FALSE(svr.is_running());
  3505. });
  3506. svr.wait_until_ready();
  3507. {
  3508. Client cli("localhost", PORT);
  3509. cli.set_follow_location(true);
  3510. std::string body;
  3511. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3512. body.append(data, data_length);
  3513. return true;
  3514. });
  3515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3516. EXPECT_EQ(StatusCode::OK_200, res->status);
  3517. EXPECT_EQ("Hello World!", body);
  3518. }
  3519. {
  3520. Client cli("localhost", PORT);
  3521. std::string body;
  3522. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3523. body.append(data, data_length);
  3524. return true;
  3525. });
  3526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3527. EXPECT_EQ(StatusCode::Found_302, res->status);
  3528. EXPECT_EQ("___", body);
  3529. }
  3530. }
  3531. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3532. Server svr;
  3533. auto port_str = std::to_string(PORT);
  3534. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3535. auto expected_host = "[::1]:" + port_str;
  3536. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3537. res.set_content("___", "text/plain");
  3538. // res.set_redirect("/2");
  3539. res.set_redirect(redirect_url);
  3540. });
  3541. svr.Get("/2", [&](const Request &req, Response &res) {
  3542. auto host_header = req.headers.find("Host");
  3543. ASSERT_TRUE(host_header != req.headers.end());
  3544. EXPECT_EQ(expected_host, host_header->second);
  3545. res.set_content("Hello World!", "text/plain");
  3546. });
  3547. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3548. auto se = detail::scope_exit([&] {
  3549. svr.stop();
  3550. th.join();
  3551. ASSERT_FALSE(svr.is_running());
  3552. });
  3553. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3554. // actually starts anything, so the condition !svr.is_running() will
  3555. // always remain true, and the loop never stops.
  3556. // This basically counts how many milliseconds have passed since the
  3557. // call to svr.listen(), and if after 5 seconds nothing started yet
  3558. // aborts the test.
  3559. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3560. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3561. ASSERT_LT(milliseconds, 5000U);
  3562. }
  3563. {
  3564. Client cli("::1", PORT);
  3565. cli.set_follow_location(true);
  3566. std::string body;
  3567. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3568. body.append(data, data_length);
  3569. return true;
  3570. });
  3571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3572. EXPECT_EQ(StatusCode::OK_200, res->status);
  3573. EXPECT_EQ("Hello World!", body);
  3574. }
  3575. {
  3576. Client cli("::1", PORT);
  3577. std::string body;
  3578. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3579. body.append(data, data_length);
  3580. return true;
  3581. });
  3582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3583. EXPECT_EQ(StatusCode::Found_302, res->status);
  3584. EXPECT_EQ("___", body);
  3585. }
  3586. }
  3587. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3588. Server svr;
  3589. svr.Get("/foo", [](const Request &req, Response &res) {
  3590. auto a = req.params.find("a");
  3591. if (a != req.params.end()) {
  3592. res.set_content((*a).second, "text/plain");
  3593. res.status = StatusCode::OK_200;
  3594. } else {
  3595. res.status = StatusCode::BadRequest_400;
  3596. }
  3597. });
  3598. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3599. auto se = detail::scope_exit([&] {
  3600. svr.stop();
  3601. thread.join();
  3602. ASSERT_FALSE(svr.is_running());
  3603. });
  3604. svr.wait_until_ready();
  3605. {
  3606. Client cli(HOST, PORT);
  3607. cli.set_path_encode(false);
  3608. auto res = cli.Get("/foo?a=explicitly+encoded");
  3609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3610. EXPECT_EQ(StatusCode::OK_200, res->status);
  3611. // This expects it back with a space, as the `+` won't have been
  3612. // url-encoded, and server-side the params get decoded turning `+`
  3613. // into spaces.
  3614. EXPECT_EQ("explicitly encoded", res->body);
  3615. }
  3616. }
  3617. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3618. // When path encoding is disabled the client must transmit the supplied
  3619. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3620. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3621. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3622. // than a space (0x20). Assert on the raw wire target to catch this.
  3623. Server svr;
  3624. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3625. svr.Get("/foo", [&](const Request &req, Response &res) {
  3626. EXPECT_EQ(expected_target, req.target);
  3627. res.status = StatusCode::OK_200;
  3628. });
  3629. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3630. auto se = detail::scope_exit([&] {
  3631. svr.stop();
  3632. thread.join();
  3633. ASSERT_FALSE(svr.is_running());
  3634. });
  3635. svr.wait_until_ready();
  3636. {
  3637. Client cli(HOST, PORT);
  3638. cli.set_path_encode(false);
  3639. auto res = cli.Get(expected_target.c_str());
  3640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3641. EXPECT_EQ(StatusCode::OK_200, res->status);
  3642. }
  3643. }
  3644. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3645. // `open_stream()` used to skip the path encoding that the buffered send
  3646. // path applies, so the same `path` produced different bytes in the request
  3647. // line depending on which API was used. Assert the two agree.
  3648. Server svr;
  3649. std::string target;
  3650. svr.Get(".*", [&](const Request &req, Response &res) {
  3651. target = req.target;
  3652. res.status = StatusCode::OK_200;
  3653. });
  3654. auto port = svr.bind_to_any_port(HOST);
  3655. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3656. auto se = detail::scope_exit([&] {
  3657. svr.stop();
  3658. thread.join();
  3659. ASSERT_FALSE(svr.is_running());
  3660. });
  3661. svr.wait_until_ready();
  3662. struct {
  3663. const char *path;
  3664. const char *expected;
  3665. } cases[] = {
  3666. {"/a b?x=1", "/a%20b?x=1"},
  3667. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3668. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3669. };
  3670. for (const auto &c : cases) {
  3671. Client cli(HOST, port);
  3672. target.clear();
  3673. auto res = cli.Get(c.path);
  3674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3675. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3676. auto buffered_target = target;
  3677. target.clear();
  3678. auto handle = cli.open_stream("GET", c.path);
  3679. EXPECT_TRUE(handle.is_valid())
  3680. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3681. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3682. }
  3683. }
  3684. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3685. // The `set_path_encode(false)` contract — transmit the supplied target
  3686. // verbatim — must hold for the streaming API too.
  3687. Server svr;
  3688. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3689. std::string target;
  3690. svr.Get("/foo", [&](const Request &req, Response &res) {
  3691. target = req.target;
  3692. res.status = StatusCode::OK_200;
  3693. });
  3694. auto port = svr.bind_to_any_port(HOST);
  3695. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3696. auto se = detail::scope_exit([&] {
  3697. svr.stop();
  3698. thread.join();
  3699. ASSERT_FALSE(svr.is_running());
  3700. });
  3701. svr.wait_until_ready();
  3702. {
  3703. Client cli(HOST, port);
  3704. cli.set_path_encode(false);
  3705. auto handle = cli.open_stream("GET", expected_target);
  3706. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3707. EXPECT_EQ(expected_target, target);
  3708. }
  3709. }
  3710. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3711. // With path encoding enabled a CR/LF in the target is percent-encoded
  3712. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3713. // write_request_line still backstops `set_path_encode(false)`, which is
  3714. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3715. Server svr;
  3716. // Captured before routing: the decoded path contains a newline, which a
  3717. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3718. std::string target;
  3719. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3720. target = req.target;
  3721. res.status = StatusCode::OK_200;
  3722. return Server::HandlerResponse::Handled;
  3723. });
  3724. auto port = svr.bind_to_any_port(HOST);
  3725. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3726. auto se = detail::scope_exit([&] {
  3727. svr.stop();
  3728. thread.join();
  3729. ASSERT_FALSE(svr.is_running());
  3730. });
  3731. svr.wait_until_ready();
  3732. {
  3733. Client cli(HOST, port);
  3734. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3735. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3736. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3737. }
  3738. }
  3739. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3740. // Every control character is percent-encoded, not just CR/LF, so the target
  3741. // passes the request-target check in write_request_line.
  3742. Server svr;
  3743. std::string target;
  3744. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3745. target = req.target;
  3746. res.status = StatusCode::OK_200;
  3747. return Server::HandlerResponse::Handled;
  3748. });
  3749. auto port = svr.bind_to_any_port(HOST);
  3750. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3751. auto se = detail::scope_exit([&] {
  3752. svr.stop();
  3753. thread.join();
  3754. ASSERT_FALSE(svr.is_running());
  3755. });
  3756. svr.wait_until_ready();
  3757. {
  3758. Client cli(HOST, port);
  3759. auto res = cli.Get("/a\tb\x1b\x7f");
  3760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3761. EXPECT_EQ("/a%09b%1B%7F", target);
  3762. }
  3763. }
  3764. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3765. // Nothing may reach the wire: a raw CR/LF target would split the request
  3766. // line and inject headers.
  3767. Server svr;
  3768. // Pre-routing so that "not called" means nothing reached the server at all,
  3769. // rather than merely failing to match a handler pattern.
  3770. auto handler_called = false;
  3771. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3772. handler_called = true;
  3773. res.status = StatusCode::OK_200;
  3774. return Server::HandlerResponse::Handled;
  3775. });
  3776. auto port = svr.bind_to_any_port(HOST);
  3777. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3778. auto se = detail::scope_exit([&] {
  3779. svr.stop();
  3780. thread.join();
  3781. ASSERT_FALSE(svr.is_running());
  3782. });
  3783. svr.wait_until_ready();
  3784. {
  3785. Client cli(HOST, port);
  3786. cli.set_path_encode(false);
  3787. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3788. EXPECT_FALSE(handle.is_valid());
  3789. EXPECT_EQ(Error::Write, handle.error);
  3790. EXPECT_FALSE(handler_called);
  3791. }
  3792. }
  3793. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3794. // Which of the two branches runs is decided by whether the query component
  3795. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3796. // an empty query and must still fall back to building one from
  3797. // `req.params`, while a non-empty query must win over `req.params`.
  3798. Server svr;
  3799. std::string target;
  3800. svr.Get("/foo", [&](const Request &req, Response &res) {
  3801. target = req.target;
  3802. res.status = StatusCode::OK_200;
  3803. });
  3804. auto port = svr.bind_to_any_port(HOST);
  3805. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3806. auto se = detail::scope_exit([&] {
  3807. svr.stop();
  3808. thread.join();
  3809. ASSERT_FALSE(svr.is_running());
  3810. });
  3811. svr.wait_until_ready();
  3812. {
  3813. // Trailing `?` -> empty query component -> `req.params` is used.
  3814. Client cli(HOST, port);
  3815. Request req;
  3816. req.method = "GET";
  3817. req.path = "/foo?";
  3818. req.params.emplace("a", "1");
  3819. target.clear();
  3820. auto res = cli.send(req);
  3821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3822. EXPECT_EQ("/foo?a=1", target);
  3823. }
  3824. {
  3825. // Non-empty query in `req.path` -> `req.params` is not appended.
  3826. Client cli(HOST, port);
  3827. Request req;
  3828. req.method = "GET";
  3829. req.path = "/foo?b=2";
  3830. req.params.emplace("a", "1");
  3831. target.clear();
  3832. auto res = cli.send(req);
  3833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3834. EXPECT_EQ("/foo?b=2", target);
  3835. }
  3836. }
  3837. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3838. Server svr;
  3839. svr.Get("/", [](const Request &req, Response &) {
  3840. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3841. });
  3842. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3843. auto se = detail::scope_exit([&] {
  3844. svr.stop();
  3845. thread.join();
  3846. ASSERT_FALSE(svr.is_running());
  3847. });
  3848. svr.wait_until_ready();
  3849. {
  3850. Client cli(HOST, PORT);
  3851. cli.set_path_encode(false);
  3852. auto res = cli.Get("/?something=%0A");
  3853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3854. EXPECT_EQ(StatusCode::OK_200, res->status);
  3855. }
  3856. }
  3857. TEST(BindServerTest, BindDualStack) {
  3858. Server svr;
  3859. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3860. res.set_content("Hello World!", "text/plain");
  3861. });
  3862. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3863. auto se = detail::scope_exit([&] {
  3864. svr.stop();
  3865. thread.join();
  3866. ASSERT_FALSE(svr.is_running());
  3867. });
  3868. svr.wait_until_ready();
  3869. {
  3870. Client cli("127.0.0.1", PORT);
  3871. auto res = cli.Get("/1");
  3872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3873. EXPECT_EQ(StatusCode::OK_200, res->status);
  3874. EXPECT_EQ("Hello World!", res->body);
  3875. }
  3876. {
  3877. Client cli("::1", PORT);
  3878. auto res = cli.Get("/1");
  3879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3880. EXPECT_EQ(StatusCode::OK_200, res->status);
  3881. EXPECT_EQ("Hello World!", res->body);
  3882. }
  3883. }
  3884. TEST(BindServerTest, BindAndListenSeparately) {
  3885. Server svr;
  3886. int port = svr.bind_to_any_port("0.0.0.0");
  3887. ASSERT_TRUE(svr.is_valid());
  3888. ASSERT_TRUE(port > 0);
  3889. svr.stop();
  3890. }
  3891. // Reports whether anything is still listening on a loopback port. A plain
  3892. // connect() is used instead of a Client request because a socket left bound by
  3893. // mistake accepts the connection into its backlog and never answers, which
  3894. // would hang the test instead of failing it.
  3895. static bool is_loopback_port_accepting(int port) {
  3896. sockaddr_in addr{};
  3897. addr.sin_family = AF_INET;
  3898. addr.sin_port = htons(static_cast<uint16_t>(port));
  3899. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3900. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3901. EXPECT_NE(sock, INVALID_SOCKET);
  3902. if (sock == INVALID_SOCKET) { return false; }
  3903. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3904. static_cast<socklen_t>(sizeof(addr)));
  3905. detail::close_socket(sock);
  3906. return ret == 0;
  3907. }
  3908. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3909. Server svr;
  3910. auto port = svr.bind_to_any_port("127.0.0.1");
  3911. ASSERT_TRUE(port > 0);
  3912. svr.stop();
  3913. // bind_to_any_port() already called listen(2), so until stop() closed the
  3914. // descriptor the port kept accepting connections into the backlog. ASSERT
  3915. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3916. // below blocks forever in the accept loop.
  3917. ASSERT_FALSE(is_loopback_port_accepting(port));
  3918. // Nothing is left to accept on, so listen_after_bind() must report failure
  3919. // instead of returning success without ever serving.
  3920. EXPECT_FALSE(svr.listen_after_bind());
  3921. // The failed listen marks the server decommissioned, so a waiter returns
  3922. // instead of spinning forever.
  3923. svr.wait_until_ready();
  3924. }
  3925. #ifdef CPPHTTPLIB_SSL_ENABLED
  3926. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3927. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3928. CLIENT_CA_CERT_DIR);
  3929. int port = svr.bind_to_any_port("0.0.0.0");
  3930. ASSERT_TRUE(svr.is_valid());
  3931. ASSERT_TRUE(port > 0);
  3932. svr.stop();
  3933. }
  3934. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3935. // or a rejected CustomRoute() registration would not stop the server binding.
  3936. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3937. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3938. CLIENT_CA_CERT_DIR);
  3939. ASSERT_TRUE(svr.is_valid());
  3940. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3941. EXPECT_FALSE(svr.is_valid());
  3942. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3943. }
  3944. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3945. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3946. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3947. int port = svr.bind_to_any_port("0.0.0.0");
  3948. ASSERT_TRUE(svr.is_valid());
  3949. ASSERT_TRUE(port > 0);
  3950. svr.stop();
  3951. }
  3952. TEST(BindServerTest, UpdateCertsPem) {
  3953. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3954. int port = svr.bind_to_any_port("0.0.0.0");
  3955. ASSERT_TRUE(svr.is_valid());
  3956. ASSERT_TRUE(port > 0);
  3957. // Read PEM files
  3958. std::string cert_pem, key_pem, ca_pem;
  3959. read_file(SERVER_CERT_FILE, cert_pem);
  3960. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3961. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3962. // Update server certificates using PEM API
  3963. ASSERT_TRUE(
  3964. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3965. ASSERT_TRUE(svr.is_valid());
  3966. svr.stop();
  3967. }
  3968. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3969. // Start server with client CA (enables client auth)
  3970. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3971. ASSERT_TRUE(svr.is_valid());
  3972. bool handler_called = false;
  3973. svr.Get("/test", [&](const Request &req, Response &res) {
  3974. handler_called = true;
  3975. // Verify client certificate is present
  3976. auto cert = req.peer_cert();
  3977. EXPECT_TRUE(static_cast<bool>(cert));
  3978. res.set_content("ok", "text/plain");
  3979. });
  3980. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3981. auto se = detail::scope_exit([&] {
  3982. svr.stop();
  3983. t.join();
  3984. ASSERT_FALSE(svr.is_running());
  3985. });
  3986. svr.wait_until_ready();
  3987. // Read PEM files
  3988. std::string cert_pem, key_pem, ca_pem;
  3989. read_file(SERVER_CERT_FILE, cert_pem);
  3990. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3991. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3992. // Update server certificates and client CA using PEM API while server running
  3993. ASSERT_TRUE(
  3994. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3995. // Connect with client certificate
  3996. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3997. cli.enable_server_certificate_verification(false);
  3998. cli.set_connection_timeout(30);
  3999. auto res = cli.Get("/test");
  4000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4001. ASSERT_EQ(StatusCode::OK_200, res->status);
  4002. ASSERT_TRUE(handler_called);
  4003. EXPECT_EQ("ok", res->body);
  4004. }
  4005. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4006. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4007. ASSERT_TRUE(svr.is_valid());
  4008. svr.Get("/test", [](const Request &, Response &res) {
  4009. res.set_content("ok", "text/plain");
  4010. });
  4011. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4012. auto se = detail::scope_exit([&] {
  4013. svr.stop();
  4014. t.join();
  4015. ASSERT_FALSE(svr.is_running());
  4016. });
  4017. svr.wait_until_ready();
  4018. auto get = [] {
  4019. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4020. cli.enable_server_certificate_verification(false);
  4021. return cli.Get("/test");
  4022. };
  4023. ASSERT_TRUE(get());
  4024. // A CA that did not sign the client's certificate takes the old one's place.
  4025. std::string cert_pem, key_pem, ca_pem;
  4026. read_file(SERVER_CERT_FILE, cert_pem);
  4027. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4028. read_file(SERVER_CERT2_FILE, ca_pem);
  4029. ASSERT_TRUE(
  4030. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4031. EXPECT_FALSE(get());
  4032. }
  4033. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4034. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4035. ASSERT_TRUE(svr.is_valid());
  4036. svr.Get("/test", [](const Request &, Response &res) {
  4037. res.set_content("ok", "text/plain");
  4038. });
  4039. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4040. auto se = detail::scope_exit([&] {
  4041. svr.stop();
  4042. t.join();
  4043. ASSERT_FALSE(svr.is_running());
  4044. });
  4045. svr.wait_until_ready();
  4046. // A connection that sends no ClientHello keeps its handshake in progress,
  4047. // once the server has had a moment to start it.
  4048. auto error = Error::Success;
  4049. auto sock = detail::create_client_socket(
  4050. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4051. /*connection_timeout_sec=*/5, 0,
  4052. /*read_timeout_sec=*/5, 0,
  4053. /*write_timeout_sec=*/5, 0, std::string(), error);
  4054. ASSERT_NE(INVALID_SOCKET, sock);
  4055. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4056. std::string cert_pem, key_pem;
  4057. read_file(SERVER_CERT_FILE, cert_pem);
  4058. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4059. auto update = std::async(std::launch::async, [&]() {
  4060. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4061. });
  4062. EXPECT_EQ(std::future_status::timeout,
  4063. update.wait_for(std::chrono::milliseconds(200)));
  4064. detail::close_socket(sock);
  4065. EXPECT_TRUE(update.get());
  4066. SSLClient cli(HOST, PORT);
  4067. cli.enable_server_certificate_verification(false);
  4068. auto res = cli.Get("/test");
  4069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4070. EXPECT_EQ(StatusCode::OK_200, res->status);
  4071. }
  4072. #endif
  4073. TEST(ErrorHandlerTest, ContentLength) {
  4074. Server svr;
  4075. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4076. res.status = StatusCode::OK_200;
  4077. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4078. "text/html"); // <= Content-Length still 13
  4079. });
  4080. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4081. res.set_content("Hello World!\n", "text/plain");
  4082. res.status = 524;
  4083. });
  4084. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4085. auto se = detail::scope_exit([&] {
  4086. svr.stop();
  4087. thread.join();
  4088. ASSERT_FALSE(svr.is_running());
  4089. });
  4090. svr.wait_until_ready();
  4091. {
  4092. Client cli(HOST, PORT);
  4093. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4095. EXPECT_EQ(StatusCode::OK_200, res->status);
  4096. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4097. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4098. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4099. }
  4100. }
  4101. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4102. TEST(ExceptionTest, WithoutExceptionHandler) {
  4103. Server svr;
  4104. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4105. throw std::runtime_error("exception...");
  4106. });
  4107. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4108. throw std::runtime_error("exception\r\n...");
  4109. });
  4110. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4111. auto se = detail::scope_exit([&] {
  4112. svr.stop();
  4113. listen_thread.join();
  4114. ASSERT_FALSE(svr.is_running());
  4115. });
  4116. svr.wait_until_ready();
  4117. Client cli("localhost", PORT);
  4118. {
  4119. auto res = cli.Get("/exception");
  4120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4121. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4122. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4123. }
  4124. {
  4125. auto res = cli.Get("/unknown");
  4126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4127. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4128. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4129. }
  4130. }
  4131. TEST(ExceptionTest, WithExceptionHandler) {
  4132. Server svr;
  4133. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4134. std::exception_ptr ep) {
  4135. EXPECT_FALSE(ep == nullptr);
  4136. try {
  4137. std::rethrow_exception(ep);
  4138. } catch (std::exception &e) {
  4139. EXPECT_EQ("abc", std::string(e.what()));
  4140. } catch (...) {}
  4141. res.status = StatusCode::InternalServerError_500;
  4142. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4143. "text/html"); // <= Content-Length still 13 at this point
  4144. });
  4145. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4146. res.set_content("Hello World!\n", "text/plain");
  4147. throw std::runtime_error("abc");
  4148. });
  4149. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4150. auto se = detail::scope_exit([&] {
  4151. svr.stop();
  4152. thread.join();
  4153. ASSERT_FALSE(svr.is_running());
  4154. });
  4155. svr.wait_until_ready();
  4156. for (size_t i = 0; i < 10; i++) {
  4157. Client cli(HOST, PORT);
  4158. for (size_t j = 0; j < 100; j++) {
  4159. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4161. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4162. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4163. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4164. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4165. }
  4166. cli.set_keep_alive(true);
  4167. for (size_t j = 0; j < 100; j++) {
  4168. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4170. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4171. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4172. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4173. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4174. }
  4175. }
  4176. }
  4177. TEST(ExceptionTest, AndErrorHandler) {
  4178. Server svr;
  4179. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4180. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4181. });
  4182. svr.set_exception_handler(
  4183. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4184. EXPECT_FALSE(ep == nullptr);
  4185. try {
  4186. std::rethrow_exception(ep);
  4187. } catch (std::exception &e) {
  4188. res.set_content(e.what(), "text/html");
  4189. } catch (...) {}
  4190. res.status = StatusCode::InternalServerError_500;
  4191. });
  4192. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4193. throw std::runtime_error("EXCEPTION");
  4194. });
  4195. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4196. res.set_content("ERROR", "text/html");
  4197. res.status = StatusCode::InternalServerError_500;
  4198. });
  4199. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4200. auto se = detail::scope_exit([&] {
  4201. svr.stop();
  4202. thread.join();
  4203. ASSERT_FALSE(svr.is_running());
  4204. });
  4205. svr.wait_until_ready();
  4206. Client cli(HOST, PORT);
  4207. {
  4208. auto res = cli.Get("/exception");
  4209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4210. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4211. EXPECT_EQ("EXCEPTION", res->body);
  4212. }
  4213. {
  4214. auto res = cli.Get("/error");
  4215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4216. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4217. EXPECT_EQ("ERROR", res->body);
  4218. }
  4219. {
  4220. auto res = cli.Get("/invalid");
  4221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4222. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4223. EXPECT_EQ("NOT_FOUND", res->body);
  4224. }
  4225. }
  4226. #endif
  4227. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4228. // process_request() wraps only routing() in a try/catch, so an exception from
  4229. // any other user callback used to unwind into the task queue - which does not
  4230. // catch - and terminate the process. Each test below runs the server on a
  4231. // single worker thread: a guard that catches the exception but still loses the
  4232. // thread would otherwise be hidden by a spare worker serving the follow-up
  4233. // request. Note that a regression here aborts the whole test binary rather
  4234. // than failing one test.
  4235. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4236. Server svr;
  4237. svr.new_task_queue = [] { return new ThreadPool(1); };
  4238. std::atomic<int> reported{0};
  4239. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4240. if (err == Error::UserCallbackException) { reported++; }
  4241. });
  4242. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4243. res.set_content_provider(
  4244. 1024, "text/plain",
  4245. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4246. sink.write("hello", 5);
  4247. throw std::runtime_error("from the content provider");
  4248. });
  4249. });
  4250. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4251. res.set_content("ok", "text/plain");
  4252. });
  4253. auto port = svr.bind_to_any_port(HOST);
  4254. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4255. auto se = detail::scope_exit([&] {
  4256. svr.stop();
  4257. listen_thread.join();
  4258. ASSERT_FALSE(svr.is_running());
  4259. });
  4260. svr.wait_until_ready();
  4261. {
  4262. Client cli(HOST, port);
  4263. cli.set_read_timeout(5, 0);
  4264. EXPECT_FALSE(cli.Get("/throw"));
  4265. }
  4266. EXPECT_TRUE(svr.is_running());
  4267. EXPECT_EQ(1, reported.load());
  4268. // A request on a fresh connection is still served.
  4269. {
  4270. Client cli(HOST, port);
  4271. auto res = cli.Get("/ok");
  4272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4273. EXPECT_EQ(StatusCode::OK_200, res->status);
  4274. EXPECT_EQ("ok", res->body);
  4275. }
  4276. }
  4277. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4278. Server svr;
  4279. svr.new_task_queue = [] { return new ThreadPool(1); };
  4280. std::atomic<bool> should_throw{true};
  4281. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4282. res.set_content("hi", "text/plain");
  4283. });
  4284. svr.set_post_routing_handler(
  4285. [&](const Request & /*req*/, Response & /*res*/) {
  4286. if (should_throw) {
  4287. throw std::runtime_error("from the post-routing handler");
  4288. }
  4289. });
  4290. auto port = svr.bind_to_any_port(HOST);
  4291. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4292. auto se = detail::scope_exit([&] {
  4293. svr.stop();
  4294. listen_thread.join();
  4295. ASSERT_FALSE(svr.is_running());
  4296. });
  4297. svr.wait_until_ready();
  4298. {
  4299. Client cli(HOST, port);
  4300. cli.set_read_timeout(5, 0);
  4301. EXPECT_FALSE(cli.Get("/hi"));
  4302. }
  4303. EXPECT_TRUE(svr.is_running());
  4304. should_throw = false;
  4305. {
  4306. Client cli(HOST, port);
  4307. auto res = cli.Get("/hi");
  4308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4309. EXPECT_EQ(StatusCode::OK_200, res->status);
  4310. EXPECT_EQ("hi", res->body);
  4311. }
  4312. }
  4313. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4314. // The guard reports the caught exception through the error logger, which is
  4315. // a user callback too. A logger that throws has to be contained as well, or
  4316. // the process would terminate from inside the catch.
  4317. Server svr;
  4318. svr.new_task_queue = [] { return new ThreadPool(1); };
  4319. std::atomic<int> reported{0};
  4320. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4321. if (err == Error::UserCallbackException) {
  4322. reported++;
  4323. throw std::runtime_error("from the error logger");
  4324. }
  4325. });
  4326. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4327. res.set_content_provider(
  4328. 1024, "text/plain",
  4329. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4330. sink.write("hello", 5);
  4331. throw std::runtime_error("from the content provider");
  4332. });
  4333. });
  4334. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4335. res.set_content("ok", "text/plain");
  4336. });
  4337. auto port = svr.bind_to_any_port(HOST);
  4338. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4339. auto se = detail::scope_exit([&] {
  4340. svr.stop();
  4341. listen_thread.join();
  4342. ASSERT_FALSE(svr.is_running());
  4343. });
  4344. svr.wait_until_ready();
  4345. {
  4346. Client cli(HOST, port);
  4347. cli.set_read_timeout(5, 0);
  4348. EXPECT_FALSE(cli.Get("/throw"));
  4349. }
  4350. EXPECT_TRUE(svr.is_running());
  4351. EXPECT_EQ(1, reported.load());
  4352. {
  4353. Client cli(HOST, port);
  4354. auto res = cli.Get("/ok");
  4355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4356. EXPECT_EQ(StatusCode::OK_200, res->status);
  4357. EXPECT_EQ("ok", res->body);
  4358. }
  4359. }
  4360. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4361. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4362. // so the exception unwinds through the ws::WebSocket object on its way to
  4363. // the guard. None of the HTTP cases above cross that.
  4364. Server svr;
  4365. svr.new_task_queue = [] { return new ThreadPool(1); };
  4366. std::atomic<int> reported{0};
  4367. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4368. if (err == Error::UserCallbackException) { reported++; }
  4369. });
  4370. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4371. throw std::runtime_error("from the WebSocket handler");
  4372. });
  4373. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4374. res.set_content("ok", "text/plain");
  4375. });
  4376. auto port = svr.bind_to_any_port(HOST);
  4377. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4378. auto se = detail::scope_exit([&] {
  4379. svr.stop();
  4380. listen_thread.join();
  4381. ASSERT_FALSE(svr.is_running());
  4382. });
  4383. svr.wait_until_ready();
  4384. {
  4385. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4386. "/ws");
  4387. auto res = client.connect();
  4388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4389. // The server dropped the connection instead of dying.
  4390. std::string msg;
  4391. EXPECT_FALSE(client.read(msg));
  4392. client.close();
  4393. }
  4394. EXPECT_TRUE(svr.is_running());
  4395. EXPECT_EQ(1, reported.load());
  4396. {
  4397. Client cli(HOST, port);
  4398. auto res = cli.Get("/ok");
  4399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4400. EXPECT_EQ(StatusCode::OK_200, res->status);
  4401. EXPECT_EQ("ok", res->body);
  4402. }
  4403. }
  4404. #ifdef CPPHTTPLIB_SSL_ENABLED
  4405. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4406. // SSLServer::process_and_close_socket() is a separate overload with its own
  4407. // guard, so it is exercised on its own.
  4408. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4409. ASSERT_TRUE(svr.is_valid());
  4410. svr.new_task_queue = [] { return new ThreadPool(1); };
  4411. std::atomic<int> reported{0};
  4412. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4413. if (err == Error::UserCallbackException) { reported++; }
  4414. });
  4415. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4416. res.set_content_provider(
  4417. 1024, "text/plain",
  4418. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4419. sink.write("hello", 5);
  4420. throw std::runtime_error("from the content provider");
  4421. });
  4422. });
  4423. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4424. res.set_content("ok", "text/plain");
  4425. });
  4426. auto port = svr.bind_to_any_port(HOST);
  4427. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4428. auto se = detail::scope_exit([&] {
  4429. svr.stop();
  4430. listen_thread.join();
  4431. ASSERT_FALSE(svr.is_running());
  4432. });
  4433. svr.wait_until_ready();
  4434. {
  4435. SSLClient cli(HOST, port);
  4436. cli.enable_server_certificate_verification(false);
  4437. cli.set_read_timeout(5, 0);
  4438. EXPECT_FALSE(cli.Get("/throw"));
  4439. }
  4440. EXPECT_TRUE(svr.is_running());
  4441. EXPECT_EQ(1, reported.load());
  4442. {
  4443. SSLClient cli(HOST, port);
  4444. cli.enable_server_certificate_verification(false);
  4445. auto res = cli.Get("/ok");
  4446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4447. EXPECT_EQ(StatusCode::OK_200, res->status);
  4448. EXPECT_EQ("ok", res->body);
  4449. }
  4450. }
  4451. #endif
  4452. #endif
  4453. TEST(NoContentTest, ContentLength) {
  4454. Server svr;
  4455. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4456. res.status = StatusCode::NoContent_204;
  4457. });
  4458. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4459. auto se = detail::scope_exit([&] {
  4460. svr.stop();
  4461. thread.join();
  4462. ASSERT_FALSE(svr.is_running());
  4463. });
  4464. svr.wait_until_ready();
  4465. {
  4466. Client cli(HOST, PORT);
  4467. auto res = cli.Get("/hi");
  4468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4469. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4470. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4471. }
  4472. }
  4473. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4474. #ifdef CPPHTTPLIB_SSL_ENABLED
  4475. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4476. ASSERT_TRUE(svr.is_valid());
  4477. #else
  4478. Server svr;
  4479. #endif
  4480. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4481. if (req.path == "/routing_handler") {
  4482. res.set_header("PRE_ROUTING", "on");
  4483. res.set_content("Routing Handler", "text/plain");
  4484. return httplib::Server::HandlerResponse::Handled;
  4485. }
  4486. return httplib::Server::HandlerResponse::Unhandled;
  4487. });
  4488. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4489. res.set_content("Error", "text/html");
  4490. });
  4491. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4492. if (req.path == "/routing_handler") {
  4493. res.set_header("POST_ROUTING", "on");
  4494. }
  4495. });
  4496. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4497. res.set_content("Hello World!\n", "text/plain");
  4498. });
  4499. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4500. auto se = detail::scope_exit([&] {
  4501. svr.stop();
  4502. thread.join();
  4503. ASSERT_FALSE(svr.is_running());
  4504. });
  4505. svr.wait_until_ready();
  4506. {
  4507. #ifdef CPPHTTPLIB_SSL_ENABLED
  4508. SSLClient cli(HOST, PORT);
  4509. cli.enable_server_certificate_verification(false);
  4510. #else
  4511. Client cli(HOST, PORT);
  4512. #endif
  4513. auto res = cli.Get("/routing_handler");
  4514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4515. EXPECT_EQ(StatusCode::OK_200, res->status);
  4516. EXPECT_EQ("Routing Handler", res->body);
  4517. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4518. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4519. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4520. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4521. }
  4522. {
  4523. #ifdef CPPHTTPLIB_SSL_ENABLED
  4524. SSLClient cli(HOST, PORT);
  4525. cli.enable_server_certificate_verification(false);
  4526. #else
  4527. Client cli(HOST, PORT);
  4528. #endif
  4529. auto res = cli.Get("/hi");
  4530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4531. EXPECT_EQ(StatusCode::OK_200, res->status);
  4532. EXPECT_EQ("Hello World!\n", res->body);
  4533. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4534. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4535. }
  4536. {
  4537. #ifdef CPPHTTPLIB_SSL_ENABLED
  4538. SSLClient cli(HOST, PORT);
  4539. cli.enable_server_certificate_verification(false);
  4540. #else
  4541. Client cli(HOST, PORT);
  4542. #endif
  4543. auto res = cli.Get("/aaa");
  4544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4545. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4546. EXPECT_EQ("Error", res->body);
  4547. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4548. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4549. }
  4550. }
  4551. TEST(RequestHandlerTest, PreRequestHandler) {
  4552. auto route_path = "/user/:user";
  4553. Server svr;
  4554. svr.Get("/hi", [](const Request &, Response &res) {
  4555. res.set_content("hi", "text/plain");
  4556. });
  4557. svr.Get(route_path, [](const Request &req, Response &res) {
  4558. res.set_content(req.path_params.at("user"), "text/plain");
  4559. });
  4560. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4561. if (req.matched_route == route_path) {
  4562. auto user = req.path_params.at("user");
  4563. if (user != "john") {
  4564. res.status = StatusCode::Forbidden_403;
  4565. res.set_content("error", "text/html");
  4566. return Server::HandlerResponse::Handled;
  4567. }
  4568. }
  4569. return Server::HandlerResponse::Unhandled;
  4570. });
  4571. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4572. auto se = detail::scope_exit([&] {
  4573. svr.stop();
  4574. thread.join();
  4575. ASSERT_FALSE(svr.is_running());
  4576. });
  4577. svr.wait_until_ready();
  4578. Client cli(HOST, PORT);
  4579. {
  4580. auto res = cli.Get("/hi");
  4581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4582. EXPECT_EQ(StatusCode::OK_200, res->status);
  4583. EXPECT_EQ("hi", res->body);
  4584. }
  4585. {
  4586. auto res = cli.Get("/user/john");
  4587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4588. EXPECT_EQ(StatusCode::OK_200, res->status);
  4589. EXPECT_EQ("john", res->body);
  4590. }
  4591. {
  4592. auto res = cli.Get("/user/invalid-user");
  4593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4594. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4595. EXPECT_EQ("error", res->body);
  4596. }
  4597. }
  4598. // The pre-request handler must run before the request body is read, so a
  4599. // rejected request never forces the server to buffer a (potentially large)
  4600. // body. Here the posted body is larger than the payload limit: if the body
  4601. // were read first the server would answer 413, but because the pre-request
  4602. // handler runs first it answers 403 and the body is never read.
  4603. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4604. Server svr;
  4605. svr.set_payload_max_length(8);
  4606. auto handler_ran = false;
  4607. svr.Post("/reject", [&](const Request &req, Response &res) {
  4608. handler_ran = true;
  4609. res.set_content(req.body, "text/plain");
  4610. });
  4611. svr.Post("/accept", [](const Request &req, Response &res) {
  4612. res.set_content(req.body, "text/plain");
  4613. });
  4614. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4615. if (req.matched_route == "/reject") {
  4616. res.status = StatusCode::Forbidden_403;
  4617. res.set_content("denied", "text/plain");
  4618. return Server::HandlerResponse::Handled;
  4619. }
  4620. return Server::HandlerResponse::Unhandled;
  4621. });
  4622. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4623. auto se = detail::scope_exit([&] {
  4624. svr.stop();
  4625. thread.join();
  4626. ASSERT_FALSE(svr.is_running());
  4627. });
  4628. svr.wait_until_ready();
  4629. Client cli(HOST, PORT);
  4630. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4631. // rejects with 403 before the body is read, so 413 is never reached.
  4632. {
  4633. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4635. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4636. EXPECT_EQ("denied", res->body);
  4637. EXPECT_FALSE(handler_ran);
  4638. }
  4639. // An approved route still reads the body and enforces the payload limit.
  4640. {
  4641. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4643. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4644. }
  4645. }
  4646. TEST(UserDataTest, BasicOperations) {
  4647. httplib::UserData ud;
  4648. // Initially empty
  4649. EXPECT_FALSE(ud.has("key"));
  4650. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4651. // set and get
  4652. ud.set("key", 42);
  4653. EXPECT_TRUE(ud.has("key"));
  4654. auto *p = ud.get<int>("key");
  4655. ASSERT_NE(nullptr, p);
  4656. EXPECT_EQ(42, *p);
  4657. // Type mismatch → nullptr
  4658. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4659. // Overwrite with different type
  4660. ud.set("key", std::string("hello"));
  4661. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4662. auto *s = ud.get<std::string>("key");
  4663. ASSERT_NE(nullptr, s);
  4664. EXPECT_EQ("hello", *s);
  4665. // erase
  4666. ud.erase("key");
  4667. EXPECT_FALSE(ud.has("key"));
  4668. // clear
  4669. ud.set("a", 1);
  4670. ud.set("b", 2);
  4671. ud.clear();
  4672. EXPECT_FALSE(ud.has("a"));
  4673. EXPECT_FALSE(ud.has("b"));
  4674. }
  4675. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4676. struct AuthCtx {
  4677. std::string user_id;
  4678. };
  4679. Server svr;
  4680. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4681. res.user_data.set("auth", AuthCtx{"alice"});
  4682. return Server::HandlerResponse::Unhandled;
  4683. });
  4684. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4685. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4686. ASSERT_NE(nullptr, ctx);
  4687. res.set_content("Hello " + ctx->user_id, "text/plain");
  4688. });
  4689. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4690. auto se = detail::scope_exit([&] {
  4691. svr.stop();
  4692. thread.join();
  4693. ASSERT_FALSE(svr.is_running());
  4694. });
  4695. svr.wait_until_ready();
  4696. Client cli(HOST, PORT);
  4697. auto res = cli.Get("/me");
  4698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4699. EXPECT_EQ(StatusCode::OK_200, res->status);
  4700. EXPECT_EQ("Hello alice", res->body);
  4701. }
  4702. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4703. struct RoleCtx {
  4704. std::string role;
  4705. };
  4706. Server svr;
  4707. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4708. res.user_data.set("role", RoleCtx{"admin"});
  4709. return Server::HandlerResponse::Unhandled;
  4710. });
  4711. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4712. auto *ctx = res.user_data.get<RoleCtx>("role");
  4713. ASSERT_NE(nullptr, ctx);
  4714. res.set_content(ctx->role, "text/plain");
  4715. });
  4716. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4717. auto se = detail::scope_exit([&] {
  4718. svr.stop();
  4719. thread.join();
  4720. ASSERT_FALSE(svr.is_running());
  4721. });
  4722. svr.wait_until_ready();
  4723. Client cli(HOST, PORT);
  4724. auto res = cli.Get("/role");
  4725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4726. EXPECT_EQ(StatusCode::OK_200, res->status);
  4727. EXPECT_EQ("admin", res->body);
  4728. }
  4729. TEST(InvalidFormatTest, StatusCode) {
  4730. Server svr;
  4731. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4732. res.set_content("Hello World!\n", "text/plain");
  4733. res.status = 9999; // Status should be a three-digit code...
  4734. });
  4735. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4736. auto se = detail::scope_exit([&] {
  4737. svr.stop();
  4738. thread.join();
  4739. ASSERT_FALSE(svr.is_running());
  4740. });
  4741. svr.wait_until_ready();
  4742. {
  4743. Client cli(HOST, PORT);
  4744. auto res = cli.Get("/hi");
  4745. ASSERT_FALSE(res);
  4746. }
  4747. }
  4748. TEST(URLFragmentTest, WithFragment) {
  4749. Server svr;
  4750. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4751. EXPECT_TRUE(req.target == "/hi");
  4752. });
  4753. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4754. auto se = detail::scope_exit([&] {
  4755. svr.stop();
  4756. thread.join();
  4757. ASSERT_FALSE(svr.is_running());
  4758. });
  4759. svr.wait_until_ready();
  4760. {
  4761. Client cli(HOST, PORT);
  4762. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4763. EXPECT_TRUE(res);
  4764. EXPECT_EQ(StatusCode::OK_200, res->status);
  4765. res = cli.Get("/hi%23key1=val1=key2=val2");
  4766. EXPECT_TRUE(res);
  4767. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4768. }
  4769. }
  4770. TEST(HeaderWriter, SetHeaderWriter) {
  4771. Server svr;
  4772. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4773. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4774. return detail::write_headers(strm, hdrs);
  4775. });
  4776. svr.Get("/hi", [](const Request &req, Response &res) {
  4777. auto it = req.headers.find("CustomClientHeader");
  4778. EXPECT_TRUE(it != req.headers.end());
  4779. EXPECT_EQ(it->second, "CustomClientValue");
  4780. res.set_content("Hello World!\n", "text/plain");
  4781. });
  4782. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4783. auto se = detail::scope_exit([&] {
  4784. svr.stop();
  4785. thread.join();
  4786. ASSERT_FALSE(svr.is_running());
  4787. });
  4788. svr.wait_until_ready();
  4789. {
  4790. Client cli(HOST, PORT);
  4791. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4792. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4793. return detail::write_headers(strm, hdrs);
  4794. });
  4795. auto res = cli.Get("/hi");
  4796. EXPECT_TRUE(res);
  4797. EXPECT_EQ(StatusCode::OK_200, res->status);
  4798. auto it = res->headers.find("CustomServerHeader");
  4799. EXPECT_TRUE(it != res->headers.end());
  4800. EXPECT_EQ(it->second, "CustomServerValue");
  4801. }
  4802. }
  4803. class ServerTest : public ::testing::Test {
  4804. protected:
  4805. ServerTest()
  4806. : cli_(HOST, PORT)
  4807. #ifdef CPPHTTPLIB_SSL_ENABLED
  4808. ,
  4809. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4810. #endif
  4811. {
  4812. #ifdef CPPHTTPLIB_SSL_ENABLED
  4813. cli_.enable_server_certificate_verification(false);
  4814. #endif
  4815. // Allow LARGE_DATA (100MB) responses
  4816. cli_.set_payload_max_length(200 * 1024 * 1024);
  4817. }
  4818. virtual void SetUp() {
  4819. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4820. svr_.set_payload_max_length(200 * 1024 * 1024);
  4821. svr_.set_mount_point("/", "./www");
  4822. svr_.set_mount_point("/mount", "./www2");
  4823. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4824. svr_.Get("/hi",
  4825. [&](const Request & /*req*/, Response &res) {
  4826. res.set_content("Hello World!", "text/plain");
  4827. })
  4828. .Get("/file_content",
  4829. [&](const Request & /*req*/, Response &res) {
  4830. res.set_file_content("./www/dir/test.html");
  4831. })
  4832. .Get("/file_content_with_content_type",
  4833. [&](const Request & /*req*/, Response &res) {
  4834. res.set_file_content("./www/file", "text/plain");
  4835. })
  4836. .Get("/invalid_file_content",
  4837. [&](const Request & /*req*/, Response &res) {
  4838. res.set_file_content("./www/dir/invalid_file_path");
  4839. })
  4840. .Get("/http_response_splitting",
  4841. [&](const Request & /*req*/, Response &res) {
  4842. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4843. EXPECT_EQ(0U, res.headers.size());
  4844. EXPECT_FALSE(res.has_header("a"));
  4845. res.set_header("a", "1\nSet-Cookie: a=1");
  4846. EXPECT_EQ(0U, res.headers.size());
  4847. EXPECT_FALSE(res.has_header("a"));
  4848. res.set_header("a", "1\rSet-Cookie: a=1");
  4849. EXPECT_EQ(0U, res.headers.size());
  4850. EXPECT_FALSE(res.has_header("a"));
  4851. res.set_header("a\r\nb", "0");
  4852. EXPECT_EQ(0U, res.headers.size());
  4853. EXPECT_FALSE(res.has_header("a"));
  4854. res.set_header("a\rb", "0");
  4855. EXPECT_EQ(0U, res.headers.size());
  4856. EXPECT_FALSE(res.has_header("a"));
  4857. res.set_header("a\nb", "0");
  4858. EXPECT_EQ(0U, res.headers.size());
  4859. EXPECT_FALSE(res.has_header("a"));
  4860. res.set_redirect("1\r\nSet-Cookie: a=1");
  4861. EXPECT_EQ(0U, res.headers.size());
  4862. EXPECT_FALSE(res.has_header("Location"));
  4863. })
  4864. .Get("/slow",
  4865. [&](const Request & /*req*/, Response &res) {
  4866. std::this_thread::sleep_for(std::chrono::seconds(4));
  4867. res.set_content("slow", "text/plain");
  4868. })
  4869. #if 0
  4870. .Post("/slowpost",
  4871. [&](const Request & /*req*/, Response &res) {
  4872. std::this_thread::sleep_for(std::chrono::seconds(2));
  4873. res.set_content("slow", "text/plain");
  4874. })
  4875. #endif
  4876. .Get("/remote_addr",
  4877. [&](const Request &req, Response &res) {
  4878. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4879. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4880. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4881. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4882. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4883. #endif
  4884. res.set_content(req.remote_addr, "text/plain");
  4885. })
  4886. .Get("/local_addr",
  4887. [&](const Request &req, Response &res) {
  4888. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4889. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4890. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4891. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4892. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4893. #endif
  4894. auto local_addr = req.local_addr;
  4895. auto local_port = std::to_string(req.local_port);
  4896. res.set_content(local_addr.append(":").append(local_port),
  4897. "text/plain");
  4898. })
  4899. .Get("/endwith%",
  4900. [&](const Request & /*req*/, Response &res) {
  4901. res.set_content("Hello World!", "text/plain");
  4902. })
  4903. .Get("/a\\+\\+b",
  4904. [&](const Request &req, Response &res) {
  4905. ASSERT_TRUE(req.has_param("a +b"));
  4906. auto val = req.get_param_value("a +b");
  4907. res.set_content(val, "text/plain");
  4908. })
  4909. .Get("/", [&](const Request & /*req*/,
  4910. Response &res) { res.set_redirect("/hi"); })
  4911. .Post("/1",
  4912. [](const Request & /*req*/, Response &res) {
  4913. res.set_redirect("/2", StatusCode::SeeOther_303);
  4914. })
  4915. .Get("/2",
  4916. [](const Request & /*req*/, Response &res) {
  4917. res.set_content("redirected.", "text/plain");
  4918. res.status = StatusCode::OK_200;
  4919. })
  4920. .Post("/person",
  4921. [&](const Request &req, Response &res) {
  4922. if (req.has_param("name") && req.has_param("note")) {
  4923. persons_[req.get_param_value("name")] =
  4924. req.get_param_value("note");
  4925. } else {
  4926. res.status = StatusCode::BadRequest_400;
  4927. }
  4928. })
  4929. .Put("/person",
  4930. [&](const Request &req, Response &res) {
  4931. if (req.has_param("name") && req.has_param("note")) {
  4932. persons_[req.get_param_value("name")] =
  4933. req.get_param_value("note");
  4934. } else {
  4935. res.status = StatusCode::BadRequest_400;
  4936. }
  4937. })
  4938. .Get("/person/(.*)",
  4939. [&](const Request &req, Response &res) {
  4940. string name = req.matches[1];
  4941. if (persons_.find(name) != persons_.end()) {
  4942. auto note = persons_[name];
  4943. res.set_content(note, "text/plain");
  4944. } else {
  4945. res.status = StatusCode::NotFound_404;
  4946. }
  4947. })
  4948. .Delete("/person",
  4949. [&](const Request &req, Response &res) {
  4950. if (req.has_param("name")) {
  4951. string name = req.get_param_value("name");
  4952. if (persons_.find(name) != persons_.end()) {
  4953. persons_.erase(name);
  4954. res.set_content("DELETED", "text/plain");
  4955. } else {
  4956. res.status = StatusCode::NotFound_404;
  4957. }
  4958. } else {
  4959. res.status = StatusCode::BadRequest_400;
  4960. }
  4961. })
  4962. .Post("/x-www-form-urlencoded-json",
  4963. [&](const Request &req, Response &res) {
  4964. auto json = req.get_param_value("json");
  4965. ASSERT_EQ(JSON_DATA, json);
  4966. res.set_content(json, "appliation/json");
  4967. res.status = StatusCode::OK_200;
  4968. })
  4969. .Get("/streamed-chunked",
  4970. [&](const Request & /*req*/, Response &res) {
  4971. res.set_chunked_content_provider(
  4972. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4973. sink.os << "123";
  4974. sink.os << "456";
  4975. sink.os << "789";
  4976. sink.done();
  4977. return true;
  4978. });
  4979. })
  4980. .Get("/streamed-chunked-with-prohibited-trailer",
  4981. [&](const Request & /*req*/, Response &res) {
  4982. auto i = new int(0);
  4983. // Declare both a prohibited trailer (Content-Length) and an
  4984. // allowed one
  4985. res.set_header("Trailer", "Content-Length, X-Allowed");
  4986. res.set_chunked_content_provider(
  4987. "text/plain",
  4988. [i](size_t /*offset*/, DataSink &sink) {
  4989. switch (*i) {
  4990. case 0: sink.os << "123"; break;
  4991. case 1: sink.os << "456"; break;
  4992. case 2: sink.os << "789"; break;
  4993. case 3: {
  4994. sink.done_with_trailer(
  4995. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4996. } break;
  4997. }
  4998. (*i)++;
  4999. return true;
  5000. },
  5001. [i](bool success) {
  5002. EXPECT_TRUE(success);
  5003. delete i;
  5004. });
  5005. })
  5006. .Get("/streamed-chunked2",
  5007. [&](const Request & /*req*/, Response &res) {
  5008. auto i = new int(0);
  5009. res.set_chunked_content_provider(
  5010. "text/plain",
  5011. [i](size_t /*offset*/, DataSink &sink) {
  5012. switch (*i) {
  5013. case 0: sink.os << "123"; break;
  5014. case 1: sink.os << "456"; break;
  5015. case 2: sink.os << "789"; break;
  5016. case 3: sink.done(); break;
  5017. }
  5018. (*i)++;
  5019. return true;
  5020. },
  5021. [i](bool success) {
  5022. EXPECT_TRUE(success);
  5023. delete i;
  5024. });
  5025. })
  5026. .Get("/streamed-chunked-with-trailer",
  5027. [&](const Request & /*req*/, Response &res) {
  5028. auto i = new int(0);
  5029. res.set_header("Trailer", "Dummy1, Dummy2");
  5030. res.set_chunked_content_provider(
  5031. "text/plain",
  5032. [i](size_t /*offset*/, DataSink &sink) {
  5033. switch (*i) {
  5034. case 0: sink.os << "123"; break;
  5035. case 1: sink.os << "456"; break;
  5036. case 2: sink.os << "789"; break;
  5037. case 3: {
  5038. sink.done_with_trailer(
  5039. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5040. } break;
  5041. }
  5042. (*i)++;
  5043. return true;
  5044. },
  5045. [i](bool success) {
  5046. EXPECT_TRUE(success);
  5047. delete i;
  5048. });
  5049. })
  5050. .Get("/streamed",
  5051. [&](const Request & /*req*/, Response &res) {
  5052. res.set_content_provider(
  5053. 6, "text/plain",
  5054. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5055. sink.os << (offset < 3 ? "a" : "b");
  5056. return true;
  5057. });
  5058. })
  5059. .Get("/streamed-without-length",
  5060. [&](const Request & /*req*/, Response &res) {
  5061. auto data = new std::string("abcdefg");
  5062. res.set_content_provider(
  5063. "text/plain",
  5064. [data](size_t offset, DataSink &sink) {
  5065. if (offset < data->size()) {
  5066. sink.os << data->substr(offset);
  5067. }
  5068. sink.done();
  5069. return true;
  5070. },
  5071. [data](bool success) {
  5072. EXPECT_TRUE(success);
  5073. delete data;
  5074. });
  5075. })
  5076. .Get("/streamed-with-range",
  5077. [&](const Request &req, Response &res) {
  5078. auto data = new std::string("abcdefg");
  5079. // An explicit status keeps the server from picking the 206 it
  5080. // would otherwise choose for a ranged request, so the response
  5081. // is not a partial representation.
  5082. auto status = req.get_param_value("status");
  5083. if (status == "200") {
  5084. res.status = StatusCode::OK_200;
  5085. } else if (status == "403") {
  5086. res.status = StatusCode::Forbidden_403;
  5087. }
  5088. res.set_content_provider(
  5089. data->size(), "text/plain",
  5090. [data](size_t offset, size_t length, DataSink &sink) {
  5091. size_t DATA_CHUNK_SIZE = 4;
  5092. const auto &d = *data;
  5093. auto out_len =
  5094. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5095. auto ret =
  5096. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5097. EXPECT_TRUE(ret);
  5098. return true;
  5099. },
  5100. [data, &req](bool success) {
  5101. EXPECT_EQ(success, !req.has_param("error"));
  5102. delete data;
  5103. });
  5104. })
  5105. .Get("/streamed-cancel",
  5106. [&](const Request & /*req*/, Response &res) {
  5107. res.set_content_provider(
  5108. size_t(-1), "text/plain",
  5109. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5110. sink.os << "data_chunk";
  5111. return true;
  5112. });
  5113. })
  5114. .Get("/regex-with-delimiter",
  5115. [&](const Request &req, Response & /*res*/) {
  5116. ASSERT_TRUE(req.has_param("key"));
  5117. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5118. })
  5119. .Get("/with-range",
  5120. [&](const Request & /*req*/, Response &res) {
  5121. res.set_content("abcdefg", "text/plain");
  5122. })
  5123. .Get("/test-start-time",
  5124. [&](const Request &req, Response & /*res*/) {
  5125. EXPECT_NE(req.start_time_,
  5126. std::chrono::steady_clock::time_point::min());
  5127. })
  5128. .Get("/with-range-customized-response",
  5129. [&](const Request & /*req*/, Response &res) {
  5130. res.status = StatusCode::BadRequest_400;
  5131. res.set_content(JSON_DATA, "application/json");
  5132. })
  5133. .Post("/chunked",
  5134. [&](const Request &req, Response & /*res*/) {
  5135. EXPECT_EQ(req.body, "dechunked post body");
  5136. })
  5137. .Post("/large-chunked",
  5138. [&](const Request &req, Response & /*res*/) {
  5139. std::string expected(6 * 30 * 1024u, 'a');
  5140. EXPECT_EQ(req.body, expected);
  5141. })
  5142. .Post("/multipart",
  5143. [&](const Request &req, Response & /*res*/) {
  5144. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5145. req.form.get_field_count("text2") +
  5146. req.form.get_field_count("file3") +
  5147. req.form.get_field_count("file4"));
  5148. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5149. req.form.get_file_count("file2"));
  5150. ASSERT_TRUE(!req.form.has_file("???"));
  5151. ASSERT_TRUE(!req.form.has_field("???"));
  5152. ASSERT_TRUE(req.body.empty());
  5153. {
  5154. const auto &text = req.form.get_field("text1");
  5155. EXPECT_EQ("text default", text);
  5156. }
  5157. {
  5158. const auto &text = req.form.get_field("text2");
  5159. EXPECT_EQ("aωb", text);
  5160. }
  5161. {
  5162. const auto &file = req.form.get_file("file1");
  5163. EXPECT_EQ("hello.txt", file.filename);
  5164. EXPECT_EQ("text/plain", file.content_type);
  5165. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5166. }
  5167. {
  5168. const auto &file = req.form.get_file("file2");
  5169. EXPECT_EQ("world.json", file.filename);
  5170. EXPECT_EQ("application/json", file.content_type);
  5171. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5172. }
  5173. {
  5174. const auto &text = req.form.get_field("file3");
  5175. EXPECT_EQ(0u, text.size());
  5176. }
  5177. {
  5178. const auto &text = req.form.get_field("file4");
  5179. EXPECT_EQ(0u, text.size());
  5180. }
  5181. })
  5182. .Post("/multipart/multi_file_values",
  5183. [&](const Request &req, Response & /*res*/) {
  5184. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5185. req.form.get_field_count("multi_text1"));
  5186. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5187. ASSERT_TRUE(!req.form.has_file("???"));
  5188. ASSERT_TRUE(!req.form.has_field("???"));
  5189. ASSERT_TRUE(req.body.empty());
  5190. {
  5191. const auto &text = req.form.get_field("text");
  5192. EXPECT_EQ("default text", text);
  5193. }
  5194. {
  5195. const auto &text1_values = req.form.get_fields("multi_text1");
  5196. EXPECT_EQ(2u, text1_values.size());
  5197. EXPECT_EQ("aaaaa", text1_values[0]);
  5198. EXPECT_EQ("bbbbb", text1_values[1]);
  5199. }
  5200. {
  5201. const auto &file1_values = req.form.get_files("multi_file1");
  5202. EXPECT_EQ(2u, file1_values.size());
  5203. auto file1 = file1_values[0];
  5204. EXPECT_EQ(file1.filename, "hello.txt");
  5205. EXPECT_EQ(file1.content_type, "text/plain");
  5206. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5207. auto file2 = file1_values[1];
  5208. EXPECT_EQ(file2.filename, "world.json");
  5209. EXPECT_EQ(file2.content_type, "application/json");
  5210. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5211. }
  5212. })
  5213. .Post("/empty",
  5214. [&](const Request &req, Response &res) {
  5215. EXPECT_EQ(req.body, "");
  5216. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5217. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5218. res.set_content("empty", "text/plain");
  5219. })
  5220. .Post("/empty-no-content-type",
  5221. [&](const Request &req, Response &res) {
  5222. EXPECT_EQ(req.body, "");
  5223. EXPECT_FALSE(req.has_header("Content-Type"));
  5224. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5225. res.set_content("empty-no-content-type", "text/plain");
  5226. })
  5227. .Post("/path-only",
  5228. [&](const Request &req, Response &res) {
  5229. EXPECT_EQ(req.body, "");
  5230. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5231. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5232. res.set_content("path-only", "text/plain");
  5233. })
  5234. .Post("/path-headers-only",
  5235. [&](const Request &req, Response &res) {
  5236. EXPECT_EQ(req.body, "");
  5237. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5238. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5239. EXPECT_EQ("world", req.get_header_value("hello"));
  5240. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5241. res.set_content("path-headers-only", "text/plain");
  5242. })
  5243. .Post("/post-large",
  5244. [&](const Request &req, Response &res) {
  5245. EXPECT_EQ(req.body, LARGE_DATA);
  5246. res.set_content(req.body, "text/plain");
  5247. })
  5248. .Post("/post-loopback",
  5249. [&](const Request &, Response &res,
  5250. ContentReader const &content_reader) {
  5251. std::string body;
  5252. content_reader([&](const char *data, size_t data_length) {
  5253. body.append(data, data_length);
  5254. return true;
  5255. });
  5256. res.set_content(body, "text/plain");
  5257. })
  5258. .Put("/put-loopback",
  5259. [&](const Request &, Response &res,
  5260. ContentReader const &content_reader) {
  5261. std::string body;
  5262. content_reader([&](const char *data, size_t data_length) {
  5263. body.append(data, data_length);
  5264. return true;
  5265. });
  5266. res.set_content(body, "text/plain");
  5267. })
  5268. .Patch("/patch-loopback",
  5269. [&](const Request &, Response &res,
  5270. ContentReader const &content_reader) {
  5271. std::string body;
  5272. content_reader([&](const char *data, size_t data_length) {
  5273. body.append(data, data_length);
  5274. return true;
  5275. });
  5276. res.set_content(body, "text/plain");
  5277. })
  5278. .Put("/empty-no-content-type",
  5279. [&](const Request &req, Response &res) {
  5280. EXPECT_EQ(req.body, "");
  5281. EXPECT_FALSE(req.has_header("Content-Type"));
  5282. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5283. res.set_content("empty-no-content-type", "text/plain");
  5284. })
  5285. .Put("/put",
  5286. [&](const Request &req, Response &res) {
  5287. EXPECT_EQ(req.body, "PUT");
  5288. res.set_content(req.body, "text/plain");
  5289. })
  5290. .Put("/put-large",
  5291. [&](const Request &req, Response &res) {
  5292. EXPECT_EQ(req.body, LARGE_DATA);
  5293. res.set_content(req.body, "text/plain");
  5294. })
  5295. .Patch("/patch",
  5296. [&](const Request &req, Response &res) {
  5297. EXPECT_EQ(req.body, "PATCH");
  5298. res.set_content(req.body, "text/plain");
  5299. })
  5300. .Delete("/delete",
  5301. [&](const Request & /*req*/, Response &res) {
  5302. res.set_content("DELETE", "text/plain");
  5303. })
  5304. .Delete("/delete-body",
  5305. [&](const Request &req, Response &res) {
  5306. EXPECT_EQ(req.body, "content");
  5307. res.set_content(req.body, "text/plain");
  5308. })
  5309. .Options(R"(\*)",
  5310. [&](const Request & /*req*/, Response &res) {
  5311. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5312. })
  5313. .CustomRoute("PROPFIND", "/dav/:id",
  5314. [&](const Request &req, Response &res) {
  5315. res.set_header("x-body-size",
  5316. std::to_string(req.body.size()));
  5317. res.set_header("x-matched-route", req.matched_route);
  5318. res.set_header("x-dav-id", req.path_params.at("id"));
  5319. res.status = StatusCode::MultiStatus_207;
  5320. res.set_content(req.body, "application/xml");
  5321. })
  5322. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5323. [&](const Request &req, Response &res) {
  5324. res.set_header("x-dav-match", req.matches[1]);
  5325. res.status = StatusCode::MultiStatus_207;
  5326. })
  5327. .CustomRoute("MKCOL", "/dav-mkcol",
  5328. [&](const Request &req, Response &res) {
  5329. EXPECT_TRUE(req.body.empty());
  5330. res.status = StatusCode::Created_201;
  5331. })
  5332. .CustomRoute(
  5333. "REPORT", "/dav-report",
  5334. [&](const Request & /*req*/, Response &res,
  5335. const ContentReader &content_reader) {
  5336. std::string body;
  5337. content_reader([&](const char *data, size_t data_length) {
  5338. body.append(data, data_length);
  5339. return true;
  5340. });
  5341. res.set_header("x-body-size", std::to_string(body.size()));
  5342. res.status = StatusCode::MultiStatus_207;
  5343. res.set_content(body, "application/xml");
  5344. })
  5345. .Get("/request-target",
  5346. [&](const Request &req, Response & /*res*/) {
  5347. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5348. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5349. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5350. })
  5351. .Get("/long-query-value",
  5352. [&](const Request &req, Response & /*res*/) {
  5353. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5354. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5355. })
  5356. .Get("/too-long-query-value",
  5357. [&](const Request &req, Response & /*res*/) {
  5358. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5359. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5360. })
  5361. .Get("/array-param",
  5362. [&](const Request &req, Response & /*res*/) {
  5363. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5364. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5365. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5366. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5367. })
  5368. .Get("/array-param-values",
  5369. [&](const Request &req, Response & /*res*/) {
  5370. auto values = req.get_param_values("array");
  5371. EXPECT_EQ(3u, values.size());
  5372. EXPECT_EQ("value1", values[0]);
  5373. EXPECT_EQ("value2", values[1]);
  5374. EXPECT_EQ("value3", values[2]);
  5375. auto empty = req.get_param_values("nonexistent");
  5376. EXPECT_TRUE(empty.empty());
  5377. })
  5378. .Post("/validate-no-multiple-headers",
  5379. [&](const Request &req, Response & /*res*/) {
  5380. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5381. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5382. })
  5383. .Post("/content_receiver",
  5384. [&](const Request &req, Response &res,
  5385. const ContentReader &content_reader) {
  5386. if (req.is_multipart_form_data()) {
  5387. std::vector<FormData> items;
  5388. content_reader(
  5389. [&](const FormData &file) {
  5390. items.push_back(file);
  5391. return true;
  5392. },
  5393. [&](const char *data, size_t data_length) {
  5394. items.back().content.append(data, data_length);
  5395. return true;
  5396. });
  5397. EXPECT_EQ(5u, items.size());
  5398. {
  5399. const auto &file = get_file_value(items, "text1");
  5400. EXPECT_TRUE(file.filename.empty());
  5401. EXPECT_EQ("text default", file.content);
  5402. }
  5403. {
  5404. const auto &file = get_file_value(items, "text2");
  5405. EXPECT_TRUE(file.filename.empty());
  5406. EXPECT_EQ("aωb", file.content);
  5407. }
  5408. {
  5409. const auto &file = get_file_value(items, "file1");
  5410. EXPECT_EQ("hello.txt", file.filename);
  5411. EXPECT_EQ("text/plain", file.content_type);
  5412. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5413. }
  5414. {
  5415. const auto &file = get_file_value(items, "file2");
  5416. EXPECT_EQ("world.json", file.filename);
  5417. EXPECT_EQ("application/json", file.content_type);
  5418. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5419. }
  5420. {
  5421. const auto &file = get_file_value(items, "file3");
  5422. EXPECT_TRUE(file.filename.empty());
  5423. EXPECT_EQ("application/octet-stream", file.content_type);
  5424. EXPECT_EQ(0u, file.content.size());
  5425. }
  5426. } else {
  5427. std::string body;
  5428. content_reader([&](const char *data, size_t data_length) {
  5429. EXPECT_EQ(7U, data_length);
  5430. body.append(data, data_length);
  5431. return true;
  5432. });
  5433. EXPECT_EQ(body, "content");
  5434. res.set_content(body, "text/plain");
  5435. }
  5436. })
  5437. .Put("/content_receiver",
  5438. [&](const Request & /*req*/, Response &res,
  5439. const ContentReader &content_reader) {
  5440. std::string body;
  5441. content_reader([&](const char *data, size_t data_length) {
  5442. body.append(data, data_length);
  5443. return true;
  5444. });
  5445. EXPECT_EQ(body, "content");
  5446. res.set_content(body, "text/plain");
  5447. })
  5448. .Patch("/content_receiver",
  5449. [&](const Request & /*req*/, Response &res,
  5450. const ContentReader &content_reader) {
  5451. std::string body;
  5452. content_reader([&](const char *data, size_t data_length) {
  5453. body.append(data, data_length);
  5454. return true;
  5455. });
  5456. EXPECT_EQ(body, "content");
  5457. res.set_content(body, "text/plain");
  5458. })
  5459. .Post("/query-string-and-body",
  5460. [&](const Request &req, Response & /*res*/) {
  5461. ASSERT_TRUE(req.has_param("key"));
  5462. EXPECT_EQ(req.get_param_value("key"), "value");
  5463. EXPECT_EQ(req.body, "content");
  5464. })
  5465. .Get("/last-request",
  5466. [&](const Request &req, Response & /*res*/) {
  5467. EXPECT_EQ("close", req.get_header_value("Connection"));
  5468. })
  5469. .Get(R"(/redirect/(\d+))",
  5470. [&](const Request &req, Response &res) {
  5471. auto num = std::stoi(req.matches[1]) + 1;
  5472. std::string url = "/redirect/" + std::to_string(num);
  5473. res.set_redirect(url);
  5474. })
  5475. .Post("/binary",
  5476. [&](const Request &req, Response &res) {
  5477. EXPECT_EQ(4U, req.body.size());
  5478. EXPECT_EQ("application/octet-stream",
  5479. req.get_header_value("Content-Type"));
  5480. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5481. res.set_content(req.body, "application/octet-stream");
  5482. })
  5483. .Put("/binary",
  5484. [&](const Request &req, Response &res) {
  5485. EXPECT_EQ(4U, req.body.size());
  5486. EXPECT_EQ("application/octet-stream",
  5487. req.get_header_value("Content-Type"));
  5488. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5489. res.set_content(req.body, "application/octet-stream");
  5490. })
  5491. .Patch("/binary",
  5492. [&](const Request &req, Response &res) {
  5493. EXPECT_EQ(4U, req.body.size());
  5494. EXPECT_EQ("application/octet-stream",
  5495. req.get_header_value("Content-Type"));
  5496. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5497. res.set_content(req.body, "application/octet-stream");
  5498. })
  5499. .Delete("/binary",
  5500. [&](const Request &req, Response &res) {
  5501. EXPECT_EQ(4U, req.body.size());
  5502. EXPECT_EQ("application/octet-stream",
  5503. req.get_header_value("Content-Type"));
  5504. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5505. res.set_content(req.body, "application/octet-stream");
  5506. })
  5507. .Get("/issue1772",
  5508. [&](const Request & /*req*/, Response &res) {
  5509. res.status = 401;
  5510. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5511. })
  5512. .Delete("/issue609",
  5513. [](const httplib::Request &, httplib::Response &res,
  5514. const httplib::ContentReader &) {
  5515. res.set_content("ok", "text/plain");
  5516. })
  5517. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5518. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5519. .Get("/compress",
  5520. [&](const Request & /*req*/, Response &res) {
  5521. res.set_content(
  5522. "12345678901234567890123456789012345678901234567890123456789"
  5523. "01234567890123456789012345678901234567890",
  5524. "text/plain");
  5525. })
  5526. .Get("/compress-with-charset",
  5527. [&](const Request & /*req*/, Response &res) {
  5528. res.set_content(
  5529. "12345678901234567890123456789012345678901234567890123456789"
  5530. "01234567890123456789012345678901234567890",
  5531. "application/json; charset=utf-8");
  5532. })
  5533. .Get("/nocompress",
  5534. [&](const Request & /*req*/, Response &res) {
  5535. res.set_content(
  5536. "12345678901234567890123456789012345678901234567890123456789"
  5537. "01234567890123456789012345678901234567890",
  5538. "application/octet-stream");
  5539. })
  5540. .Post("/compress-multipart",
  5541. [&](const Request &req, Response & /*res*/) {
  5542. EXPECT_EQ(2u, req.form.fields.size());
  5543. ASSERT_TRUE(!req.form.has_field("???"));
  5544. {
  5545. const auto &text = req.form.get_field("key1");
  5546. EXPECT_EQ("test", text);
  5547. }
  5548. {
  5549. const auto &text = req.form.get_field("key2");
  5550. EXPECT_EQ("--abcdefg123", text);
  5551. }
  5552. })
  5553. #endif
  5554. ;
  5555. persons_["john"] = "programmer";
  5556. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5557. svr_.wait_until_ready();
  5558. }
  5559. virtual void TearDown() {
  5560. svr_.stop();
  5561. if (!request_threads_.empty()) {
  5562. std::this_thread::sleep_for(std::chrono::seconds(1));
  5563. for (auto &t : request_threads_) {
  5564. t.join();
  5565. }
  5566. }
  5567. t_.join();
  5568. }
  5569. map<string, string> persons_;
  5570. #ifdef CPPHTTPLIB_SSL_ENABLED
  5571. SSLClient cli_;
  5572. SSLServer svr_;
  5573. #else
  5574. Client cli_;
  5575. Server svr_;
  5576. #endif
  5577. thread t_;
  5578. std::vector<thread> request_threads_;
  5579. };
  5580. TEST_F(ServerTest, GetMethod200) {
  5581. auto res = cli_.Get("/hi");
  5582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5583. EXPECT_EQ("HTTP/1.1", res->version);
  5584. EXPECT_EQ(StatusCode::OK_200, res->status);
  5585. EXPECT_EQ("OK", res->reason);
  5586. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5587. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5588. EXPECT_EQ("Hello World!", res->body);
  5589. }
  5590. TEST_F(ServerTest, GetEmptyFile) {
  5591. auto res = cli_.Get("/empty_file");
  5592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5593. EXPECT_EQ(StatusCode::OK_200, res->status);
  5594. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5595. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5596. EXPECT_EQ("", res->body);
  5597. }
  5598. TEST_F(ServerTest, GetFileContent) {
  5599. auto res = cli_.Get("/file_content");
  5600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5601. EXPECT_EQ(StatusCode::OK_200, res->status);
  5602. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5603. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5604. EXPECT_EQ("test.html", res->body);
  5605. }
  5606. TEST_F(ServerTest, GetFileContentWithRange) {
  5607. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5609. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5610. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5611. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5612. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5613. EXPECT_EQ("est", res->body);
  5614. }
  5615. TEST_F(ServerTest, GetFileContentWithContentType) {
  5616. auto res = cli_.Get("/file_content_with_content_type");
  5617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5618. EXPECT_EQ(StatusCode::OK_200, res->status);
  5619. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5620. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5621. EXPECT_EQ("file\n", res->body);
  5622. }
  5623. TEST_F(ServerTest, GetInvalidFileContent) {
  5624. auto res = cli_.Get("/invalid_file_content");
  5625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5626. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5627. }
  5628. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5629. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5631. EXPECT_EQ("HTTP/1.1", res->version);
  5632. EXPECT_EQ(StatusCode::OK_200, res->status);
  5633. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5634. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5635. EXPECT_EQ("Hello World!", res->body);
  5636. }
  5637. TEST_F(ServerTest, GetMethod302) {
  5638. auto res = cli_.Get("/");
  5639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5640. EXPECT_EQ(StatusCode::Found_302, res->status);
  5641. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5642. }
  5643. TEST_F(ServerTest, GetMethod302Redirect) {
  5644. cli_.set_follow_location(true);
  5645. auto res = cli_.Get("/");
  5646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5647. EXPECT_EQ(StatusCode::OK_200, res->status);
  5648. EXPECT_EQ("Hello World!", res->body);
  5649. EXPECT_EQ("/hi", res->location);
  5650. }
  5651. TEST_F(ServerTest, GetMethod404) {
  5652. auto res = cli_.Get("/invalid");
  5653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5654. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5655. }
  5656. TEST_F(ServerTest, HeadMethod200) {
  5657. auto res = cli_.Head("/hi");
  5658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5659. EXPECT_EQ(StatusCode::OK_200, res->status);
  5660. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5661. EXPECT_TRUE(res->body.empty());
  5662. }
  5663. TEST_F(ServerTest, HeadMethod200Static) {
  5664. auto res = cli_.Head("/mount/dir/index.html");
  5665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5666. EXPECT_EQ(StatusCode::OK_200, res->status);
  5667. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5668. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5669. EXPECT_TRUE(res->body.empty());
  5670. }
  5671. TEST_F(ServerTest, HeadMethod404) {
  5672. auto res = cli_.Head("/invalid");
  5673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5674. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5675. EXPECT_TRUE(res->body.empty());
  5676. }
  5677. TEST_F(ServerTest, GetMethodPersonJohn) {
  5678. auto res = cli_.Get("/person/john");
  5679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5680. EXPECT_EQ(StatusCode::OK_200, res->status);
  5681. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5682. EXPECT_EQ("programmer", res->body);
  5683. }
  5684. TEST_F(ServerTest, PostMethod1) {
  5685. auto res = cli_.Get("/person/john1");
  5686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5687. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5688. res = cli_.Post("/person", "name=john1&note=coder",
  5689. "application/x-www-form-urlencoded");
  5690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5691. ASSERT_EQ(StatusCode::OK_200, res->status);
  5692. res = cli_.Get("/person/john1");
  5693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5694. ASSERT_EQ(StatusCode::OK_200, res->status);
  5695. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5696. ASSERT_EQ("coder", res->body);
  5697. }
  5698. TEST_F(ServerTest, PostMethod2) {
  5699. auto res = cli_.Get("/person/john2");
  5700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5701. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5702. Params params;
  5703. params.emplace("name", "john2");
  5704. params.emplace("note", "coder");
  5705. res = cli_.Post("/person", params);
  5706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5707. ASSERT_EQ(StatusCode::OK_200, res->status);
  5708. res = cli_.Get("/person/john2");
  5709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5710. ASSERT_EQ(StatusCode::OK_200, res->status);
  5711. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5712. ASSERT_EQ("coder", res->body);
  5713. }
  5714. TEST_F(ServerTest, PutMethod3) {
  5715. auto res = cli_.Get("/person/john3");
  5716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5717. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5718. Params params;
  5719. params.emplace("name", "john3");
  5720. params.emplace("note", "coder");
  5721. res = cli_.Put("/person", params);
  5722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5723. ASSERT_EQ(StatusCode::OK_200, res->status);
  5724. res = cli_.Get("/person/john3");
  5725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5726. ASSERT_EQ(StatusCode::OK_200, res->status);
  5727. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5728. ASSERT_EQ("coder", res->body);
  5729. }
  5730. TEST_F(ServerTest, DeleteMethod1) {
  5731. auto res = cli_.Get("/person/john4");
  5732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5733. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5734. Params params;
  5735. params.emplace("name", "john4");
  5736. params.emplace("note", "coder");
  5737. res = cli_.Post("/person", params);
  5738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5739. ASSERT_EQ(StatusCode::OK_200, res->status);
  5740. res = cli_.Get("/person/john4");
  5741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5742. ASSERT_EQ(StatusCode::OK_200, res->status);
  5743. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5744. ASSERT_EQ("coder", res->body);
  5745. Params delete_params;
  5746. delete_params.emplace("name", "john4");
  5747. res = cli_.Delete("/person", delete_params);
  5748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5749. ASSERT_EQ(StatusCode::OK_200, res->status);
  5750. ASSERT_EQ("DELETED", res->body);
  5751. res = cli_.Get("/person/john4");
  5752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5753. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5754. }
  5755. TEST_F(ServerTest, DeleteMethod2) {
  5756. auto res = cli_.Get("/person/john5");
  5757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5758. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5759. Params params;
  5760. params.emplace("name", "john5");
  5761. params.emplace("note", "developer");
  5762. res = cli_.Post("/person", params);
  5763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5764. ASSERT_EQ(StatusCode::OK_200, res->status);
  5765. res = cli_.Get("/person/john5");
  5766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5767. ASSERT_EQ(StatusCode::OK_200, res->status);
  5768. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5769. ASSERT_EQ("developer", res->body);
  5770. Params delete_params;
  5771. delete_params.emplace("name", "john5");
  5772. Headers headers;
  5773. headers.emplace("Custom-Header", "test-value");
  5774. res = cli_.Delete("/person", headers, delete_params);
  5775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5776. ASSERT_EQ(StatusCode::OK_200, res->status);
  5777. ASSERT_EQ("DELETED", res->body);
  5778. res = cli_.Get("/person/john5");
  5779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5780. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5781. }
  5782. TEST_F(ServerTest, DeleteMethod3) {
  5783. auto res = cli_.Get("/person/john6");
  5784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5785. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5786. Params params;
  5787. params.emplace("name", "john6");
  5788. params.emplace("note", "tester");
  5789. res = cli_.Post("/person", params);
  5790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5791. ASSERT_EQ(StatusCode::OK_200, res->status);
  5792. res = cli_.Get("/person/john6");
  5793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5794. ASSERT_EQ(StatusCode::OK_200, res->status);
  5795. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5796. ASSERT_EQ("tester", res->body);
  5797. Params delete_params;
  5798. delete_params.emplace("name", "john6");
  5799. Headers headers;
  5800. headers.emplace("Custom-Header", "test-value");
  5801. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5803. ASSERT_EQ(StatusCode::OK_200, res->status);
  5804. ASSERT_EQ("DELETED", res->body);
  5805. res = cli_.Get("/person/john6");
  5806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5807. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5808. }
  5809. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5810. Params params;
  5811. params.emplace("json", JSON_DATA);
  5812. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5814. ASSERT_EQ(StatusCode::OK_200, res->status);
  5815. ASSERT_EQ(JSON_DATA, res->body);
  5816. }
  5817. TEST_F(ServerTest, PostEmptyContent) {
  5818. auto res = cli_.Post("/empty", "", "text/plain");
  5819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5820. ASSERT_EQ(StatusCode::OK_200, res->status);
  5821. ASSERT_EQ("empty", res->body);
  5822. }
  5823. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5824. auto res = cli_.Post("/empty-no-content-type");
  5825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5826. ASSERT_EQ(StatusCode::OK_200, res->status);
  5827. ASSERT_EQ("empty-no-content-type", res->body);
  5828. }
  5829. TEST_F(ServerTest, PostPathOnly) {
  5830. auto res = cli_.Post("/path-only");
  5831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5832. ASSERT_EQ(StatusCode::OK_200, res->status);
  5833. ASSERT_EQ("path-only", res->body);
  5834. }
  5835. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5836. auto res = cli_.Post("/path-headers-only",
  5837. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5839. ASSERT_EQ(StatusCode::OK_200, res->status);
  5840. ASSERT_EQ("path-headers-only", res->body);
  5841. }
  5842. TEST_F(ServerTest, PostLarge) {
  5843. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5845. ASSERT_EQ(StatusCode::OK_200, res->status);
  5846. EXPECT_EQ(LARGE_DATA, res->body);
  5847. }
  5848. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5849. auto res = cli_.Put("/empty-no-content-type");
  5850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5851. ASSERT_EQ(StatusCode::OK_200, res->status);
  5852. ASSERT_EQ("empty-no-content-type", res->body);
  5853. }
  5854. TEST_F(ServerTest, GetMethodDir) {
  5855. auto res = cli_.Get("/dir/");
  5856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5857. EXPECT_EQ(StatusCode::OK_200, res->status);
  5858. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5859. auto body = R"(<html>
  5860. <head>
  5861. </head>
  5862. <body>
  5863. <a href="/dir/test.html">Test</a>
  5864. <a href="/hi">hi</a>
  5865. </body>
  5866. </html>
  5867. )";
  5868. EXPECT_EQ(body, res->body);
  5869. }
  5870. TEST_F(ServerTest, GetMethodDirTest) {
  5871. auto res = cli_.Get("/dir/test.html");
  5872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5873. EXPECT_EQ(StatusCode::OK_200, res->status);
  5874. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5875. EXPECT_EQ("test.html", res->body);
  5876. }
  5877. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5878. auto res = cli_.Get("/dir/../dir/test.html");
  5879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5880. EXPECT_EQ(StatusCode::OK_200, res->status);
  5881. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5882. EXPECT_EQ("test.html", res->body);
  5883. }
  5884. TEST_F(ServerTest, GetMethodInvalidPath) {
  5885. auto res = cli_.Get("/dir/../test.html");
  5886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5887. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5888. }
  5889. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5890. auto res = cli_.Get("/../www/dir/test.html");
  5891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5892. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5893. }
  5894. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5895. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5897. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5898. }
  5899. TEST_F(ServerTest, GetMethodDirMountTest) {
  5900. auto res = cli_.Get("/mount/dir/test.html");
  5901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5902. EXPECT_EQ(StatusCode::OK_200, res->status);
  5903. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5904. EXPECT_EQ("test.html", res->body);
  5905. }
  5906. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5907. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5909. EXPECT_EQ(StatusCode::OK_200, res->status);
  5910. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5911. EXPECT_EQ("test.html", res->body);
  5912. }
  5913. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5914. auto res = cli_.Get("/mount/dir/../test.html");
  5915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5916. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5917. }
  5918. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5919. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5921. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5922. }
  5923. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5924. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5926. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5927. }
  5928. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5929. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5931. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5932. }
  5933. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5934. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5936. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5937. }
  5938. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  5939. auto res = cli_.Get("/mount/dir");
  5940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5941. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5942. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5943. }
  5944. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  5945. auto res = cli_.Get("//dir");
  5946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5947. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5948. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5949. }
  5950. TEST_F(ServerTest, PostMethod303) {
  5951. auto res = cli_.Post("/1", "body", "text/plain");
  5952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5953. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5954. EXPECT_EQ("/2", res->get_header_value("Location"));
  5955. }
  5956. TEST_F(ServerTest, PostMethod303Redirect) {
  5957. cli_.set_follow_location(true);
  5958. auto res = cli_.Post("/1", "body", "text/plain");
  5959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5960. EXPECT_EQ(StatusCode::OK_200, res->status);
  5961. EXPECT_EQ("redirected.", res->body);
  5962. EXPECT_EQ("/2", res->location);
  5963. }
  5964. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5965. auto res = cli_.Get("/dir/test.abcde");
  5966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5967. EXPECT_EQ(StatusCode::OK_200, res->status);
  5968. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5969. EXPECT_EQ("abcde", res->body);
  5970. }
  5971. TEST_F(ServerTest, StaticFileRange) {
  5972. auto res =
  5973. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5975. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5976. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5977. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5978. EXPECT_EQ(true, res->has_header("Content-Range"));
  5979. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5980. EXPECT_EQ(std::string("cd"), res->body);
  5981. }
  5982. TEST_F(ServerTest, StaticFileRanges) {
  5983. auto res = cli_.Get("/dir/test.abcde",
  5984. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5986. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5987. EXPECT_TRUE(
  5988. res->get_header_value("Content-Type")
  5989. .find(
  5990. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5991. 0);
  5992. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5993. }
  5994. TEST_F(ServerTest, StaticFileRangeHead) {
  5995. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5997. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5998. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5999. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6000. EXPECT_EQ(true, res->has_header("Content-Range"));
  6001. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6002. }
  6003. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6004. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6006. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6007. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6008. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6009. EXPECT_EQ(true, res->has_header("Content-Range"));
  6010. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6011. res->get_header_value("Content-Range"));
  6012. EXPECT_EQ("LAST\n", res->body);
  6013. }
  6014. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6015. auto res =
  6016. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6018. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6019. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6020. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6021. EXPECT_EQ(true, res->has_header("Content-Range"));
  6022. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6023. }
  6024. TEST_F(ServerTest, StaticFileBigFile) {
  6025. auto res = cli_.Get("/dir/1MB.txt");
  6026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6027. EXPECT_EQ(StatusCode::OK_200, res->status);
  6028. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6029. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6030. }
  6031. TEST_F(ServerTest, InvalidBaseDirMount) {
  6032. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6033. }
  6034. TEST_F(ServerTest, Binary) {
  6035. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6036. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6037. "application/octet-stream");
  6038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6039. ASSERT_EQ(StatusCode::OK_200, res->status);
  6040. ASSERT_EQ(4U, res->body.size());
  6041. res = cli_.Put("/binary", binary.data(), binary.size(),
  6042. "application/octet-stream");
  6043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6044. ASSERT_EQ(StatusCode::OK_200, res->status);
  6045. ASSERT_EQ(4U, res->body.size());
  6046. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6047. "application/octet-stream");
  6048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6049. ASSERT_EQ(StatusCode::OK_200, res->status);
  6050. ASSERT_EQ(4U, res->body.size());
  6051. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6052. "application/octet-stream");
  6053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6054. ASSERT_EQ(StatusCode::OK_200, res->status);
  6055. ASSERT_EQ(4U, res->body.size());
  6056. }
  6057. TEST_F(ServerTest, BinaryString) {
  6058. auto binary = std::string("\x00\x01\x02\x03", 4);
  6059. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6061. ASSERT_EQ(StatusCode::OK_200, res->status);
  6062. ASSERT_EQ(4U, res->body.size());
  6063. res = cli_.Put("/binary", binary, "application/octet-stream");
  6064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6065. ASSERT_EQ(StatusCode::OK_200, res->status);
  6066. ASSERT_EQ(4U, res->body.size());
  6067. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6069. ASSERT_EQ(StatusCode::OK_200, res->status);
  6070. ASSERT_EQ(4U, res->body.size());
  6071. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6073. ASSERT_EQ(StatusCode::OK_200, res->status);
  6074. ASSERT_EQ(4U, res->body.size());
  6075. }
  6076. TEST_F(ServerTest, EmptyRequest) {
  6077. auto res = cli_.Get("");
  6078. ASSERT_TRUE(!res);
  6079. EXPECT_EQ(Error::Connection, res.error());
  6080. }
  6081. TEST_F(ServerTest, LongRequest) {
  6082. std::string request;
  6083. for (size_t i = 0; i < 545; i++) {
  6084. request += "/TooLongRequest";
  6085. }
  6086. request += "OK";
  6087. auto res = cli_.Get(request.c_str());
  6088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6089. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6090. }
  6091. TEST_F(ServerTest, TooLongRequest) {
  6092. std::string request;
  6093. for (size_t i = 0; i < 546; i++) {
  6094. request += "/TooLongRequest";
  6095. }
  6096. request += "_NG";
  6097. auto start = std::chrono::high_resolution_clock::now();
  6098. cli_.set_keep_alive(true);
  6099. auto res = cli_.Get(request.c_str());
  6100. auto end = std::chrono::high_resolution_clock::now();
  6101. auto elapsed =
  6102. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6103. .count();
  6104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6105. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6106. EXPECT_LE(elapsed, 1000);
  6107. EXPECT_EQ("close", res->get_header_value("Connection"));
  6108. EXPECT_FALSE(cli_.is_socket_open());
  6109. }
  6110. TEST_F(ServerTest, AlmostTooLongRequest) {
  6111. // test for #2046 - URI length check shouldn't include other content on req
  6112. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6113. // leading /, space, HTTP/1.1)
  6114. std::string request =
  6115. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6116. auto res = cli_.Get(request.c_str());
  6117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6118. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6119. }
  6120. TEST_F(ServerTest, LongHeader) {
  6121. Request req;
  6122. req.method = "GET";
  6123. req.path = "/hi";
  6124. std::string host_and_port;
  6125. host_and_port += HOST;
  6126. host_and_port += ":";
  6127. host_and_port += std::to_string(PORT);
  6128. req.headers.emplace("Host", host_and_port.c_str());
  6129. req.headers.emplace("Accept", "*/*");
  6130. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6131. req.headers.emplace(
  6132. "Header-Name",
  6133. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6134. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6135. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6136. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6137. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6138. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6139. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6140. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6141. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6142. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6143. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6144. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6145. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6146. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6147. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6148. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6149. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6150. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6151. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6152. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6153. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6154. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6155. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6156. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6157. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6158. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6159. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6160. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6161. "@@@@@@@@@@@@@@@@");
  6162. auto res = std::make_shared<Response>();
  6163. auto error = Error::Success;
  6164. auto ret = cli_.send(req, *res, error);
  6165. ASSERT_TRUE(ret);
  6166. EXPECT_EQ(StatusCode::OK_200, res->status);
  6167. }
  6168. TEST_F(ServerTest, LongQueryValue) {
  6169. auto start = std::chrono::high_resolution_clock::now();
  6170. cli_.set_keep_alive(true);
  6171. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6172. auto end = std::chrono::high_resolution_clock::now();
  6173. auto elapsed =
  6174. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6175. .count();
  6176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6177. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6178. EXPECT_LE(elapsed, 1000);
  6179. EXPECT_EQ("close", res->get_header_value("Connection"));
  6180. EXPECT_FALSE(cli_.is_socket_open());
  6181. }
  6182. TEST_F(ServerTest, TooLongQueryValue) {
  6183. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6184. ASSERT_FALSE(res);
  6185. EXPECT_EQ(Error::Read, res.error());
  6186. }
  6187. TEST_F(ServerTest, TooLongHeader) {
  6188. Request req;
  6189. req.method = "GET";
  6190. req.path = "/hi";
  6191. std::string host_and_port;
  6192. host_and_port += HOST;
  6193. host_and_port += ":";
  6194. host_and_port += std::to_string(PORT);
  6195. req.headers.emplace("Host", host_and_port.c_str());
  6196. req.headers.emplace("Accept", "*/*");
  6197. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6198. req.headers.emplace(
  6199. "Header-Name",
  6200. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6201. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6202. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6203. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6204. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6205. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6206. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6207. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6208. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6209. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6210. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6211. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6212. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6213. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6214. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6215. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6216. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6217. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6218. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6219. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6220. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6221. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6222. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6223. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6224. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6225. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6226. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6227. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6228. "@@@@@@@@@@@@@@@@@");
  6229. auto res = std::make_shared<Response>();
  6230. auto error = Error::Success;
  6231. auto ret = cli_.send(req, *res, error);
  6232. ASSERT_TRUE(ret);
  6233. EXPECT_EQ(StatusCode::OK_200, res->status);
  6234. }
  6235. TEST_F(ServerTest, HeaderCountAtLimit) {
  6236. // Test with headers just under the 100 limit
  6237. httplib::Headers headers;
  6238. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6239. // This should keep us just under the 100 header limit
  6240. for (int i = 0; i < 95; i++) {
  6241. std::string name = "X-Test-Header-" + std::to_string(i);
  6242. std::string value = "value" + std::to_string(i);
  6243. headers.emplace(name, value);
  6244. }
  6245. // This should work fine as we're under the limit
  6246. auto res = cli_.Get("/hi", headers);
  6247. EXPECT_TRUE(res);
  6248. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6249. }
  6250. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6251. // Test with many headers to exceed the 100 limit
  6252. httplib::Headers headers;
  6253. // Add 150 headers to definitely exceed the 100 limit
  6254. for (int i = 0; i < 150; i++) {
  6255. std::string name = "X-Test-Header-" + std::to_string(i);
  6256. std::string value = "value" + std::to_string(i);
  6257. headers.emplace(name, value);
  6258. }
  6259. // This should fail due to exceeding header count limit
  6260. cli_.set_keep_alive(true);
  6261. auto res = cli_.Get("/hi", headers);
  6262. // The server should respond with 400 Bad Request
  6263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6264. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6265. EXPECT_EQ("close", res->get_header_value("Connection"));
  6266. EXPECT_FALSE(cli_.is_socket_open());
  6267. }
  6268. TEST_F(ServerTest, PercentEncoding) {
  6269. auto res = cli_.Get("/e%6edwith%");
  6270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6271. EXPECT_EQ(StatusCode::OK_200, res->status);
  6272. }
  6273. TEST_F(ServerTest, PercentEncodingUnicode) {
  6274. auto res = cli_.Get("/e%u006edwith%");
  6275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6276. EXPECT_EQ(StatusCode::OK_200, res->status);
  6277. }
  6278. TEST_F(ServerTest, InvalidPercentEncoding) {
  6279. auto res = cli_.Get("/%endwith%");
  6280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6281. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6282. }
  6283. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6284. auto res = cli_.Get("/%uendwith%");
  6285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6286. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6287. }
  6288. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6289. auto res = cli_.Get("/hello?aaa=bbb%");
  6290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6291. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6292. }
  6293. TEST_F(ServerTest, PlusSignEncoding) {
  6294. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6296. EXPECT_EQ(StatusCode::OK_200, res->status);
  6297. EXPECT_EQ("a +b", res->body);
  6298. }
  6299. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6300. // This test simulates a potential DoS attack using many headers
  6301. // to verify our security fix prevents memory exhaustion
  6302. httplib::Headers attack_headers;
  6303. // Attempt to add many headers like an attacker would (200 headers to far
  6304. // exceed limit)
  6305. for (int i = 0; i < 200; i++) {
  6306. std::string name = "X-Attack-Header-" + std::to_string(i);
  6307. std::string value = "attack_payload_" + std::to_string(i);
  6308. attack_headers.emplace(name, value);
  6309. }
  6310. // Try to POST with excessive headers
  6311. cli_.set_keep_alive(true);
  6312. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6313. // Should either fail or return 400 Bad Request due to security limit
  6314. if (res) {
  6315. // If we get a response, it should be 400 Bad Request
  6316. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6317. EXPECT_EQ("close", res->get_header_value("Connection"));
  6318. }
  6319. EXPECT_FALSE(cli_.is_socket_open());
  6320. }
  6321. TEST_F(ServerTest, MultipartFormData) {
  6322. UploadFormDataItems items = {
  6323. {"text1", "text default", "", ""},
  6324. {"text2", "aωb", "", ""},
  6325. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6326. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6327. {"file3", "", "", "application/octet-stream"},
  6328. {"file4", "", "", " application/json tmp-string "}};
  6329. auto res = cli_.Post("/multipart", items);
  6330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6331. EXPECT_EQ(StatusCode::OK_200, res->status);
  6332. }
  6333. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6334. UploadFormDataItems items = {
  6335. {"text", "default text", "", ""},
  6336. {"multi_text1", "aaaaa", "", ""},
  6337. {"multi_text1", "bbbbb", "", ""},
  6338. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6339. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6340. "application/json"},
  6341. };
  6342. auto res = cli_.Post("/multipart/multi_file_values", items);
  6343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6344. EXPECT_EQ(StatusCode::OK_200, res->status);
  6345. }
  6346. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6347. auto res = cli_.Get("/hi");
  6348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6349. EXPECT_EQ(StatusCode::OK_200, res->status);
  6350. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6351. EXPECT_EQ("Hello World!", res->body);
  6352. }
  6353. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6354. Request req;
  6355. req.method = "POST";
  6356. req.path = "/chunked";
  6357. std::string host_and_port;
  6358. host_and_port += HOST;
  6359. host_and_port += ":";
  6360. host_and_port += std::to_string(PORT);
  6361. req.headers.emplace("Host", host_and_port.c_str());
  6362. req.headers.emplace("Accept", "*/*");
  6363. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6364. req.headers.emplace("Content-Type", "text/plain");
  6365. req.headers.emplace("Content-Length", "0");
  6366. req.headers.emplace(
  6367. "Transfer-Encoding",
  6368. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6369. // Client does not chunk, so make a chunked body manually.
  6370. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6371. auto res = std::make_shared<Response>();
  6372. auto error = Error::Success;
  6373. auto ret = cli_.send(req, *res, error);
  6374. ASSERT_TRUE(ret);
  6375. EXPECT_EQ(StatusCode::OK_200, res->status);
  6376. }
  6377. template <typename ClientT>
  6378. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6379. int expected_status) {
  6380. Request req;
  6381. req.method = "POST";
  6382. req.path = "/chunked";
  6383. std::string host_and_port;
  6384. host_and_port += HOST;
  6385. host_and_port += ":";
  6386. host_and_port += std::to_string(PORT);
  6387. req.headers.emplace("Host", host_and_port.c_str());
  6388. req.headers.emplace("Content-Length", "0");
  6389. req.headers.emplace("Transfer-Encoding", "chunked");
  6390. req.body = body;
  6391. auto res = std::make_shared<Response>();
  6392. auto error = Error::Success;
  6393. ASSERT_TRUE(cli.send(req, *res, error));
  6394. EXPECT_EQ(expected_status, res->status);
  6395. }
  6396. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6397. // rather than treat them as valid lengths.
  6398. template <typename ClientT>
  6399. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6400. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6401. }
  6402. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6403. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6404. }
  6405. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6406. expect_chunked_body_rejected(
  6407. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6408. }
  6409. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6410. // chunk-size line carries no CR, LF or other control character ahead of its
  6411. // terminator. Such a line must be refused rather than read as extension text.
  6412. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6413. expect_chunked_body_rejected(
  6414. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6415. }
  6416. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6417. expect_chunked_body_rejected(
  6418. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6419. }
  6420. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6421. expect_chunked_body_rejected(
  6422. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6423. }
  6424. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6425. // The literal stays split: a hex escape consumes every hex digit that
  6426. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6427. expect_chunked_body_rejected(
  6428. cli_, "4;a\x01"
  6429. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6430. }
  6431. TEST_F(ServerTest, AcceptsChunkExtension) {
  6432. expect_chunked_body_status(cli_,
  6433. "4;name=value\r\ndech\r\n"
  6434. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6435. "0;last\r\n\r\n",
  6436. StatusCode::OK_200);
  6437. }
  6438. TEST_F(ServerTest, GetStreamed2) {
  6439. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6441. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6442. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6443. EXPECT_EQ(true, res->has_header("Content-Range"));
  6444. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6445. EXPECT_EQ(std::string("ab"), res->body);
  6446. }
  6447. TEST_F(ServerTest, GetStreamed) {
  6448. auto res = cli_.Get("/streamed");
  6449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6450. EXPECT_EQ(StatusCode::OK_200, res->status);
  6451. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6452. EXPECT_EQ(std::string("aaabbb"), res->body);
  6453. }
  6454. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6455. auto res = cli_.Get("/streamed-without-length",
  6456. Headers{make_range_header({{0, -1}})});
  6457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6458. EXPECT_EQ(StatusCode::OK_200, res->status);
  6459. EXPECT_EQ(false, res->has_header("Content-Length"));
  6460. EXPECT_EQ(false, res->has_header("Content-Range"));
  6461. EXPECT_EQ(std::string("abcdefg"), res->body);
  6462. }
  6463. TEST_F(ServerTest, GetStreamedWithRange1) {
  6464. auto res =
  6465. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6467. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6468. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6469. EXPECT_EQ(true, res->has_header("Content-Range"));
  6470. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6471. EXPECT_EQ(std::string("def"), res->body);
  6472. }
  6473. TEST_F(ServerTest, GetStreamedWithRange2) {
  6474. auto res =
  6475. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6477. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6478. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6479. EXPECT_EQ(true, res->has_header("Content-Range"));
  6480. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6481. EXPECT_EQ(std::string("bcdefg"), res->body);
  6482. }
  6483. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6484. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6486. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6487. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6488. EXPECT_EQ(true, res->has_header("Content-Range"));
  6489. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6490. EXPECT_EQ(std::string("efg"), res->body);
  6491. }
  6492. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6493. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6494. // the entire representation.
  6495. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6496. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6498. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6499. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6500. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6501. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6502. }
  6503. }
  6504. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6505. auto res =
  6506. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6508. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6509. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6510. EXPECT_EQ(false, res->has_header("Content-Range"));
  6511. EXPECT_EQ(0U, res->body.size());
  6512. }
  6513. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6514. // Only a 206 is served as a partial representation. Under any other status
  6515. // `apply_ranges()` reported the full content length, so the body must match
  6516. // that header, and the content provider must never be asked for an offset
  6517. // outside the representation.
  6518. auto check = [&](int status, const char *range) {
  6519. auto path =
  6520. std::string("/streamed-with-range?status=") + std::to_string(status);
  6521. auto ctx = path + " Range: " + range;
  6522. auto res = cli_.Get(path, Headers{{"Range", range}});
  6523. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6524. EXPECT_EQ(status, res->status) << ctx;
  6525. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6526. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6527. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6528. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6529. };
  6530. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6531. check(403, "bytes=3-5");
  6532. // The offset is far past the representation.
  6533. check(403, "bytes=100000-100200");
  6534. // `first_pos` is still -1 here, and the bounds asserts in
  6535. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6536. check(403, "bytes=-3");
  6537. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6538. // multipart branch would have written one that is empty.
  6539. check(403, "bytes=1-2, 4-5");
  6540. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6541. // covers the whole representation.
  6542. check(200, "bytes=3-5");
  6543. check(200, "bytes=1-2, 4-5");
  6544. }
  6545. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6546. auto res =
  6547. cli_.Get("/streamed-with-range",
  6548. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6549. "92233720368547758079223372036854775807"}});
  6550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6551. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6552. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6553. EXPECT_EQ(false, res->has_header("Content-Range"));
  6554. EXPECT_EQ(0U, res->body.size());
  6555. }
  6556. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6557. auto res = cli_.Get(
  6558. "/with-range",
  6559. Headers{{"Range",
  6560. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6561. {"Accept-Encoding", ""}});
  6562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6563. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6564. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6565. EXPECT_EQ(true, res->has_header("Content-Range"));
  6566. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6567. EXPECT_EQ(std::string("abcdefg"), res->body);
  6568. }
  6569. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6570. auto res = cli_.Get("/with-range", Headers{
  6571. {"Range", "bytes=0-"},
  6572. {"Accept-Encoding", ""},
  6573. });
  6574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6575. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6576. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6577. EXPECT_EQ(true, res->has_header("Content-Range"));
  6578. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6579. EXPECT_EQ(std::string("abcdefg"), res->body);
  6580. }
  6581. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6582. auto res = cli_.Get("/streamed-with-range",
  6583. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6585. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6586. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6587. EXPECT_EQ(false, res->has_header("Content-Range"));
  6588. EXPECT_EQ(267U, res->body.size());
  6589. // Check that both range contents are present
  6590. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6591. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6592. // Check that Content-Range headers are present for both ranges
  6593. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6594. std::string::npos);
  6595. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6596. std::string::npos);
  6597. }
  6598. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6599. Ranges ranges;
  6600. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6601. ranges.emplace_back(0, -1);
  6602. }
  6603. auto res = cli_.Get("/streamed-with-range?error",
  6604. Headers{{make_range_header(ranges)}});
  6605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6606. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6607. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6608. EXPECT_EQ(false, res->has_header("Content-Range"));
  6609. EXPECT_EQ(0U, res->body.size());
  6610. }
  6611. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6612. auto res = cli_.Get("/streamed-with-range",
  6613. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6615. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6616. EXPECT_EQ(5U, res->body.size());
  6617. // Check that overlapping ranges are coalesced into a single range
  6618. EXPECT_EQ("bcdef", res->body);
  6619. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6620. // Should be single range, not multipart
  6621. EXPECT_TRUE(res->has_header("Content-Range"));
  6622. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6623. }
  6624. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6625. auto res = cli_.Get("/streamed-with-range",
  6626. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6628. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6629. EXPECT_EQ(268U, res->body.size());
  6630. // Check that both range contents are present
  6631. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6632. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6633. // Check that Content-Range headers are present for both ranges
  6634. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6635. std::string::npos);
  6636. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6637. std::string::npos);
  6638. }
  6639. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6640. auto res = cli_.Get("/streamed-with-range",
  6641. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6643. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6644. EXPECT_EQ(269U, res->body.size());
  6645. // Check that both duplicate range contents are present
  6646. size_t first_abc = res->body.find("abc\r\n");
  6647. EXPECT_TRUE(first_abc != std::string::npos);
  6648. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6649. EXPECT_TRUE(second_abc != std::string::npos);
  6650. // Check that Content-Range headers are present for both ranges
  6651. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6652. EXPECT_TRUE(first_range != std::string::npos);
  6653. size_t second_range =
  6654. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6655. EXPECT_TRUE(second_range != std::string::npos);
  6656. }
  6657. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6658. auto res =
  6659. cli_.Get("/streamed-with-range?error",
  6660. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6662. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6663. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6664. EXPECT_EQ(false, res->has_header("Content-Range"));
  6665. EXPECT_EQ(0U, res->body.size());
  6666. }
  6667. TEST_F(ServerTest, GetStreamedEndless) {
  6668. uint64_t offset = 0;
  6669. auto res = cli_.Get("/streamed-cancel",
  6670. [&](const char * /*data*/, uint64_t data_length) {
  6671. if (offset < 100) {
  6672. offset += data_length;
  6673. return true;
  6674. }
  6675. return false;
  6676. });
  6677. ASSERT_TRUE(!res);
  6678. EXPECT_EQ(Error::Canceled, res.error());
  6679. }
  6680. TEST_F(ServerTest, ClientStop) {
  6681. std::atomic_size_t count{4};
  6682. std::vector<std::thread> threads;
  6683. for (auto i = count.load(); i != 0; --i) {
  6684. threads.emplace_back([&]() {
  6685. auto res = cli_.Get("/streamed-cancel",
  6686. [&](const char *, uint64_t) { return true; });
  6687. --count;
  6688. ASSERT_TRUE(!res);
  6689. EXPECT_TRUE(res.error() == Error::Canceled ||
  6690. res.error() == Error::Read || res.error() == Error::Write);
  6691. });
  6692. }
  6693. std::this_thread::sleep_for(std::chrono::seconds(2));
  6694. while (count != 0) {
  6695. cli_.stop();
  6696. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6697. }
  6698. for (auto &t : threads) {
  6699. t.join();
  6700. }
  6701. }
  6702. TEST_F(ServerTest, GetWithRange1) {
  6703. auto res = cli_.Get("/with-range", Headers{
  6704. make_range_header({{3, 5}}),
  6705. {"Accept-Encoding", ""},
  6706. });
  6707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6708. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6709. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6710. EXPECT_EQ(true, res->has_header("Content-Range"));
  6711. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6712. EXPECT_EQ(std::string("def"), res->body);
  6713. }
  6714. TEST_F(ServerTest, GetWithRange2) {
  6715. auto res = cli_.Get("/with-range", Headers{
  6716. make_range_header({{1, -1}}),
  6717. {"Accept-Encoding", ""},
  6718. });
  6719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6720. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6721. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6722. EXPECT_EQ(true, res->has_header("Content-Range"));
  6723. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6724. EXPECT_EQ(std::string("bcdefg"), res->body);
  6725. }
  6726. TEST_F(ServerTest, GetWithRange3) {
  6727. auto res = cli_.Get("/with-range", Headers{
  6728. make_range_header({{0, 0}}),
  6729. {"Accept-Encoding", ""},
  6730. });
  6731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6732. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6733. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6734. EXPECT_EQ(true, res->has_header("Content-Range"));
  6735. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6736. EXPECT_EQ(std::string("a"), res->body);
  6737. }
  6738. TEST_F(ServerTest, GetWithRange4) {
  6739. auto res = cli_.Get("/with-range", Headers{
  6740. make_range_header({{-1, 2}}),
  6741. {"Accept-Encoding", ""},
  6742. });
  6743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6744. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6745. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6746. EXPECT_EQ(true, res->has_header("Content-Range"));
  6747. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6748. EXPECT_EQ(std::string("fg"), res->body);
  6749. }
  6750. TEST_F(ServerTest, GetWithRange5) {
  6751. auto res = cli_.Get("/with-range", Headers{
  6752. make_range_header({{0, 5}}),
  6753. {"Accept-Encoding", ""},
  6754. });
  6755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6756. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6757. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6758. EXPECT_EQ(true, res->has_header("Content-Range"));
  6759. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6760. EXPECT_EQ(std::string("abcdef"), res->body);
  6761. }
  6762. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6763. auto res =
  6764. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6766. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6767. }
  6768. TEST_F(ServerTest, GetWithRangeMultipart) {
  6769. auto res =
  6770. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6772. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6773. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6774. EXPECT_EQ(false, res->has_header("Content-Range"));
  6775. EXPECT_EQ(267U, res->body.size());
  6776. }
  6777. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6778. auto res = cli_.Get("/with-range",
  6779. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6781. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6782. }
  6783. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6784. auto res = cli_.Get("/with-range-customized-response",
  6785. Headers{{make_range_header({{1, 2}})}});
  6786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6787. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6788. EXPECT_EQ(true, res->has_header("Content-Length"));
  6789. EXPECT_EQ(false, res->has_header("Content-Range"));
  6790. EXPECT_EQ(JSON_DATA, res->body);
  6791. }
  6792. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6793. auto res = cli_.Get("/with-range-customized-response",
  6794. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6796. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6797. EXPECT_EQ(true, res->has_header("Content-Length"));
  6798. EXPECT_EQ(false, res->has_header("Content-Range"));
  6799. EXPECT_EQ(JSON_DATA, res->body);
  6800. }
  6801. TEST_F(ServerTest, Issue1772) {
  6802. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6804. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6805. }
  6806. TEST_F(ServerTest, Issue609) {
  6807. auto res = cli_.Delete("/issue609");
  6808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6809. EXPECT_EQ(StatusCode::OK_200, res->status);
  6810. EXPECT_EQ(std::string("ok"), res->body);
  6811. }
  6812. TEST_F(ServerTest, GetStreamedChunked) {
  6813. auto res = cli_.Get("/streamed-chunked");
  6814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6815. EXPECT_EQ(StatusCode::OK_200, res->status);
  6816. EXPECT_EQ(std::string("123456789"), res->body);
  6817. }
  6818. TEST_F(ServerTest, GetStreamedChunked2) {
  6819. auto res = cli_.Get("/streamed-chunked2");
  6820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6821. EXPECT_EQ(StatusCode::OK_200, res->status);
  6822. EXPECT_EQ(std::string("123456789"), res->body);
  6823. }
  6824. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6825. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6827. EXPECT_EQ(StatusCode::OK_200, res->status);
  6828. EXPECT_EQ(std::string("123456789"), res->body);
  6829. EXPECT_TRUE(res->has_header("Trailer"));
  6830. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6831. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6832. // Trailers are now stored separately from headers (security fix)
  6833. EXPECT_EQ(2U, res->trailers.size());
  6834. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6835. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6836. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6837. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6838. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6839. // Verify trailers are NOT in headers (security verification)
  6840. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6841. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6842. }
  6843. TEST_F(ServerTest, LargeChunkedPost) {
  6844. Request req;
  6845. req.method = "POST";
  6846. req.path = "/large-chunked";
  6847. std::string host_and_port;
  6848. host_and_port += HOST;
  6849. host_and_port += ":";
  6850. host_and_port += std::to_string(PORT);
  6851. req.headers.emplace("Host", host_and_port.c_str());
  6852. req.headers.emplace("Accept", "*/*");
  6853. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6854. req.headers.emplace("Content-Type", "text/plain");
  6855. req.headers.emplace("Content-Length", "0");
  6856. req.headers.emplace("Transfer-Encoding", "chunked");
  6857. std::string long_string(30 * 1024u, 'a');
  6858. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6859. // Attempt to make a large enough post to exceed OS buffers, to test that
  6860. // the server handles short reads if the full chunk data isn't available.
  6861. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6862. auto res = std::make_shared<Response>();
  6863. auto error = Error::Success;
  6864. auto ret = cli_.send(req, *res, error);
  6865. ASSERT_TRUE(ret);
  6866. EXPECT_EQ(StatusCode::OK_200, res->status);
  6867. }
  6868. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6869. auto res = cli_.Get("/remote_addr");
  6870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6871. EXPECT_EQ(StatusCode::OK_200, res->status);
  6872. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6873. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6874. }
  6875. TEST_F(ServerTest, GetMethodLocalAddr) {
  6876. auto res = cli_.Get("/local_addr");
  6877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6878. EXPECT_EQ(StatusCode::OK_200, res->status);
  6879. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6880. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6881. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6882. }
  6883. TEST_F(ServerTest, HTTPResponseSplitting) {
  6884. auto res = cli_.Get("/http_response_splitting");
  6885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6886. EXPECT_EQ(StatusCode::OK_200, res->status);
  6887. }
  6888. TEST_F(ServerTest, SlowRequest) {
  6889. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6890. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6891. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6892. }
  6893. #if 0
  6894. TEST_F(ServerTest, SlowPost) {
  6895. char buffer[64 * 1024];
  6896. memset(buffer, 0x42, sizeof(buffer));
  6897. auto res = cli_.Post(
  6898. "/slowpost", 64 * 1024 * 1024,
  6899. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6900. auto ret = sink.write(buffer, sizeof(buffer));
  6901. EXPECT_TRUE(ret);
  6902. return true;
  6903. },
  6904. "text/plain");
  6905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6906. EXPECT_EQ(StatusCode::OK_200, res->status);
  6907. }
  6908. TEST_F(ServerTest, SlowPostFail) {
  6909. char buffer[64 * 1024];
  6910. memset(buffer, 0x42, sizeof(buffer));
  6911. cli_.set_write_timeout(std::chrono::seconds(0));
  6912. auto res = cli_.Post(
  6913. "/slowpost", 64 * 1024 * 1024,
  6914. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6915. sink.write(buffer, sizeof(buffer));
  6916. return true;
  6917. },
  6918. "text/plain");
  6919. ASSERT_TRUE(!res);
  6920. EXPECT_EQ(Error::Write, res.error());
  6921. }
  6922. #endif
  6923. TEST_F(ServerTest, Put) {
  6924. auto res = cli_.Put("/put", "PUT", "text/plain");
  6925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6926. EXPECT_EQ(StatusCode::OK_200, res->status);
  6927. EXPECT_EQ("PUT", res->body);
  6928. }
  6929. TEST_F(ServerTest, PutWithContentProvider) {
  6930. auto res = cli_.Put(
  6931. "/put", 3,
  6932. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6933. sink.os << "PUT";
  6934. return true;
  6935. },
  6936. "text/plain");
  6937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6938. EXPECT_EQ(StatusCode::OK_200, res->status);
  6939. EXPECT_EQ("PUT", res->body);
  6940. }
  6941. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6942. auto res = cli_.Post(
  6943. "/post", 42,
  6944. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6945. return false;
  6946. },
  6947. "text/plain");
  6948. ASSERT_TRUE(!res);
  6949. EXPECT_EQ(Error::Canceled, res.error());
  6950. }
  6951. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6952. auto res = cli_.Put(
  6953. "/put",
  6954. [](size_t /*offset*/, DataSink &sink) {
  6955. sink.os << "PUT";
  6956. sink.done();
  6957. return true;
  6958. },
  6959. "text/plain");
  6960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6961. EXPECT_EQ(StatusCode::OK_200, res->status);
  6962. EXPECT_EQ("PUT", res->body);
  6963. }
  6964. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6965. auto res = cli_.Post(
  6966. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6967. "text/plain");
  6968. ASSERT_TRUE(!res);
  6969. EXPECT_EQ(Error::Canceled, res.error());
  6970. }
  6971. TEST_F(ServerTest, PostLoopBack) {
  6972. std::string body;
  6973. auto res = cli_.Post(
  6974. "/post-loopback", 9,
  6975. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6976. EXPECT_EQ(9u, length);
  6977. sink.write("123", 3);
  6978. sink.write("456", 3);
  6979. sink.write("789", 3);
  6980. return true;
  6981. },
  6982. "text/plain",
  6983. [&body](const char *data, size_t data_length) {
  6984. body.append(data, data_length);
  6985. return true;
  6986. });
  6987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6988. EXPECT_EQ(StatusCode::OK_200, res->status);
  6989. EXPECT_EQ("123456789", body);
  6990. }
  6991. TEST_F(ServerTest, PutLoopBack) {
  6992. std::string body;
  6993. auto res = cli_.Put(
  6994. "/put-loopback", 9,
  6995. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6996. EXPECT_EQ(9u, length);
  6997. sink.write("123", 3);
  6998. sink.write("456", 3);
  6999. sink.write("789", 3);
  7000. return true;
  7001. },
  7002. "text/plain",
  7003. [&body](const char *data, size_t data_length) {
  7004. body.append(data, data_length);
  7005. return true;
  7006. });
  7007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7008. EXPECT_EQ(StatusCode::OK_200, res->status);
  7009. EXPECT_EQ("123456789", body);
  7010. }
  7011. TEST_F(ServerTest, PatchLoopBack) {
  7012. std::string body;
  7013. auto res = cli_.Patch(
  7014. "/patch-loopback", 9,
  7015. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7016. EXPECT_EQ(9u, length);
  7017. sink.write("123", 3);
  7018. sink.write("456", 3);
  7019. sink.write("789", 3);
  7020. return true;
  7021. },
  7022. "text/plain",
  7023. [&body](const char *data, size_t data_length) {
  7024. body.append(data, data_length);
  7025. return true;
  7026. });
  7027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7028. EXPECT_EQ(StatusCode::OK_200, res->status);
  7029. EXPECT_EQ("123456789", body);
  7030. }
  7031. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7032. std::string body;
  7033. auto res = cli_.Post(
  7034. "/post-loopback",
  7035. [](size_t /*offset*/, DataSink &sink) {
  7036. sink.write("123", 3);
  7037. sink.write("456", 3);
  7038. sink.write("789", 3);
  7039. sink.done();
  7040. return true;
  7041. },
  7042. "text/plain",
  7043. [&body](const char *data, size_t data_length) {
  7044. body.append(data, data_length);
  7045. return true;
  7046. });
  7047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7048. EXPECT_EQ(StatusCode::OK_200, res->status);
  7049. EXPECT_EQ("123456789", body);
  7050. }
  7051. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7052. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7053. cli_.set_compress(true);
  7054. auto res = cli_.Put(
  7055. "/put", 3,
  7056. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7057. sink.os << "PUT";
  7058. return true;
  7059. },
  7060. "text/plain");
  7061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7062. EXPECT_EQ(StatusCode::OK_200, res->status);
  7063. EXPECT_EQ("PUT", res->body);
  7064. }
  7065. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7066. cli_.set_compress(true);
  7067. auto res = cli_.Post(
  7068. "/post", 42,
  7069. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7070. return false;
  7071. },
  7072. "text/plain");
  7073. ASSERT_TRUE(!res);
  7074. EXPECT_EQ(Error::Canceled, res.error());
  7075. }
  7076. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7077. cli_.set_compress(true);
  7078. auto res = cli_.Put(
  7079. "/put",
  7080. [](size_t /*offset*/, DataSink &sink) {
  7081. sink.os << "PUT";
  7082. sink.done();
  7083. return true;
  7084. },
  7085. "text/plain");
  7086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7087. EXPECT_EQ(StatusCode::OK_200, res->status);
  7088. EXPECT_EQ("PUT", res->body);
  7089. }
  7090. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7091. cli_.set_compress(true);
  7092. auto res = cli_.Post(
  7093. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7094. "text/plain");
  7095. ASSERT_TRUE(!res);
  7096. EXPECT_EQ(Error::Canceled, res.error());
  7097. }
  7098. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7099. cli_.set_compress(true);
  7100. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7102. EXPECT_EQ(StatusCode::OK_200, res->status);
  7103. EXPECT_EQ(LARGE_DATA, res->body);
  7104. }
  7105. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7106. #ifdef CPPHTTPLIB_SSL_ENABLED
  7107. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7108. Client cli(s.c_str());
  7109. cli.enable_server_certificate_verification(false);
  7110. #else
  7111. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7112. Client cli(s.c_str());
  7113. #endif
  7114. cli.set_compress(true);
  7115. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7117. EXPECT_EQ(StatusCode::OK_200, res->status);
  7118. EXPECT_EQ(LARGE_DATA, res->body);
  7119. // The compressed size should be less than a 10th of the original. May vary
  7120. // depending on the zlib library.
  7121. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7122. static_cast<uint64_t>(10 * 1024 * 1024));
  7123. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7124. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7125. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7126. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7127. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7128. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7129. #endif
  7130. }
  7131. TEST_F(ServerTest, PutContentWithDeflate) {
  7132. cli_.set_compress(false);
  7133. Headers headers;
  7134. headers.emplace("Content-Encoding", "deflate");
  7135. // PUT in deflate format:
  7136. auto res = cli_.Put("/put", headers,
  7137. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7139. EXPECT_EQ(StatusCode::OK_200, res->status);
  7140. EXPECT_EQ("PUT", res->body);
  7141. }
  7142. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7143. Headers headers;
  7144. headers.emplace("Accept-Encoding", "gzip, deflate");
  7145. auto res = cli_.Get("/streamed-chunked", headers);
  7146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7147. EXPECT_EQ(StatusCode::OK_200, res->status);
  7148. EXPECT_EQ(std::string("123456789"), res->body);
  7149. }
  7150. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7151. Headers headers;
  7152. headers.emplace("Accept-Encoding", "gzip, deflate");
  7153. auto res = cli_.Get("/streamed-chunked2", headers);
  7154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7155. EXPECT_EQ(StatusCode::OK_200, res->status);
  7156. EXPECT_EQ(std::string("123456789"), res->body);
  7157. }
  7158. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7159. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7161. EXPECT_EQ(StatusCode::OK_200, res->status);
  7162. }
  7163. TEST(GzipDecompressor, ChunkedDecompression) {
  7164. std::string data;
  7165. for (size_t i = 0; i < 32 * 1024; ++i) {
  7166. data.push_back(static_cast<char>('a' + i % 26));
  7167. }
  7168. std::string compressed_data;
  7169. {
  7170. httplib::detail::gzip_compressor compressor;
  7171. bool result = compressor.compress(
  7172. data.data(), data.size(),
  7173. /*last=*/true,
  7174. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7175. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7176. compressed_data_size);
  7177. return true;
  7178. });
  7179. ASSERT_TRUE(result);
  7180. }
  7181. std::string decompressed_data;
  7182. {
  7183. httplib::detail::gzip_decompressor decompressor;
  7184. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7185. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7186. size_t chunk_size = 130;
  7187. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7188. chunk_begin += chunk_size) {
  7189. size_t current_chunk_size =
  7190. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7191. bool result = decompressor.decompress(
  7192. compressed_data.data() + chunk_begin, current_chunk_size,
  7193. [&](const char *decompressed_data_chunk,
  7194. size_t decompressed_data_chunk_size) {
  7195. decompressed_data.insert(decompressed_data.size(),
  7196. decompressed_data_chunk,
  7197. decompressed_data_chunk_size);
  7198. return true;
  7199. });
  7200. ASSERT_TRUE(result);
  7201. }
  7202. }
  7203. ASSERT_EQ(data, decompressed_data);
  7204. }
  7205. TEST(GzipDecompressor, DeflateDecompression) {
  7206. std::string original_text = "Raw deflate without gzip";
  7207. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7208. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7209. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7210. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7211. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7212. std::string decompressed_data;
  7213. {
  7214. httplib::detail::gzip_decompressor decompressor;
  7215. bool result = decompressor.decompress(
  7216. compressed_data.data(), compressed_data.size(),
  7217. [&](const char *decompressed_data_chunk,
  7218. size_t decompressed_data_chunk_size) {
  7219. decompressed_data.insert(decompressed_data.size(),
  7220. decompressed_data_chunk,
  7221. decompressed_data_chunk_size);
  7222. return true;
  7223. });
  7224. ASSERT_TRUE(result);
  7225. }
  7226. ASSERT_EQ(original_text, decompressed_data);
  7227. }
  7228. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7229. std::string original_text = "Raw deflate without gzip";
  7230. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7231. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7232. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7233. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7234. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7235. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7236. std::string decompressed_data;
  7237. {
  7238. httplib::detail::gzip_decompressor decompressor;
  7239. bool result = decompressor.decompress(
  7240. compressed_data.data(), compressed_data.size(),
  7241. [&](const char *decompressed_data_chunk,
  7242. size_t decompressed_data_chunk_size) {
  7243. decompressed_data.insert(decompressed_data.size(),
  7244. decompressed_data_chunk,
  7245. decompressed_data_chunk_size);
  7246. return true;
  7247. });
  7248. ASSERT_TRUE(result);
  7249. }
  7250. ASSERT_EQ(original_text, decompressed_data);
  7251. }
  7252. #endif
  7253. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7254. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7255. Headers headers;
  7256. headers.emplace("Accept-Encoding", "br");
  7257. auto res = cli_.Get("/streamed-chunked", headers);
  7258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7259. EXPECT_EQ(StatusCode::OK_200, res->status);
  7260. EXPECT_EQ(std::string("123456789"), res->body);
  7261. }
  7262. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7263. Headers headers;
  7264. headers.emplace("Accept-Encoding", "br");
  7265. auto res = cli_.Get("/streamed-chunked2", headers);
  7266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7267. EXPECT_EQ(StatusCode::OK_200, res->status);
  7268. EXPECT_EQ(std::string("123456789"), res->body);
  7269. }
  7270. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7271. cli_.set_compress(true);
  7272. auto res = cli_.Put(
  7273. "/put", 3,
  7274. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7275. sink.os << "PUT";
  7276. return true;
  7277. },
  7278. "text/plain");
  7279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7280. EXPECT_EQ(StatusCode::OK_200, res->status);
  7281. EXPECT_EQ("PUT", res->body);
  7282. }
  7283. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7284. cli_.set_compress(true);
  7285. auto res = cli_.Put(
  7286. "/put",
  7287. [](size_t /*offset*/, DataSink &sink) {
  7288. sink.os << "PUT";
  7289. sink.done();
  7290. return true;
  7291. },
  7292. "text/plain");
  7293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7294. EXPECT_EQ(StatusCode::OK_200, res->status);
  7295. EXPECT_EQ("PUT", res->body);
  7296. }
  7297. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7298. cli_.set_compress(true);
  7299. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7301. EXPECT_EQ(StatusCode::OK_200, res->status);
  7302. EXPECT_EQ(LARGE_DATA, res->body);
  7303. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7304. }
  7305. #endif
  7306. TEST_F(ServerTest, Patch) {
  7307. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7309. EXPECT_EQ(StatusCode::OK_200, res->status);
  7310. EXPECT_EQ("PATCH", res->body);
  7311. }
  7312. TEST_F(ServerTest, Delete) {
  7313. auto res = cli_.Delete("/delete");
  7314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7315. EXPECT_EQ(StatusCode::OK_200, res->status);
  7316. EXPECT_EQ("DELETE", res->body);
  7317. }
  7318. TEST_F(ServerTest, DeleteContentReceiver) {
  7319. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7321. EXPECT_EQ(StatusCode::OK_200, res->status);
  7322. EXPECT_EQ("content", res->body);
  7323. }
  7324. TEST_F(ServerTest, Options) {
  7325. auto res = cli_.Options("*");
  7326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7327. EXPECT_EQ(StatusCode::OK_200, res->status);
  7328. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7329. EXPECT_TRUE(res->body.empty());
  7330. }
  7331. TEST_F(ServerTest, URL) {
  7332. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7334. EXPECT_EQ(StatusCode::OK_200, res->status);
  7335. }
  7336. TEST_F(ServerTest, ArrayParam) {
  7337. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7339. EXPECT_EQ(StatusCode::OK_200, res->status);
  7340. }
  7341. TEST_F(ServerTest, ArrayParamValues) {
  7342. auto res =
  7343. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7345. EXPECT_EQ(StatusCode::OK_200, res->status);
  7346. }
  7347. TEST_F(ServerTest, NoMultipleHeaders) {
  7348. Headers headers = {{"Content-Length", "5"}};
  7349. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7350. "text/plain");
  7351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7352. EXPECT_EQ(StatusCode::OK_200, res->status);
  7353. }
  7354. TEST_F(ServerTest, PostContentReceiver) {
  7355. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7357. ASSERT_EQ(StatusCode::OK_200, res->status);
  7358. ASSERT_EQ("content", res->body);
  7359. }
  7360. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7361. UploadFormDataItems items = {
  7362. {"text1", "text default", "", ""},
  7363. {"text2", "aωb", "", ""},
  7364. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7365. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7366. {"file3", "", "", "application/octet-stream"},
  7367. };
  7368. auto res = cli_.Post("/content_receiver", items);
  7369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7370. EXPECT_EQ(StatusCode::OK_200, res->status);
  7371. }
  7372. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7373. UploadFormDataItems items = {
  7374. {"text1", "text default", "", ""},
  7375. {"text2", "aωb", "", ""},
  7376. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7377. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7378. {"file3", "", "", "application/octet-stream"},
  7379. };
  7380. auto boundary = std::string("+++++");
  7381. std::string body;
  7382. for (const auto &item : items) {
  7383. body += "--" + boundary + "\r\n";
  7384. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7385. if (!item.filename.empty()) {
  7386. body += "; filename=\"" + item.filename + "\"";
  7387. }
  7388. body += "\r\n";
  7389. if (!item.content_type.empty()) {
  7390. body += "Content-Type: " + item.content_type + "\r\n";
  7391. }
  7392. body += "\r\n";
  7393. body += item.content + "\r\n";
  7394. }
  7395. body += "--" + boundary + "--\r\n";
  7396. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7397. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7399. EXPECT_EQ(StatusCode::OK_200, res->status);
  7400. }
  7401. TEST(MultipartFormDataTest, FieldEscaping) {
  7402. Server svr;
  7403. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7404. const ContentReader &content_reader) {
  7405. ASSERT_TRUE(req.is_multipart_form_data());
  7406. std::vector<FormData> received;
  7407. content_reader(
  7408. [&](const FormData &file) {
  7409. received.push_back(file);
  7410. return true;
  7411. },
  7412. [&](const char *data, size_t data_length) {
  7413. received.back().content.append(data, data_length);
  7414. return true;
  7415. });
  7416. // '"', CR and LF in names and filenames are escaped following the
  7417. // WHATWG HTML standard, so each part still parses as a single part
  7418. // with no injected headers. Content types get CR/LF escaped too,
  7419. // while '"' (legal there, e.g. quoted charset) is preserved.
  7420. ASSERT_EQ(4U, received.size());
  7421. EXPECT_EQ("na%22me", received[0].name);
  7422. EXPECT_EQ("quoted name", received[0].content);
  7423. EXPECT_EQ("file", received[1].name);
  7424. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7425. received[1].filename);
  7426. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7427. EXPECT_EQ("injected", received[1].content);
  7428. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7429. EXPECT_EQ("my%22file.txt", received[2].filename);
  7430. EXPECT_EQ("cr lf name", received[2].content);
  7431. EXPECT_EQ("typed", received[3].name);
  7432. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7433. received[3].content_type);
  7434. EXPECT_EQ("typed content", received[3].content);
  7435. });
  7436. auto port = svr.bind_to_any_port("localhost");
  7437. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7438. auto se = detail::scope_exit([&] {
  7439. svr.stop();
  7440. t.join();
  7441. ASSERT_FALSE(svr.is_running());
  7442. });
  7443. svr.wait_until_ready();
  7444. Client cli("localhost", port);
  7445. UploadFormDataItems items = {
  7446. {"na\"me", "quoted name", "", ""},
  7447. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7448. "application/octet-stream"},
  7449. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7450. {"typed", "typed content", "",
  7451. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7452. };
  7453. auto res = cli.Post("/post", items);
  7454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7455. EXPECT_EQ(StatusCode::OK_200, res->status);
  7456. }
  7457. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7458. const UploadFormDataItems items = {
  7459. {"name1", "Content 1", "", ""},
  7460. {"name2", "Content 2", "file2.txt", "text/plain"},
  7461. };
  7462. Server svr;
  7463. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7464. const ContentReader &content_reader) {
  7465. ASSERT_TRUE(req.is_multipart_form_data());
  7466. std::vector<FormData> received;
  7467. content_reader(
  7468. [&](const FormData &file) {
  7469. received.push_back(file);
  7470. return true;
  7471. },
  7472. [&](const char *data, size_t data_length) {
  7473. received.back().content.append(data, data_length);
  7474. return true;
  7475. });
  7476. ASSERT_EQ(2U, received.size());
  7477. EXPECT_EQ("name1", received[0].name);
  7478. EXPECT_EQ("Content 1", received[0].content);
  7479. EXPECT_EQ("name2", received[1].name);
  7480. EXPECT_EQ("Content 2", received[1].content);
  7481. EXPECT_EQ("file2.txt", received[1].filename);
  7482. EXPECT_EQ("text/plain", received[1].content_type);
  7483. });
  7484. auto port = svr.bind_to_any_port("localhost");
  7485. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7486. auto se = detail::scope_exit([&] {
  7487. svr.stop();
  7488. t.join();
  7489. ASSERT_FALSE(svr.is_running());
  7490. });
  7491. svr.wait_until_ready();
  7492. Client cli("localhost", port);
  7493. // Whole-body serialization with a generated boundary
  7494. {
  7495. MultipartFormDataWriter writer;
  7496. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7497. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7498. writer.content_type());
  7499. auto body = writer.serialize(items);
  7500. EXPECT_EQ(body.size(), writer.content_length(items));
  7501. auto res = cli.Post("/post", body, writer.content_type());
  7502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7503. EXPECT_EQ(StatusCode::OK_200, res->status);
  7504. }
  7505. // Per-part framing with a custom boundary via a content provider
  7506. {
  7507. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7508. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7509. MultipartFormDataWriter writer("custom-boundary_123");
  7510. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7511. std::string body;
  7512. for (const auto &item : items) {
  7513. body += writer.item_begin(item);
  7514. body += item.content;
  7515. body += MultipartFormDataWriter::item_end();
  7516. }
  7517. body += writer.finish();
  7518. EXPECT_EQ(body.size(), writer.content_length(items));
  7519. auto res = cli.Post(
  7520. "/post", body.size(),
  7521. [&](size_t offset, size_t length, DataSink &sink) {
  7522. sink.write(body.data() + offset, length);
  7523. return true;
  7524. },
  7525. writer.content_type());
  7526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7527. EXPECT_EQ(StatusCode::OK_200, res->status);
  7528. }
  7529. }
  7530. TEST_F(ServerTest, PostContentReceiverGzip) {
  7531. cli_.set_compress(true);
  7532. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7534. ASSERT_EQ(StatusCode::OK_200, res->status);
  7535. ASSERT_EQ("content", res->body);
  7536. }
  7537. TEST_F(ServerTest, PutContentReceiver) {
  7538. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7540. ASSERT_EQ(StatusCode::OK_200, res->status);
  7541. ASSERT_EQ("content", res->body);
  7542. }
  7543. TEST_F(ServerTest, PatchContentReceiver) {
  7544. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7546. ASSERT_EQ(StatusCode::OK_200, res->status);
  7547. ASSERT_EQ("content", res->body);
  7548. }
  7549. template <typename ClientType>
  7550. void TestWithHeadersAndContentReceiver(
  7551. ClientType &cli,
  7552. std::function<Result(ClientType &, const std::string &, const Headers &,
  7553. const std::string &, const std::string &,
  7554. ContentReceiver, DownloadProgress)>
  7555. request_func) {
  7556. Headers headers;
  7557. headers.emplace("X-Custom-Header", "test-value");
  7558. std::string received_body;
  7559. auto res = request_func(
  7560. cli, "/content_receiver", headers, "content", "application/json",
  7561. [&](const char *data, size_t data_length) {
  7562. received_body.append(data, data_length);
  7563. return true;
  7564. },
  7565. nullptr);
  7566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7567. EXPECT_EQ(StatusCode::OK_200, res->status);
  7568. EXPECT_EQ("content", received_body);
  7569. }
  7570. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7571. #ifdef CPPHTTPLIB_SSL_ENABLED
  7572. using ClientT = SSLClient;
  7573. #else
  7574. using ClientT = Client;
  7575. #endif
  7576. TestWithHeadersAndContentReceiver<ClientT>(
  7577. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7578. const std::string &body, const std::string &content_type,
  7579. ContentReceiver receiver, DownloadProgress progress) {
  7580. return cli.Post(path, headers, body, content_type, receiver, progress);
  7581. });
  7582. }
  7583. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7584. #ifdef CPPHTTPLIB_SSL_ENABLED
  7585. using ClientT = SSLClient;
  7586. #else
  7587. using ClientT = Client;
  7588. #endif
  7589. TestWithHeadersAndContentReceiver<ClientT>(
  7590. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7591. const std::string &body, const std::string &content_type,
  7592. ContentReceiver receiver, DownloadProgress progress) {
  7593. return cli.Put(path, headers, body, content_type, receiver, progress);
  7594. });
  7595. }
  7596. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7597. #ifdef CPPHTTPLIB_SSL_ENABLED
  7598. using ClientT = SSLClient;
  7599. #else
  7600. using ClientT = Client;
  7601. #endif
  7602. TestWithHeadersAndContentReceiver<ClientT>(
  7603. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7604. const std::string &body, const std::string &content_type,
  7605. ContentReceiver receiver, DownloadProgress progress) {
  7606. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7607. });
  7608. }
  7609. template <typename ClientType>
  7610. void TestWithHeadersAndContentReceiverWithProgress(
  7611. ClientType &cli,
  7612. std::function<Result(ClientType &, const std::string &, const Headers &,
  7613. const std::string &, const std::string &,
  7614. ContentReceiver, DownloadProgress)>
  7615. request_func) {
  7616. Headers headers;
  7617. headers.emplace("X-Test-Header", "progress-test");
  7618. std::string received_body;
  7619. auto progress_called = false;
  7620. auto res = request_func(
  7621. cli, "/content_receiver", headers, "content", "text/plain",
  7622. [&](const char *data, size_t data_length) {
  7623. received_body.append(data, data_length);
  7624. return true;
  7625. },
  7626. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7627. progress_called = true;
  7628. return true;
  7629. });
  7630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7631. EXPECT_EQ(StatusCode::OK_200, res->status);
  7632. EXPECT_EQ("content", received_body);
  7633. EXPECT_TRUE(progress_called);
  7634. }
  7635. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7636. #ifdef CPPHTTPLIB_SSL_ENABLED
  7637. using ClientT = SSLClient;
  7638. #else
  7639. using ClientT = Client;
  7640. #endif
  7641. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7642. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7643. const std::string &body, const std::string &content_type,
  7644. ContentReceiver receiver, DownloadProgress progress) {
  7645. return cli.Post(path, headers, body, content_type, receiver, progress);
  7646. });
  7647. }
  7648. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7649. #ifdef CPPHTTPLIB_SSL_ENABLED
  7650. using ClientT = SSLClient;
  7651. #else
  7652. using ClientT = Client;
  7653. #endif
  7654. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7655. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7656. const std::string &body, const std::string &content_type,
  7657. ContentReceiver receiver, DownloadProgress progress) {
  7658. return cli.Put(path, headers, body, content_type, receiver, progress);
  7659. });
  7660. }
  7661. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7662. #ifdef CPPHTTPLIB_SSL_ENABLED
  7663. using ClientT = SSLClient;
  7664. #else
  7665. using ClientT = Client;
  7666. #endif
  7667. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7668. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7669. const std::string &body, const std::string &content_type,
  7670. ContentReceiver receiver, DownloadProgress progress) {
  7671. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7672. });
  7673. }
  7674. template <typename ClientType>
  7675. void TestWithHeadersAndContentReceiverError(
  7676. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7677. const Headers &, const std::string &,
  7678. const std::string &, ContentReceiver)>
  7679. request_func) {
  7680. Headers headers;
  7681. headers.emplace("X-Error-Test", "true");
  7682. std::string received_body;
  7683. auto receiver_failed = false;
  7684. auto res =
  7685. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7686. [&](const char *data, size_t data_length) {
  7687. received_body.append(data, data_length);
  7688. receiver_failed = true;
  7689. return false;
  7690. });
  7691. ASSERT_FALSE(res);
  7692. EXPECT_TRUE(receiver_failed);
  7693. }
  7694. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7695. #ifdef CPPHTTPLIB_SSL_ENABLED
  7696. using ClientT = SSLClient;
  7697. #else
  7698. using ClientT = Client;
  7699. #endif
  7700. TestWithHeadersAndContentReceiverError<ClientT>(
  7701. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7702. const std::string &body, const std::string &content_type,
  7703. ContentReceiver receiver) {
  7704. return cli.Post(path, headers, body, content_type, receiver);
  7705. });
  7706. }
  7707. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7708. #ifdef CPPHTTPLIB_SSL_ENABLED
  7709. using ClientT = SSLClient;
  7710. #else
  7711. using ClientT = Client;
  7712. #endif
  7713. TestWithHeadersAndContentReceiverError<ClientT>(
  7714. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7715. const std::string &body, const std::string &content_type,
  7716. ContentReceiver receiver) {
  7717. return cli.Put(path, headers, body, content_type, receiver);
  7718. });
  7719. }
  7720. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7721. #ifdef CPPHTTPLIB_SSL_ENABLED
  7722. using ClientT = SSLClient;
  7723. #else
  7724. using ClientT = Client;
  7725. #endif
  7726. TestWithHeadersAndContentReceiverError<ClientT>(
  7727. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7728. const std::string &body, const std::string &content_type,
  7729. ContentReceiver receiver) {
  7730. return cli.Patch(path, headers, body, content_type, receiver);
  7731. });
  7732. }
  7733. TEST_F(ServerTest, PostQueryStringAndBody) {
  7734. auto res =
  7735. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7737. ASSERT_EQ(StatusCode::OK_200, res->status);
  7738. }
  7739. TEST_F(ServerTest, HTTP2Magic) {
  7740. Request req;
  7741. req.method = "PRI";
  7742. req.path = "*";
  7743. req.body = "SM";
  7744. auto res = std::make_shared<Response>();
  7745. auto error = Error::Success;
  7746. auto ret = cli_.send(req, *res, error);
  7747. ASSERT_TRUE(ret);
  7748. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7749. }
  7750. TEST_F(ServerTest, KeepAlive) {
  7751. auto res = cli_.Get("/hi");
  7752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7753. EXPECT_EQ(StatusCode::OK_200, res->status);
  7754. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7755. EXPECT_EQ("Hello World!", res->body);
  7756. res = cli_.Get("/hi");
  7757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7758. EXPECT_EQ(StatusCode::OK_200, res->status);
  7759. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7760. EXPECT_EQ("Hello World!", res->body);
  7761. res = cli_.Get("/hi");
  7762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7763. EXPECT_EQ(StatusCode::OK_200, res->status);
  7764. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7765. EXPECT_EQ("Hello World!", res->body);
  7766. res = cli_.Get("/not-exist");
  7767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7768. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7769. res = cli_.Post("/empty", "", "text/plain");
  7770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7771. EXPECT_EQ(StatusCode::OK_200, res->status);
  7772. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7773. EXPECT_EQ("empty", res->body);
  7774. EXPECT_EQ("close", res->get_header_value("Connection"));
  7775. res = cli_.Post(
  7776. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7777. "text/plain");
  7778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7779. EXPECT_EQ(StatusCode::OK_200, res->status);
  7780. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7781. EXPECT_EQ("empty", res->body);
  7782. cli_.set_keep_alive(false);
  7783. res = cli_.Get("/last-request");
  7784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7785. EXPECT_EQ(StatusCode::OK_200, res->status);
  7786. EXPECT_EQ("close", res->get_header_value("Connection"));
  7787. }
  7788. TEST_F(ServerTest, TooManyRedirect) {
  7789. cli_.set_follow_location(true);
  7790. auto res = cli_.Get("/redirect/0");
  7791. ASSERT_TRUE(!res);
  7792. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7793. }
  7794. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7795. Request req;
  7796. req.method = "FOOBAR";
  7797. req.path = "/hi";
  7798. cli_.set_keep_alive(true);
  7799. auto res = cli_.send(req);
  7800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7801. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7802. EXPECT_EQ("close", res->get_header_value("Connection"));
  7803. EXPECT_FALSE(cli_.is_socket_open());
  7804. }
  7805. TEST_F(ServerTest, CustomRouteReadsBody) {
  7806. const std::string xml =
  7807. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7808. Request req;
  7809. req.method = "PROPFIND";
  7810. req.path = "/dav/dir";
  7811. req.set_header("Depth", "1");
  7812. req.body = xml;
  7813. auto res = cli_.send(req);
  7814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7815. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7816. EXPECT_EQ(xml, res->body);
  7817. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7818. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7819. }
  7820. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7821. Request req;
  7822. req.method = "PROPFIND";
  7823. req.path = "/dav/42";
  7824. auto res = cli_.send(req);
  7825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7826. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7827. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7828. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7829. }
  7830. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7831. Request req;
  7832. req.method = "PROPFIND";
  7833. req.path = "/dav-re/123";
  7834. auto res = cli_.send(req);
  7835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7836. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7837. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7838. }
  7839. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7840. Request req;
  7841. req.method = "MKCOL";
  7842. req.path = "/dav-mkcol";
  7843. auto res = cli_.send(req);
  7844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7845. EXPECT_EQ(StatusCode::Created_201, res->status);
  7846. }
  7847. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7848. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7849. Request req;
  7850. req.method = "REPORT";
  7851. req.path = "/dav-report";
  7852. req.body = xml;
  7853. auto res = cli_.send(req);
  7854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7855. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7856. EXPECT_EQ(xml, res->body);
  7857. }
  7858. // A content reader route must fire even when the request carries no body,
  7859. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7860. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7861. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7862. Request req;
  7863. req.method = "REPORT";
  7864. req.path = "/dav-report";
  7865. auto res = cli_.send(req);
  7866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7867. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7868. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7869. }
  7870. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7871. Request req;
  7872. req.method = "PROPFIND";
  7873. req.path = "/not-dav";
  7874. auto res = cli_.send(req);
  7875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7876. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7877. }
  7878. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7879. Request req;
  7880. req.method = "UNLOCK";
  7881. req.path = "/dav/dir";
  7882. cli_.set_keep_alive(true);
  7883. auto res = cli_.send(req);
  7884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7885. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7886. EXPECT_EQ("close", res->get_header_value("Connection"));
  7887. EXPECT_FALSE(cli_.is_socket_open());
  7888. }
  7889. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7890. // The mount point serves this path, but only for GET and HEAD.
  7891. auto get_res = cli_.Get("/dir/index.html");
  7892. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7893. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7894. Request req;
  7895. req.method = "PROPFIND";
  7896. req.path = "/dir/index.html";
  7897. auto res = cli_.send(req);
  7898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7899. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7900. }
  7901. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7902. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7903. cli_.set_keep_alive(true);
  7904. for (auto i = 0; i < 2; i++) {
  7905. Request req;
  7906. req.method = "PROPFIND";
  7907. req.path = "/dav/dir";
  7908. req.body = xml;
  7909. auto res = cli_.send(req);
  7910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7911. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7912. EXPECT_EQ(xml, res->body);
  7913. EXPECT_TRUE(cli_.is_socket_open());
  7914. }
  7915. // A built-in method must still be served on the same connection.
  7916. cli_.set_keep_alive(false);
  7917. auto res = cli_.Get("/hi");
  7918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7919. EXPECT_EQ(StatusCode::OK_200, res->status);
  7920. EXPECT_EQ("close", res->get_header_value("Connection"));
  7921. }
  7922. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7923. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7924. Request req;
  7925. req.method = "PROPFIND";
  7926. req.path = "/dav/dir";
  7927. req.set_header("Expect", "100-continue");
  7928. req.body = xml;
  7929. auto res = cli_.send(req);
  7930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7931. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7932. EXPECT_EQ(xml, res->body);
  7933. }
  7934. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7935. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7936. TEST_F(ServerTest, Gzip) {
  7937. Headers headers;
  7938. headers.emplace("Accept-Encoding", "gzip, deflate");
  7939. auto res = cli_.Get("/compress", headers);
  7940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7941. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7942. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7943. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7944. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7945. "7890123456789012345678901234567890",
  7946. res->body);
  7947. EXPECT_EQ(StatusCode::OK_200, res->status);
  7948. }
  7949. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7950. Headers headers;
  7951. headers.emplace("Accept-Encoding", "gzip, deflate");
  7952. auto res = cli_.Get("/compress-with-charset", headers);
  7953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7954. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7955. EXPECT_EQ("application/json; charset=utf-8",
  7956. res->get_header_value("Content-Type"));
  7957. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7958. "7890123456789012345678901234567890",
  7959. res->body);
  7960. EXPECT_EQ(StatusCode::OK_200, res->status);
  7961. }
  7962. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7963. Headers headers;
  7964. headers.emplace("Accept-Encoding", "");
  7965. auto res = cli_.Get("/compress", headers);
  7966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7967. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7968. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7969. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7970. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7971. "7890123456789012345678901234567890",
  7972. res->body);
  7973. EXPECT_EQ(StatusCode::OK_200, res->status);
  7974. }
  7975. TEST_F(ServerTest, GzipWithContentReceiver) {
  7976. Headers headers;
  7977. headers.emplace("Accept-Encoding", "gzip, deflate");
  7978. std::string body;
  7979. auto res = cli_.Get("/compress", headers,
  7980. [&](const char *data, uint64_t data_length) {
  7981. EXPECT_EQ(100U, data_length);
  7982. body.append(data, data_length);
  7983. return true;
  7984. });
  7985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7986. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7987. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7988. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7989. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7990. "7890123456789012345678901234567890",
  7991. body);
  7992. EXPECT_EQ(StatusCode::OK_200, res->status);
  7993. }
  7994. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7995. Headers headers;
  7996. headers.emplace("Accept-Encoding", "gzip, deflate");
  7997. cli_.set_decompress(false);
  7998. auto res = cli_.Get("/compress", headers);
  7999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8000. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8001. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8002. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8003. EXPECT_EQ(33U, res->body.size());
  8004. EXPECT_EQ(StatusCode::OK_200, res->status);
  8005. }
  8006. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8007. Headers headers;
  8008. headers.emplace("Accept-Encoding", "");
  8009. std::string body;
  8010. auto res = cli_.Get("/compress", headers,
  8011. [&](const char *data, uint64_t data_length) {
  8012. EXPECT_EQ(100U, data_length);
  8013. body.append(data, data_length);
  8014. return true;
  8015. });
  8016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8017. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8018. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8019. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8020. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8021. "7890123456789012345678901234567890",
  8022. body);
  8023. EXPECT_EQ(StatusCode::OK_200, res->status);
  8024. }
  8025. TEST_F(ServerTest, NoGzip) {
  8026. Headers headers;
  8027. headers.emplace("Accept-Encoding", "gzip, deflate");
  8028. auto res = cli_.Get("/nocompress", headers);
  8029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8030. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8031. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8032. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8033. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8034. "7890123456789012345678901234567890",
  8035. res->body);
  8036. EXPECT_EQ(StatusCode::OK_200, res->status);
  8037. }
  8038. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8039. Headers headers;
  8040. headers.emplace("Accept-Encoding", "gzip, deflate");
  8041. std::string body;
  8042. auto res = cli_.Get("/nocompress", headers,
  8043. [&](const char *data, uint64_t data_length) {
  8044. EXPECT_EQ(100U, data_length);
  8045. body.append(data, data_length);
  8046. return true;
  8047. });
  8048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8049. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8050. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8051. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8052. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8053. "7890123456789012345678901234567890",
  8054. body);
  8055. EXPECT_EQ(StatusCode::OK_200, res->status);
  8056. }
  8057. TEST_F(ServerTest, MultipartFormDataGzip) {
  8058. UploadFormDataItems items = {
  8059. {"key1", "test", "", ""},
  8060. {"key2", "--abcdefg123", "", ""},
  8061. };
  8062. cli_.set_compress(true);
  8063. auto res = cli_.Post("/compress-multipart", items);
  8064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8065. EXPECT_EQ(StatusCode::OK_200, res->status);
  8066. }
  8067. #endif
  8068. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8069. // Static file compression is opt-in, so these run their own server rather than
  8070. // flipping it on for the shared ServerTest fixture, which would silently
  8071. // rewrite what every other static file test is asserting.
  8072. class StaticFileCompressionTest : public ::testing::Test {
  8073. protected:
  8074. void TearDown() override {
  8075. if (t_.joinable()) {
  8076. svr_.stop();
  8077. t_.join();
  8078. }
  8079. }
  8080. int start(const std::function<void(Server &)> &configure = nullptr) {
  8081. // Serves the same tree as a directory of build-time compressed assets
  8082. // would be served: the mount point names the coding the files are already
  8083. // stored in. Registered before "/" so it is the one that matches.
  8084. svr_.set_mount_point("/pre-encoded", "./www",
  8085. {{"Content-Encoding", "gzip"}});
  8086. svr_.set_mount_point("/", "./www");
  8087. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8088. res.set_file_content("./www/dir/index.html", "text/html");
  8089. });
  8090. svr_.Get("/pre-encoded-file-content",
  8091. [](const Request & /*req*/, Response &res) {
  8092. res.set_header("Content-Encoding", "gzip");
  8093. res.set_file_content("./www/dir/index.html", "text/html");
  8094. });
  8095. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8096. res.set_content_provider(
  8097. 6, "text/plain",
  8098. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8099. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8100. return true;
  8101. });
  8102. });
  8103. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8104. res.set_content_provider(
  8105. 1000, "text/plain",
  8106. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8107. if (offset < 100) {
  8108. std::string data(100, 'A');
  8109. sink.write(data.data(), data.size());
  8110. return true;
  8111. }
  8112. std::this_thread::sleep_for(std::chrono::seconds(2));
  8113. std::string data(900, 'B');
  8114. sink.write(data.data(), data.size());
  8115. return true;
  8116. });
  8117. });
  8118. if (configure) { configure(svr_); }
  8119. auto port = svr_.bind_to_any_port(HOST);
  8120. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8121. svr_.wait_until_ready();
  8122. return port;
  8123. }
  8124. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8125. // Every file under ./www except 1MB.txt is smaller than the default
  8126. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8127. // it out of the way.
  8128. static void enable_without_floor(Server &svr) {
  8129. svr.set_static_file_compression(true);
  8130. svr.set_static_file_compression_min_length(0);
  8131. }
  8132. Server svr_;
  8133. std::thread t_;
  8134. };
  8135. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8136. auto port = start();
  8137. Client cli(HOST, port);
  8138. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8140. EXPECT_EQ(StatusCode::OK_200, res->status);
  8141. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8142. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8143. EXPECT_EQ(1048576U, res->body.size());
  8144. }
  8145. TEST_F(StaticFileCompressionTest, MountPoint) {
  8146. auto port = start(enable);
  8147. Client cli(HOST, port);
  8148. cli.set_decompress(false);
  8149. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8151. EXPECT_EQ(StatusCode::OK_200, res->status);
  8152. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8153. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8154. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8155. // The response stays self-delimiting: a length, not a chunked body.
  8156. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8157. EXPECT_EQ(std::to_string(res->body.size()),
  8158. res->get_header_value("Content-Length"));
  8159. EXPECT_LT(res->body.size(), 1048576U);
  8160. EXPECT_FALSE(res->body.empty());
  8161. }
  8162. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8163. auto port = start(enable);
  8164. Client cli(HOST, port);
  8165. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8167. EXPECT_EQ(StatusCode::OK_200, res->status);
  8168. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8169. EXPECT_EQ(1048576U, res->body.size());
  8170. }
  8171. TEST_F(StaticFileCompressionTest, FileContent) {
  8172. auto port = start(enable_without_floor);
  8173. Client cli(HOST, port);
  8174. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8176. EXPECT_EQ(StatusCode::OK_200, res->status);
  8177. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8178. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8179. EXPECT_EQ(104U, res->body.size());
  8180. }
  8181. // A handler that serves an already-encoded file names the coding itself. The
  8182. // file-backed path decided its coding from Accept-Encoding and the content
  8183. // type alone, so it compressed the stored bytes a second time and appended a
  8184. // second Content-Encoding field line.
  8185. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8186. auto port = start(enable_without_floor);
  8187. Client cli(HOST, port);
  8188. cli.set_decompress(false);
  8189. auto res = cli.Get("/pre-encoded-file-content",
  8190. Headers{{"Accept-Encoding", "gzip"}});
  8191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8192. EXPECT_EQ(StatusCode::OK_200, res->status);
  8193. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8194. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8195. // Vary belongs to a coding the server chose, and it chose none here.
  8196. EXPECT_FALSE(res->has_header("Vary"));
  8197. // The file travels exactly as it is stored on disk.
  8198. EXPECT_EQ(104U, res->body.size());
  8199. }
  8200. // The 1MB file clears the default floor, so this one runs the configuration a
  8201. // deployment would actually have.
  8202. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8203. auto port = start(enable);
  8204. Client cli(HOST, port);
  8205. cli.set_decompress(false);
  8206. auto res =
  8207. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8209. EXPECT_EQ(StatusCode::OK_200, res->status);
  8210. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8211. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8212. EXPECT_FALSE(res->has_header("Vary"));
  8213. EXPECT_EQ(1048576U, res->body.size());
  8214. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8215. }
  8216. TEST_F(StaticFileCompressionTest, Head) {
  8217. auto port = start(enable);
  8218. Client cli(HOST, port);
  8219. cli.set_decompress(false);
  8220. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8221. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8222. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8224. EXPECT_EQ(StatusCode::OK_200, res->status);
  8225. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8226. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8227. // HEAD still reports the size a GET would return.
  8228. EXPECT_EQ(get->get_header_value("Content-Length"),
  8229. res->get_header_value("Content-Length"));
  8230. EXPECT_TRUE(res->body.empty());
  8231. }
  8232. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8233. auto port = start(enable);
  8234. Client cli(HOST, port);
  8235. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8236. {"Accept-Encoding", "gzip"}});
  8237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8238. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8239. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8240. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8241. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8242. EXPECT_EQ("cd", res->body);
  8243. }
  8244. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8245. auto port = start(enable);
  8246. Client cli(HOST, port);
  8247. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8249. EXPECT_EQ(StatusCode::OK_200, res->status);
  8250. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8251. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8252. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8253. }
  8254. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8255. auto port = start(enable);
  8256. Client cli(HOST, port);
  8257. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8259. EXPECT_EQ(StatusCode::OK_200, res->status);
  8260. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8261. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8262. EXPECT_TRUE(res->body.empty());
  8263. }
  8264. TEST_F(StaticFileCompressionTest, MinLength) {
  8265. auto port = start(enable);
  8266. Client cli(HOST, port);
  8267. // 104 bytes, well under the default floor. Compressing it would add the
  8268. // gzip header and trailer to a body that already fits in one packet.
  8269. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8271. EXPECT_EQ(StatusCode::OK_200, res->status);
  8272. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8273. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8274. }
  8275. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8276. auto port = start([](Server &svr) {
  8277. svr.set_static_file_compression(true);
  8278. svr.set_static_file_compression_min_length(1);
  8279. });
  8280. Client cli(HOST, port);
  8281. cli.set_decompress(false);
  8282. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8284. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8285. // A 9-byte file comes back larger than it went in, because gzip's header and
  8286. // trailer outweigh anything deflate can save. That is the end of the range
  8287. // the floor exists to keep out.
  8288. EXPECT_GT(res->body.size(), 9U);
  8289. }
  8290. TEST_F(StaticFileCompressionTest, MaxLength) {
  8291. auto port = start([](Server &svr) {
  8292. svr.set_static_file_compression(true);
  8293. svr.set_static_file_compression_min_length(0);
  8294. svr.set_static_file_compression_max_length(1024);
  8295. });
  8296. Client cli(HOST, port);
  8297. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8298. // defines `small` as a macro on Windows.
  8299. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8300. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8301. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8302. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8303. // Under it: compressed.
  8304. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8305. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8306. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8307. }
  8308. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8309. auto port = start(enable_without_floor);
  8310. Client cli(HOST, port);
  8311. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8312. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8313. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8314. auto identity_etag = identity->get_header_value("ETag");
  8315. ASSERT_FALSE(identity_etag.empty());
  8316. auto gzipped =
  8317. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8318. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8319. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8320. auto gzip_etag = gzipped->get_header_value("ETag");
  8321. ASSERT_FALSE(gzip_etag.empty());
  8322. // Two representations, two validators.
  8323. EXPECT_NE(identity_etag, gzip_etag);
  8324. // Each one revalidates against the request that would produce it...
  8325. auto fresh =
  8326. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8327. {"If-None-Match", gzip_etag}});
  8328. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8329. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8330. auto fresh_identity =
  8331. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8332. {"If-None-Match", identity_etag}});
  8333. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8334. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8335. // ...and not against the other representation.
  8336. auto crossed =
  8337. cli.Get("/dir/index.html",
  8338. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8339. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8340. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8341. }
  8342. // The opt-in covers responses the server reads off disk itself. A caller's own
  8343. // known-length provider keeps its Content-Length and, more importantly, keeps
  8344. // delivering incrementally: routing it through a compressor would hold every
  8345. // write back until zlib's window filled.
  8346. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8347. auto port = start(enable);
  8348. Client cli(HOST, port);
  8349. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8351. EXPECT_EQ(StatusCode::OK_200, res->status);
  8352. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8353. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8354. EXPECT_EQ("aaabbb", res->body);
  8355. }
  8356. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8357. auto port = start(enable);
  8358. Client cli(HOST, port);
  8359. cli.set_read_timeout(1, 0);
  8360. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8361. Headers{{"Accept-Encoding", "gzip"}});
  8362. ASSERT_TRUE(handle.is_valid());
  8363. // The provider writes 100 bytes and then stalls for longer than the read
  8364. // timeout. Those first bytes have to arrive anyway: run the response through
  8365. // a compressor and zlib holds them until its window fills, so the read would
  8366. // come back empty instead.
  8367. char buf[256];
  8368. auto n = handle.read(buf, sizeof(buf));
  8369. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8370. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8371. }
  8372. #endif
  8373. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8374. TEST_F(ServerTest, Brotli) {
  8375. Headers headers;
  8376. headers.emplace("Accept-Encoding", "br");
  8377. auto res = cli_.Get("/compress", headers);
  8378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8379. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8380. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8381. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8382. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8383. "7890123456789012345678901234567890",
  8384. res->body);
  8385. EXPECT_EQ(StatusCode::OK_200, res->status);
  8386. }
  8387. #endif
  8388. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8389. TEST_F(ServerTest, Zstd) {
  8390. Headers headers;
  8391. headers.emplace("Accept-Encoding", "zstd");
  8392. auto res = cli_.Get("/compress", headers);
  8393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8394. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8395. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8396. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8397. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8398. "7890123456789012345678901234567890",
  8399. res->body);
  8400. EXPECT_EQ(StatusCode::OK_200, res->status);
  8401. }
  8402. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8403. Headers headers;
  8404. headers.emplace("Accept-Encoding", "");
  8405. auto res = cli_.Get("/compress", headers);
  8406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8407. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8408. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8409. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8410. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8411. "7890123456789012345678901234567890",
  8412. res->body);
  8413. EXPECT_EQ(StatusCode::OK_200, res->status);
  8414. }
  8415. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8416. Headers headers;
  8417. headers.emplace("Accept-Encoding", "zstd");
  8418. std::string body;
  8419. auto res = cli_.Get("/compress", headers,
  8420. [&](const char *data, uint64_t data_length) {
  8421. EXPECT_EQ(100U, data_length);
  8422. body.append(data, data_length);
  8423. return true;
  8424. });
  8425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8426. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8427. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8428. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8429. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8430. "7890123456789012345678901234567890",
  8431. body);
  8432. EXPECT_EQ(StatusCode::OK_200, res->status);
  8433. }
  8434. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8435. Headers headers;
  8436. headers.emplace("Accept-Encoding", "zstd");
  8437. cli_.set_decompress(false);
  8438. auto res = cli_.Get("/compress", headers);
  8439. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8440. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8441. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8442. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8444. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8445. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8446. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8447. EXPECT_EQ(StatusCode::OK_200, res->status);
  8448. ASSERT_EQ(26U, res->body.size());
  8449. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8450. 0);
  8451. }
  8452. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8453. Headers headers;
  8454. headers.emplace("Accept-Encoding", "");
  8455. std::string body;
  8456. auto res = cli_.Get("/compress", headers,
  8457. [&](const char *data, uint64_t data_length) {
  8458. EXPECT_EQ(100U, data_length);
  8459. body.append(data, data_length);
  8460. return true;
  8461. });
  8462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8463. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8464. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8465. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8466. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8467. "7890123456789012345678901234567890",
  8468. body);
  8469. EXPECT_EQ(StatusCode::OK_200, res->status);
  8470. }
  8471. TEST_F(ServerTest, NoZstd) {
  8472. Headers headers;
  8473. headers.emplace("Accept-Encoding", "zstd");
  8474. auto res = cli_.Get("/nocompress", headers);
  8475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8476. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8477. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8478. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8479. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8480. "7890123456789012345678901234567890",
  8481. res->body);
  8482. EXPECT_EQ(StatusCode::OK_200, res->status);
  8483. }
  8484. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8485. Headers headers;
  8486. headers.emplace("Accept-Encoding", "zstd");
  8487. std::string body;
  8488. auto res = cli_.Get("/nocompress", headers,
  8489. [&](const char *data, uint64_t data_length) {
  8490. EXPECT_EQ(100U, data_length);
  8491. body.append(data, data_length);
  8492. return true;
  8493. });
  8494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8495. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8496. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8497. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8498. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8499. "7890123456789012345678901234567890",
  8500. body);
  8501. EXPECT_EQ(StatusCode::OK_200, res->status);
  8502. }
  8503. // TODO: How to enable zstd ??
  8504. TEST_F(ServerTest, MultipartFormDataZstd) {
  8505. UploadFormDataItems items = {
  8506. {"key1", "test", "", ""},
  8507. {"key2", "--abcdefg123", "", ""},
  8508. };
  8509. Headers headers;
  8510. headers.emplace("Accept-Encoding", "zstd");
  8511. cli_.set_compress(true);
  8512. auto res = cli_.Post("/compress-multipart", headers, items);
  8513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8514. EXPECT_EQ(StatusCode::OK_200, res->status);
  8515. }
  8516. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8517. Headers headers;
  8518. headers.emplace("Accept-Encoding", "zstd");
  8519. cli_.set_compress(true);
  8520. auto res = cli_.Put(
  8521. "/put", headers, 3,
  8522. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8523. sink.os << "PUT";
  8524. return true;
  8525. },
  8526. "text/plain");
  8527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8528. EXPECT_EQ(StatusCode::OK_200, res->status);
  8529. EXPECT_EQ("PUT", res->body);
  8530. }
  8531. // Pre-compression logging tests
  8532. TEST_F(ServerTest, PreCompressionLogging) {
  8533. // Test data for compression (matches the actual /compress endpoint content)
  8534. const std::string test_content =
  8535. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8536. "3456789012345678901234567890";
  8537. // Variables to capture logging data
  8538. std::string pre_compression_body;
  8539. std::string pre_compression_content_type;
  8540. std::string pre_compression_content_encoding;
  8541. std::string post_compression_body;
  8542. std::string post_compression_content_type;
  8543. std::string post_compression_content_encoding;
  8544. // Set up pre-compression logger
  8545. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8546. const Response &res) {
  8547. pre_compression_body = res.body;
  8548. pre_compression_content_type = res.get_header_value("Content-Type");
  8549. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8550. });
  8551. // Set up post-compression logger
  8552. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8553. post_compression_body = res.body;
  8554. post_compression_content_type = res.get_header_value("Content-Type");
  8555. post_compression_content_encoding =
  8556. res.get_header_value("Content-Encoding");
  8557. });
  8558. // Test with gzip compression
  8559. Headers headers;
  8560. headers.emplace("Accept-Encoding", "gzip");
  8561. auto res = cli_.Get("/compress", headers);
  8562. // Verify response was compressed
  8563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8564. EXPECT_EQ(StatusCode::OK_200, res->status);
  8565. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8566. // Verify pre-compression logger captured uncompressed content
  8567. EXPECT_EQ(test_content, pre_compression_body);
  8568. EXPECT_EQ("text/plain", pre_compression_content_type);
  8569. EXPECT_TRUE(pre_compression_content_encoding
  8570. .empty()); // No encoding header before compression
  8571. // Verify post-compression logger captured compressed content
  8572. EXPECT_NE(test_content,
  8573. post_compression_body); // Should be different after compression
  8574. EXPECT_EQ("text/plain", post_compression_content_type);
  8575. EXPECT_EQ("gzip", post_compression_content_encoding);
  8576. // Verify compressed content is smaller
  8577. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8578. }
  8579. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8580. const std::string test_content =
  8581. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8582. "3456789012345678901234567890";
  8583. std::string pre_compression_body;
  8584. std::string post_compression_body;
  8585. svr_.set_pre_compression_logger(
  8586. [&](const Request & /*req*/, const Response &res) {
  8587. pre_compression_body = res.body;
  8588. });
  8589. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8590. post_compression_body = res.body;
  8591. });
  8592. Headers headers;
  8593. headers.emplace("Accept-Encoding", "br");
  8594. auto res = cli_.Get("/compress", headers);
  8595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8596. EXPECT_EQ(StatusCode::OK_200, res->status);
  8597. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8598. // Verify pre-compression content is uncompressed
  8599. EXPECT_EQ(test_content, pre_compression_body);
  8600. // Verify post-compression content is compressed
  8601. EXPECT_NE(test_content, post_compression_body);
  8602. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8603. }
  8604. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8605. const std::string test_content =
  8606. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8607. "3456789012345678901234567890";
  8608. std::string pre_compression_body;
  8609. std::string post_compression_body;
  8610. svr_.set_pre_compression_logger(
  8611. [&](const Request & /*req*/, const Response &res) {
  8612. pre_compression_body = res.body;
  8613. });
  8614. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8615. post_compression_body = res.body;
  8616. });
  8617. // Request without compression (use /nocompress endpoint)
  8618. Headers headers;
  8619. auto res = cli_.Get("/nocompress", headers);
  8620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8621. EXPECT_EQ(StatusCode::OK_200, res->status);
  8622. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8623. // Pre-compression logger should not be called when no compression is applied
  8624. EXPECT_TRUE(
  8625. pre_compression_body.empty()); // Pre-compression logger not called
  8626. EXPECT_EQ(
  8627. test_content,
  8628. post_compression_body); // Post-compression logger captures final content
  8629. }
  8630. TEST_F(ServerTest, LoggerSeesContentLength) {
  8631. size_t logged_content_length = 0;
  8632. std::string logged_content_length_header;
  8633. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8634. logged_content_length = res.content_length_;
  8635. logged_content_length_header = res.get_header_value("Content-Length");
  8636. });
  8637. auto res = cli_.Get("/nocompress");
  8638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8639. EXPECT_EQ(StatusCode::OK_200, res->status);
  8640. EXPECT_EQ(res->body.size(), logged_content_length);
  8641. EXPECT_EQ(std::to_string(logged_content_length),
  8642. logged_content_length_header);
  8643. }
  8644. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8645. const std::string test_content =
  8646. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8647. "3456789012345678901234567890";
  8648. std::string pre_compression_body;
  8649. bool pre_logger_called = false;
  8650. // Set only pre-compression logger
  8651. svr_.set_pre_compression_logger(
  8652. [&](const Request & /*req*/, const Response &res) {
  8653. pre_compression_body = res.body;
  8654. pre_logger_called = true;
  8655. });
  8656. Headers headers;
  8657. headers.emplace("Accept-Encoding", "gzip");
  8658. auto res = cli_.Get("/compress", headers);
  8659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8660. EXPECT_EQ(StatusCode::OK_200, res->status);
  8661. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8662. // Verify pre-compression logger was called
  8663. EXPECT_TRUE(pre_logger_called);
  8664. EXPECT_EQ(test_content, pre_compression_body);
  8665. }
  8666. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8667. {
  8668. // Test with Expect: 100-continue header - success case
  8669. // Server returns 100 Continue, client sends body, server returns 200 OK
  8670. Request req;
  8671. req.method = "POST";
  8672. req.path = "/post-large";
  8673. req.set_header("Expect", "100-continue");
  8674. req.body = LARGE_DATA;
  8675. Response res;
  8676. auto error = Error::Success;
  8677. cli_.set_keep_alive(true);
  8678. auto ret = cli_.send(req, res, error);
  8679. EXPECT_TRUE(ret);
  8680. EXPECT_EQ(StatusCode::OK_200, res.status);
  8681. EXPECT_EQ(LARGE_DATA, res.body);
  8682. }
  8683. {
  8684. // Test with Expect: 100-continue header - error case
  8685. // Client should not send the body when server returns an error
  8686. Request req;
  8687. req.method = "POST";
  8688. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8689. req.set_header("Expect", "100-continue");
  8690. req.body = LARGE_DATA;
  8691. Response res;
  8692. auto error = Error::Success;
  8693. auto start = std::chrono::high_resolution_clock::now();
  8694. cli_.set_keep_alive(true);
  8695. auto ret = cli_.send(req, res, error);
  8696. auto end = std::chrono::high_resolution_clock::now();
  8697. auto elapsed =
  8698. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8699. .count();
  8700. // With Expect: 100-continue, request completes successfully but with error
  8701. EXPECT_TRUE(ret);
  8702. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8703. EXPECT_EQ("close", res.get_header_value("Connection"));
  8704. EXPECT_FALSE(cli_.is_socket_open());
  8705. EXPECT_LE(elapsed, 2000);
  8706. }
  8707. {
  8708. // Send an extra GET request to ensure error recovery without hanging
  8709. Request req;
  8710. req.method = "GET";
  8711. req.path = "/hi";
  8712. auto start = std::chrono::high_resolution_clock::now();
  8713. auto res = cli_.send(req);
  8714. auto end = std::chrono::high_resolution_clock::now();
  8715. auto elapsed =
  8716. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8717. .count();
  8718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8719. EXPECT_EQ(StatusCode::OK_200, res->status);
  8720. EXPECT_EQ("Hello World!", res->body);
  8721. EXPECT_LE(elapsed, 500);
  8722. }
  8723. }
  8724. TEST(ZstdDecompressor, ChunkedDecompression) {
  8725. std::string data;
  8726. for (size_t i = 0; i < 32 * 1024; ++i) {
  8727. data.push_back(static_cast<char>('a' + i % 26));
  8728. }
  8729. std::string compressed_data;
  8730. {
  8731. httplib::detail::zstd_compressor compressor;
  8732. bool result = compressor.compress(
  8733. data.data(), data.size(),
  8734. /*last=*/true,
  8735. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8736. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8737. compressed_data_size);
  8738. return true;
  8739. });
  8740. ASSERT_TRUE(result);
  8741. }
  8742. std::string decompressed_data;
  8743. {
  8744. httplib::detail::zstd_decompressor decompressor;
  8745. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8746. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8747. size_t chunk_size = 130;
  8748. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8749. chunk_begin += chunk_size) {
  8750. size_t current_chunk_size =
  8751. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8752. bool result = decompressor.decompress(
  8753. compressed_data.data() + chunk_begin, current_chunk_size,
  8754. [&](const char *decompressed_data_chunk,
  8755. size_t decompressed_data_chunk_size) {
  8756. decompressed_data.insert(decompressed_data.size(),
  8757. decompressed_data_chunk,
  8758. decompressed_data_chunk_size);
  8759. return true;
  8760. });
  8761. ASSERT_TRUE(result);
  8762. }
  8763. }
  8764. ASSERT_EQ(data, decompressed_data);
  8765. }
  8766. TEST(ZstdDecompressor, Decompress) {
  8767. std::string original_text = "Compressed with ZSTD";
  8768. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8769. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8770. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8771. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8772. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8773. std::string decompressed_data;
  8774. {
  8775. httplib::detail::zstd_decompressor decompressor;
  8776. bool result = decompressor.decompress(
  8777. compressed_data.data(), compressed_data.size(),
  8778. [&](const char *decompressed_data_chunk,
  8779. size_t decompressed_data_chunk_size) {
  8780. decompressed_data.insert(decompressed_data.size(),
  8781. decompressed_data_chunk,
  8782. decompressed_data_chunk_size);
  8783. return true;
  8784. });
  8785. ASSERT_TRUE(result);
  8786. }
  8787. ASSERT_EQ(original_text, decompressed_data);
  8788. }
  8789. #endif
  8790. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8791. // separate chunks so that the server sees each part in its own read(). Used to
  8792. // place a read boundary at a specific offset of a request body.
  8793. static bool send_request_in_parts(time_t read_timeout_sec,
  8794. const std::vector<std::string> &parts,
  8795. std::string *resp = nullptr,
  8796. int port = PORT) {
  8797. auto error = Error::Success;
  8798. auto client_sock = detail::create_client_socket(
  8799. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8800. /*connection_timeout_sec=*/5, 0,
  8801. /*read_timeout_sec=*/5, 0,
  8802. /*write_timeout_sec=*/5, 0, std::string(), error);
  8803. if (client_sock == INVALID_SOCKET) { return false; }
  8804. auto ret = detail::process_client_socket(
  8805. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8806. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8807. for (size_t i = 0; i < parts.size(); i++) {
  8808. const auto &part = parts[i];
  8809. if (part.size() !=
  8810. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8811. return false;
  8812. }
  8813. if (i + 1 < parts.size()) {
  8814. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8815. }
  8816. }
  8817. char buf[512];
  8818. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8819. while (line_reader.getline()) {
  8820. if (resp) { *resp += line_reader.ptr(); }
  8821. }
  8822. return true;
  8823. });
  8824. detail::close_socket(client_sock);
  8825. return ret;
  8826. }
  8827. // Sends a raw request to a server listening at HOST:PORT.
  8828. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8829. std::string *resp = nullptr, int port = PORT) {
  8830. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8831. }
  8832. #ifdef CPPHTTPLIB_SSL_ENABLED
  8833. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  8834. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8835. ASSERT_TRUE(svr.is_valid());
  8836. svr.set_read_timeout(1, 0);
  8837. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8838. auto se = detail::scope_exit([&] {
  8839. svr.stop();
  8840. t.join();
  8841. ASSERT_FALSE(svr.is_running());
  8842. });
  8843. svr.wait_until_ready();
  8844. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  8845. // keeps each wait well within the read timeout. The server gives up a
  8846. // second in, so the bytes sent after that fail.
  8847. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  8848. parts.resize(26, std::string(1, '\0'));
  8849. EXPECT_FALSE(send_request_in_parts(5, parts));
  8850. }
  8851. #endif
  8852. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8853. Server svr;
  8854. std::string header_value;
  8855. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8856. header_value = req.get_header_value("foo");
  8857. res.set_content("ok", "text/plain");
  8858. });
  8859. thread t = thread([&] { svr.listen(HOST, PORT); });
  8860. auto se = detail::scope_exit([&] {
  8861. svr.stop();
  8862. t.join();
  8863. ASSERT_FALSE(svr.is_running());
  8864. });
  8865. svr.wait_until_ready();
  8866. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8867. // like characters are not treated the same - use vertical tab and escape.
  8868. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8869. "foo: \t \v bar \x1B\t \r\n"
  8870. "Connection: close\r\n"
  8871. "\r\n";
  8872. std::string res;
  8873. ASSERT_TRUE(send_request(5, req, &res));
  8874. EXPECT_EQ(header_value, "");
  8875. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8876. }
  8877. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8878. Server svr;
  8879. std::string received;
  8880. svr.Get("/order", [&](const Request &req, Response &res) {
  8881. received = entries_to_string(req.headers);
  8882. res.set_content("ok", "text/plain");
  8883. });
  8884. auto port = svr.bind_to_any_port(HOST);
  8885. thread t = thread([&] { svr.listen_after_bind(); });
  8886. auto se = detail::scope_exit([&] {
  8887. svr.stop();
  8888. t.join();
  8889. ASSERT_FALSE(svr.is_running());
  8890. });
  8891. svr.wait_until_ready();
  8892. const std::string req = "GET /order HTTP/1.1\r\n"
  8893. "Host: localhost\r\n"
  8894. "X-First: 1\r\n"
  8895. "X-Dup: a\r\n"
  8896. "X-Second: 2\r\n"
  8897. "X-Dup: b\r\n"
  8898. "Connection: close\r\n"
  8899. "\r\n";
  8900. std::string res;
  8901. ASSERT_TRUE(send_request(5, req, &res, port));
  8902. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8903. EXPECT_EQ(
  8904. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  8905. received);
  8906. }
  8907. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8908. Server svr;
  8909. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8910. res.set_header("Set-Cookie", "first=1");
  8911. res.set_header("X-Between", "y");
  8912. res.set_header("Set-Cookie", "second=2");
  8913. res.set_content("ok", "text/plain");
  8914. });
  8915. auto port = svr.bind_to_any_port(HOST);
  8916. thread t = thread([&] { svr.listen_after_bind(); });
  8917. auto se = detail::scope_exit([&] {
  8918. svr.stop();
  8919. t.join();
  8920. ASSERT_FALSE(svr.is_running());
  8921. });
  8922. svr.wait_until_ready();
  8923. Client cli(HOST, port);
  8924. auto res = cli.Get("/cookies");
  8925. ASSERT_TRUE(res);
  8926. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8927. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8928. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8929. }
  8930. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8931. Server svr;
  8932. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8933. auto i = new int(0);
  8934. res.set_header("Trailer", "X-Safe, X-Reflected");
  8935. res.set_chunked_content_provider(
  8936. "text/plain",
  8937. [i](size_t /*offset*/, DataSink &sink) {
  8938. if (*i == 0) {
  8939. sink.os << "body";
  8940. } else {
  8941. Headers trailer;
  8942. // A valid trailer that must survive.
  8943. trailer.emplace("X-Safe", "safe");
  8944. // Attacker-controlled value carrying CR/LF (response splitting).
  8945. trailer.emplace("X-Reflected",
  8946. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8947. // Attacker-controlled name carrying CR/LF.
  8948. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8949. sink.done_with_trailer(trailer);
  8950. }
  8951. (*i)++;
  8952. return true;
  8953. },
  8954. [i](bool /*success*/) { delete i; });
  8955. });
  8956. thread t = thread([&] { svr.listen(HOST, PORT); });
  8957. auto se = detail::scope_exit([&] {
  8958. svr.stop();
  8959. t.join();
  8960. ASSERT_FALSE(svr.is_running());
  8961. });
  8962. svr.wait_until_ready();
  8963. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8964. "Host: " + HOST +
  8965. "\r\n"
  8966. "Connection: close\r\n"
  8967. "\r\n";
  8968. std::string res;
  8969. ASSERT_TRUE(send_request(5, req, &res));
  8970. // The injected fields must not appear anywhere in the raw response.
  8971. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8972. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8973. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8974. // Invalid trailers are dropped entirely, matching set_header().
  8975. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8976. // The valid trailer still passes through.
  8977. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8978. }
  8979. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8980. Server svr;
  8981. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8982. // res.headers is a public field an application can populate directly,
  8983. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8984. // A valid header that must survive.
  8985. res.headers.emplace("X-Safe", "safe");
  8986. // Attacker-controlled value carrying CR/LF (response splitting).
  8987. res.headers.emplace("X-Reflected",
  8988. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8989. // Attacker-controlled name carrying CR/LF.
  8990. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8991. res.set_content("body", "text/plain");
  8992. });
  8993. thread t = thread([&] { svr.listen(HOST, PORT); });
  8994. auto se = detail::scope_exit([&] {
  8995. svr.stop();
  8996. t.join();
  8997. ASSERT_FALSE(svr.is_running());
  8998. });
  8999. svr.wait_until_ready();
  9000. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9001. "Host: " + HOST +
  9002. "\r\n"
  9003. "Connection: close\r\n"
  9004. "\r\n";
  9005. std::string res;
  9006. ASSERT_TRUE(send_request(5, req, &res));
  9007. // The injected fields must not appear anywhere in the raw response.
  9008. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9009. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9010. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9011. // Invalid headers are dropped entirely, matching set_header().
  9012. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9013. // The valid header still passes through.
  9014. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9015. }
  9016. // Forward declaration: in split builds split.py strips `inline` and moves the
  9017. // definition into httplib.cc, so detail::write_request_line is not visible from
  9018. // the public httplib.h. Re-declaring it here lets the tests link against the
  9019. // symbol in both header-only and split builds.
  9020. namespace httplib {
  9021. namespace detail {
  9022. ssize_t write_request_line(Stream &strm, const std::string &method,
  9023. const std::string &path);
  9024. } // namespace detail
  9025. } // namespace httplib
  9026. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9027. // A well-formed target is written verbatim.
  9028. {
  9029. detail::BufferStream strm;
  9030. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9031. EXPECT_GT(n, 0);
  9032. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9033. }
  9034. // A target carrying CR/LF, SP or other control octets must be rejected
  9035. // before anything reaches the wire, otherwise it splits the request line and
  9036. // injects a header or a whole request.
  9037. const std::string evil_targets[] = {
  9038. "/a\r\nInjected: pwned",
  9039. "/a\rInjected",
  9040. "/a\nInjected",
  9041. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9042. "/a b",
  9043. "/a\tb",
  9044. "/a\x7f",
  9045. };
  9046. for (const auto &evil : evil_targets) {
  9047. detail::BufferStream strm;
  9048. auto n = detail::write_request_line(strm, "GET", evil);
  9049. EXPECT_LT(n, 0);
  9050. EXPECT_TRUE(strm.get_buffer().empty());
  9051. }
  9052. }
  9053. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9054. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9055. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9056. // target reaches write_request. The client must fail cleanly with
  9057. // Error::Write instead of putting a request-line-less, header-injecting
  9058. // request on the wire.
  9059. Server svr;
  9060. svr.Get("/a", [](const Request &, Response &res) {
  9061. res.set_content("ok", "text/plain");
  9062. });
  9063. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9064. auto se = detail::scope_exit([&] {
  9065. svr.stop();
  9066. thread.join();
  9067. ASSERT_FALSE(svr.is_running());
  9068. });
  9069. svr.wait_until_ready();
  9070. {
  9071. Client cli(HOST, PORT);
  9072. cli.set_path_encode(false);
  9073. // The request is rejected before anything is written, so the connection
  9074. // stays silent and the subsequent response read would otherwise block for
  9075. // the full default read timeout. Shorten it -- the assertion is on the
  9076. // error, not the timeout.
  9077. cli.set_read_timeout(1, 0);
  9078. auto res = cli.Get("/a\r\nInjected: pwned");
  9079. EXPECT_FALSE(res);
  9080. EXPECT_EQ(Error::Write, res.error());
  9081. }
  9082. }
  9083. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9084. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9085. // including extension methods.
  9086. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9087. for (const auto &method : good_methods) {
  9088. detail::BufferStream strm;
  9089. auto n = detail::write_request_line(strm, method, "/");
  9090. EXPECT_GT(n, 0);
  9091. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9092. }
  9093. // A method carrying CR/LF would split the request line and smuggle a whole
  9094. // request ahead of the real one. A space or an empty method corrupts the
  9095. // request line. All must be rejected before anything reaches the wire.
  9096. const std::string evil_methods[] = {
  9097. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9098. "GET\r\nInjected: pwned",
  9099. "GET\r",
  9100. "GET\n",
  9101. "GE T",
  9102. "",
  9103. };
  9104. for (const auto &evil : evil_methods) {
  9105. detail::BufferStream strm;
  9106. auto n = detail::write_request_line(strm, evil, "/");
  9107. EXPECT_LT(n, 0);
  9108. EXPECT_TRUE(strm.get_buffer().empty());
  9109. }
  9110. }
  9111. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9112. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9113. // through Client::send must fail with Error::Write and no request, neither
  9114. // the smuggled one nor the real one, may reach the server.
  9115. Server svr;
  9116. std::atomic<int> request_count(0);
  9117. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9118. request_count++;
  9119. res.status = StatusCode::OK_200;
  9120. return Server::HandlerResponse::Handled;
  9121. });
  9122. auto port = svr.bind_to_any_port(HOST);
  9123. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9124. auto se = detail::scope_exit([&] {
  9125. svr.stop();
  9126. thread.join();
  9127. ASSERT_FALSE(svr.is_running());
  9128. });
  9129. svr.wait_until_ready();
  9130. {
  9131. Client cli(HOST, port);
  9132. const std::string evil_methods[] = {
  9133. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9134. "GE T",
  9135. "",
  9136. };
  9137. for (const auto &evil : evil_methods) {
  9138. Request req;
  9139. req.method = evil;
  9140. req.path = "/";
  9141. auto res = cli.send(req);
  9142. EXPECT_FALSE(res);
  9143. EXPECT_EQ(Error::Write, res.error());
  9144. }
  9145. auto handle =
  9146. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9147. EXPECT_FALSE(handle.is_valid());
  9148. EXPECT_EQ(Error::Write, handle.error);
  9149. // A valid request on the same client still goes through.
  9150. auto res = cli.Get("/");
  9151. ASSERT_TRUE(res);
  9152. EXPECT_EQ(StatusCode::OK_200, res->status);
  9153. }
  9154. EXPECT_EQ(1, request_count.load());
  9155. }
  9156. // Sends a raw request and verifies that there isn't a crash or exception.
  9157. static void test_raw_request(const std::string &req,
  9158. std::string *out = nullptr) {
  9159. Server svr;
  9160. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9161. res.set_content("ok", "text/plain");
  9162. });
  9163. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9164. res.set_content("ok", "text/plain");
  9165. });
  9166. svr.Get("/header_field_value_check",
  9167. [&](const Request & /*req*/, Response &res) {
  9168. res.set_content("ok", "text/plain");
  9169. });
  9170. svr.CustomRoute("PROPFIND", "/dav",
  9171. [&](const Request & /*req*/, Response &res) {
  9172. res.status = StatusCode::MultiStatus_207;
  9173. });
  9174. // Server read timeout must be longer than the client read timeout for the
  9175. // bug to reproduce, probably to force the server to process a request
  9176. // without a trailing blank line.
  9177. const time_t client_read_timeout_sec = 1;
  9178. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9179. bool listen_thread_ok = false;
  9180. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9181. auto se = detail::scope_exit([&] {
  9182. svr.stop();
  9183. t.join();
  9184. ASSERT_FALSE(svr.is_running());
  9185. EXPECT_TRUE(listen_thread_ok);
  9186. });
  9187. svr.wait_until_ready();
  9188. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9189. }
  9190. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9191. // A certain header line causes an exception if the header property is parsed
  9192. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9193. test_raw_request(
  9194. "GET /hi HTTP/1.1\r\n"
  9195. " : "
  9196. " "
  9197. " ");
  9198. }
  9199. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9200. // A certain header line causes an exception if the header property *name* is
  9201. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9202. // greedy matcher and requires backtracking when there are a lot of ":"
  9203. // characters.
  9204. // This occurs with libc++ but not libstdc++.
  9205. test_raw_request(
  9206. "GET /hi HTTP/1.1\r\n"
  9207. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9208. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9209. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9210. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9211. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9212. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9213. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9214. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9215. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9216. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9217. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9218. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9219. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9220. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9221. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9222. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9223. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9224. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9225. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9226. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9227. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9228. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9229. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9230. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9231. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9232. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9233. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9234. "&&&%%%");
  9235. }
  9236. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9237. // Make sure this doesn't crash the server.
  9238. // In a previous version of the header line regex, the "\r" rendered the line
  9239. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9240. // a new position where the leading white space ended and the field value
  9241. // began.
  9242. // The crash occurs with libc++ but not libstdc++.
  9243. test_raw_request("GET /hi HTTP/1.1\r\n"
  9244. "a:" +
  9245. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9246. "\r\n"
  9247. "\r\n");
  9248. }
  9249. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9250. const char *rejected[] = {
  9251. // RFC 9112 §3: one SP between the parts, and nothing else
  9252. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9253. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9254. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9255. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9256. // A request-target has no fragment
  9257. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9258. // An HTTP/1.1 request needs a Host
  9259. "GET /hi HTTP/1.1\r\n\r\n",
  9260. };
  9261. for (auto request : rejected) {
  9262. std::string out;
  9263. test_raw_request(request, &out);
  9264. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9265. }
  9266. std::string out;
  9267. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9268. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9269. }
  9270. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9271. // RFC 9112 §6.1
  9272. const char *requests[] = {
  9273. "PUT /put_hi HTTP/1.1\r\n"
  9274. "Host: localhost\r\n"
  9275. "Content-Length: 0\r\n"
  9276. "Transfer-Encoding: chunked\r\n"
  9277. "\r\n"
  9278. "0\r\n\r\n",
  9279. "PUT /put_hi HTTP/1.0\r\n"
  9280. "Connection: keep-alive\r\n"
  9281. "Transfer-Encoding: chunked\r\n"
  9282. "\r\n"
  9283. "0\r\n\r\n",
  9284. };
  9285. for (auto request : requests) {
  9286. std::string out;
  9287. test_raw_request(request, &out);
  9288. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9289. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9290. }
  9291. }
  9292. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9293. std::string out;
  9294. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9295. "Content-Type: text/plain\r\n"
  9296. "Transfer-Encoding: chunked\r\n"
  9297. "\r\n"
  9298. "nothex\r\n",
  9299. &out);
  9300. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9301. }
  9302. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9303. std::string out;
  9304. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9305. "Content-Type: text/plain\r\n"
  9306. "Transfer-Encoding: chunked\r\n"
  9307. "\r\n"
  9308. "3\r\n"
  9309. "xyz\r\n"
  9310. "NaN\r\n",
  9311. &out);
  9312. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9313. }
  9314. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9315. std::string out;
  9316. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9317. "Content-Type: text/plain\r\n"
  9318. "Transfer-Encoding: chunked\r\n"
  9319. "\r\n"
  9320. // Length is too large for 64 bits.
  9321. "1ffffffffffffffff\r\n"
  9322. "xyz\r\n",
  9323. &out);
  9324. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9325. }
  9326. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9327. test_raw_request("GET /hi HTTP/1.1\r\n"
  9328. "Content-Type: text/plain\r\n\r");
  9329. }
  9330. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9331. std::string out;
  9332. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9333. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9334. }
  9335. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9336. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9337. std::string out;
  9338. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9339. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9340. }
  9341. }
  9342. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9343. std::string out;
  9344. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9345. "Host: localhost\r\n"
  9346. "Connection: close\r\n\r\n",
  9347. &out);
  9348. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9349. }
  9350. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9351. Server svr;
  9352. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9353. EXPECT_TRUE(!req.remote_addr.empty());
  9354. });
  9355. thread t = thread([&] { svr.listen(HOST, PORT); });
  9356. auto se = detail::scope_exit([&] {
  9357. svr.stop();
  9358. t.join();
  9359. ASSERT_FALSE(svr.is_running());
  9360. });
  9361. svr.wait_until_ready();
  9362. // Send an invalid request line to trigger Bad Request
  9363. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9364. std::string out;
  9365. ASSERT_TRUE(send_request(5, bad_req, &out));
  9366. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9367. }
  9368. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9369. // answered right away rather than blocking on a read that waits for EOF.
  9370. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9371. std::string out;
  9372. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9373. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9374. }
  9375. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9376. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9377. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9378. for (const auto *method : methods) {
  9379. Server svr;
  9380. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9381. EXPECT_FALSE(svr.is_valid()) << method;
  9382. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9383. }
  9384. }
  9385. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9386. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9387. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9388. for (const auto *method : methods) {
  9389. Server svr;
  9390. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9391. EXPECT_FALSE(svr.is_valid()) << method;
  9392. }
  9393. }
  9394. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9395. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9396. "COPY", "MOVE", "LOCK",
  9397. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9398. Server svr;
  9399. for (const auto *method : methods) {
  9400. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9401. }
  9402. EXPECT_TRUE(svr.is_valid());
  9403. }
  9404. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9405. Server svr;
  9406. svr.CustomRoute("POST", "/x",
  9407. [](const Request &, Response &, const ContentReader &) {});
  9408. EXPECT_FALSE(svr.is_valid());
  9409. }
  9410. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9411. Server svr;
  9412. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9413. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9414. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9415. EXPECT_FALSE(svr.is_valid());
  9416. }
  9417. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9418. Server svr;
  9419. auto captured = Error::Success;
  9420. svr.set_error_logger(
  9421. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9422. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9423. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9424. }
  9425. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9426. std::string out;
  9427. std::string request(
  9428. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9429. test_raw_request(request, &out);
  9430. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9431. }
  9432. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9433. std::string out;
  9434. std::string request(
  9435. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9436. test_raw_request(request, &out);
  9437. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9438. }
  9439. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9440. std::string out;
  9441. std::string request(
  9442. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9443. test_raw_request(request, &out);
  9444. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9445. }
  9446. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9447. std::string out;
  9448. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9449. "Host: localhost\r\n"
  9450. "Test: \r\n\r\n",
  9451. &out);
  9452. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9453. }
  9454. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9455. Server svr;
  9456. std::string x_custom;
  9457. std::string cookie;
  9458. std::string xff;
  9459. std::string x_unicode;
  9460. std::string x_iis;
  9461. svr.Get("/check", [&](const Request &req, Response &res) {
  9462. x_custom = req.get_header_value("X-Custom");
  9463. cookie = req.get_header_value("Cookie");
  9464. xff = req.get_header_value("X-Forwarded-For");
  9465. x_unicode = req.get_header_value("X-Unicode");
  9466. x_iis = req.get_header_value("X-IIS");
  9467. res.set_content("ok", "text/plain");
  9468. });
  9469. thread t = thread([&] { svr.listen(HOST, PORT); });
  9470. auto se = detail::scope_exit([&] {
  9471. svr.stop();
  9472. t.join();
  9473. ASSERT_FALSE(svr.is_running());
  9474. });
  9475. svr.wait_until_ready();
  9476. const std::string req = "GET /check HTTP/1.1\r\n"
  9477. "Host: localhost\r\n"
  9478. "X-Custom: a%0D%0AInjected: b\r\n"
  9479. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9480. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9481. "X-Unicode: %E3%81%82\r\n"
  9482. "X-IIS: %u00E9\r\n"
  9483. "Connection: close\r\n"
  9484. "\r\n";
  9485. std::string res;
  9486. ASSERT_TRUE(send_request(5, req, &res));
  9487. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9488. // Every value must be returned verbatim (wire form), with no decoding.
  9489. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9490. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9491. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9492. EXPECT_EQ("%E3%81%82", x_unicode);
  9493. EXPECT_EQ("%u00E9", x_iis);
  9494. }
  9495. // Applications that previously relied on automatic percent-decoding can
  9496. // reproduce the old behavior by explicitly calling decode_path_component()
  9497. // or, for RFC 3986 conformance, decode_uri_component().
  9498. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9499. Server svr;
  9500. std::string decoded;
  9501. svr.Get("/check", [&](const Request &req, Response &res) {
  9502. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9503. res.set_content("ok", "text/plain");
  9504. });
  9505. thread t = thread([&] { svr.listen(HOST, PORT); });
  9506. auto se = detail::scope_exit([&] {
  9507. svr.stop();
  9508. t.join();
  9509. ASSERT_FALSE(svr.is_running());
  9510. });
  9511. svr.wait_until_ready();
  9512. const std::string req = "GET /check HTTP/1.1\r\n"
  9513. "Host: localhost\r\n"
  9514. "X-Custom: hello%20world\r\n"
  9515. "Connection: close\r\n"
  9516. "\r\n";
  9517. std::string res;
  9518. ASSERT_TRUE(send_request(5, req, &res));
  9519. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9520. EXPECT_EQ("hello world", decoded);
  9521. }
  9522. // Regression test for #2033. Browsers send Referer values that include
  9523. // percent-encoded characters such as %0A inside the URL. Decoding the
  9524. // header value would either trip the post-decode CR/LF/NUL guard (the
  9525. // original bug, returning 400) or, after that guard was relaxed, silently
  9526. // store a literal LF — both unacceptable. The wire form must round-trip.
  9527. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9528. Server svr;
  9529. std::string referer;
  9530. svr.Get("/check", [&](const Request &req, Response &res) {
  9531. referer = req.get_header_value("Referer");
  9532. res.set_content("ok", "text/plain");
  9533. });
  9534. thread t = thread([&] { svr.listen(HOST, PORT); });
  9535. auto se = detail::scope_exit([&] {
  9536. svr.stop();
  9537. t.join();
  9538. ASSERT_FALSE(svr.is_running());
  9539. });
  9540. svr.wait_until_ready();
  9541. const std::string req = "GET /check HTTP/1.1\r\n"
  9542. "Host: localhost\r\n"
  9543. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9544. "Connection: close\r\n"
  9545. "\r\n";
  9546. std::string res;
  9547. ASSERT_TRUE(send_request(5, req, &res));
  9548. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9549. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9550. }
  9551. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9552. Server svr;
  9553. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9554. res.set_header("Cache-Control", "no-cache");
  9555. res.set_chunked_content_provider(
  9556. "text/event-stream", [](size_t offset, DataSink &sink) {
  9557. std::string s = "data:";
  9558. s += std::to_string(offset);
  9559. s += "\n\n";
  9560. auto ret = sink.write(s.data(), s.size());
  9561. EXPECT_TRUE(ret);
  9562. std::this_thread::sleep_for(std::chrono::seconds(1));
  9563. return true;
  9564. });
  9565. });
  9566. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9567. svr.wait_until_ready();
  9568. Client client(HOST, PORT);
  9569. const Headers headers = {{"Accept", "text/event-stream"}};
  9570. auto get_thread = std::thread([&client, &headers]() {
  9571. auto res = client.Get(
  9572. "/events", headers,
  9573. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9574. });
  9575. auto se = detail::scope_exit([&] {
  9576. svr.stop();
  9577. get_thread.join();
  9578. listen_thread.join();
  9579. ASSERT_FALSE(svr.is_running());
  9580. });
  9581. // Give GET time to get a few messages.
  9582. std::this_thread::sleep_for(std::chrono::seconds(2));
  9583. }
  9584. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9585. httplib::Server svr;
  9586. svr.Post("/hi",
  9587. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9588. res.status = StatusCode::OK_200;
  9589. });
  9590. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9591. svr.wait_until_ready();
  9592. Client cli(HOST, PORT);
  9593. auto res = cli.Post("/hi", "data", "text/plain");
  9594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9595. EXPECT_EQ(StatusCode::OK_200, res->status);
  9596. svr.stop();
  9597. thread.join();
  9598. ASSERT_FALSE(svr.is_running());
  9599. res = cli.Post("/hi", "data", "text/plain");
  9600. ASSERT_FALSE(res);
  9601. }
  9602. TEST(ServerStopTest, ListenFailure) {
  9603. Server svr;
  9604. auto t = thread([&]() {
  9605. auto ret = svr.listen("????", PORT);
  9606. EXPECT_FALSE(ret);
  9607. });
  9608. svr.wait_until_ready();
  9609. svr.stop();
  9610. t.join();
  9611. }
  9612. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9613. TEST(ServerStopTest, Decommision) {
  9614. Server svr;
  9615. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9616. for (int i = 0; i < 4; i++) {
  9617. auto is_even = !(i % 2);
  9618. std::thread t{[&] {
  9619. try {
  9620. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9621. if (is_even) {
  9622. throw std::runtime_error("Some thing that happens to go wrong.");
  9623. }
  9624. svr.listen(HOST, PORT);
  9625. } catch (...) { svr.decommission(); }
  9626. }};
  9627. svr.wait_until_ready();
  9628. // Server is up
  9629. {
  9630. Client cli(HOST, PORT);
  9631. auto res = cli.Get("/hi");
  9632. if (is_even) {
  9633. EXPECT_FALSE(res);
  9634. } else {
  9635. EXPECT_TRUE(res);
  9636. EXPECT_EQ("hi...", res->body);
  9637. }
  9638. }
  9639. svr.stop();
  9640. t.join();
  9641. // Server is down...
  9642. {
  9643. Client cli(HOST, PORT);
  9644. auto res = cli.Get("/hi");
  9645. EXPECT_FALSE(res);
  9646. }
  9647. }
  9648. }
  9649. #endif
  9650. // Helper function for string body upload progress tests
  9651. template <typename SetupHandler, typename ClientCall>
  9652. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9653. ClientCall &&client_call,
  9654. const string &body) {
  9655. Server svr;
  9656. setup_handler(svr);
  9657. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9658. auto se = detail::scope_exit([&] {
  9659. svr.stop();
  9660. t.join();
  9661. });
  9662. svr.wait_until_ready();
  9663. Client cli(HOST, PORT);
  9664. vector<uint64_t> progress_values;
  9665. bool progress_called = false;
  9666. auto res =
  9667. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9668. progress_values.push_back(current);
  9669. progress_called = true;
  9670. return true;
  9671. });
  9672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9673. EXPECT_EQ(200, res->status);
  9674. EXPECT_TRUE(progress_called);
  9675. }
  9676. TEST(UploadProgressTest, PostStringBodyBasic) {
  9677. TestStringBodyUploadProgress(
  9678. [](Server &svr) {
  9679. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9680. res.set_content("received", "text/plain");
  9681. });
  9682. },
  9683. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9684. return cli.Post("/test", body, "text/plain", progress_callback);
  9685. },
  9686. "test data for upload progress");
  9687. }
  9688. TEST(UploadProgressTest, PutStringBodyBasic) {
  9689. TestStringBodyUploadProgress(
  9690. [](Server &svr) {
  9691. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9692. res.set_content("put received", "text/plain");
  9693. });
  9694. },
  9695. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9696. return cli.Put("/test", body, "text/plain", progress_callback);
  9697. },
  9698. "put test data for upload progress");
  9699. }
  9700. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9701. TestStringBodyUploadProgress(
  9702. [](Server &svr) {
  9703. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9704. res.set_content("patch received", "text/plain");
  9705. });
  9706. },
  9707. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9708. return cli.Patch("/test", body, "text/plain", progress_callback);
  9709. },
  9710. "patch test data for upload progress");
  9711. }
  9712. // Helper function for content provider upload progress tests
  9713. template <typename SetupHandler, typename ClientCall>
  9714. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9715. ClientCall &&client_call) {
  9716. Server svr;
  9717. setup_handler(svr);
  9718. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9719. auto se = detail::scope_exit([&] {
  9720. svr.stop();
  9721. t.join();
  9722. });
  9723. svr.wait_until_ready();
  9724. Client cli(HOST, PORT);
  9725. vector<uint64_t> progress_values;
  9726. auto res =
  9727. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9728. progress_values.push_back(current);
  9729. return true;
  9730. });
  9731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9732. EXPECT_EQ(200, res->status);
  9733. EXPECT_FALSE(progress_values.empty());
  9734. }
  9735. TEST(UploadProgressTest, PostContentProviderProgress) {
  9736. TestContentProviderUploadProgress(
  9737. [](Server &svr) {
  9738. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9739. res.set_content("provider received", "text/plain");
  9740. });
  9741. },
  9742. [](Client &cli, UploadProgress progress_callback) {
  9743. return cli.Post(
  9744. "/test", 10,
  9745. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9746. sink.os << "test data";
  9747. return true;
  9748. },
  9749. "text/plain", progress_callback);
  9750. });
  9751. }
  9752. // Helper function for multipart upload progress tests
  9753. template <typename SetupHandler, typename ClientCall>
  9754. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9755. ClientCall &&client_call,
  9756. const string &endpoint) {
  9757. Server svr;
  9758. setup_handler(svr);
  9759. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9760. auto se = detail::scope_exit([&] {
  9761. svr.stop();
  9762. t.join();
  9763. });
  9764. svr.wait_until_ready();
  9765. Client cli(HOST, PORT);
  9766. vector<uint64_t> progress_values;
  9767. UploadFormDataItems items = {
  9768. {"field1", "value1", "", ""},
  9769. {"field2", "longer value for progress tracking test", "", ""},
  9770. {"file1", "file content data for upload progress", "test.txt",
  9771. "text/plain"}};
  9772. auto res = client_call(cli, endpoint, items,
  9773. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9774. progress_values.push_back(current);
  9775. return true;
  9776. });
  9777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9778. EXPECT_EQ(200, res->status);
  9779. EXPECT_FALSE(progress_values.empty());
  9780. }
  9781. TEST(UploadProgressTest, PostMultipartProgress) {
  9782. TestMultipartUploadProgress(
  9783. [](Server &svr) {
  9784. svr.Post("/multipart", [](const Request &req, Response &res) {
  9785. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9786. res.set_content("multipart received", "text/plain");
  9787. });
  9788. },
  9789. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9790. UploadProgress progress_callback) {
  9791. return cli.Post(endpoint, items, progress_callback);
  9792. },
  9793. "/multipart");
  9794. }
  9795. // Helper function for basic download progress tests
  9796. template <typename SetupHandler, typename ClientCall>
  9797. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9798. ClientCall &&client_call, const string &endpoint,
  9799. size_t expected_content_size) {
  9800. Server svr;
  9801. setup_handler(svr);
  9802. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9803. auto se = detail::scope_exit([&] {
  9804. svr.stop();
  9805. t.join();
  9806. });
  9807. svr.wait_until_ready();
  9808. Client cli(HOST, PORT);
  9809. vector<uint64_t> progress_values;
  9810. auto res = client_call(cli, endpoint,
  9811. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9812. progress_values.push_back(current);
  9813. return true;
  9814. });
  9815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9816. EXPECT_EQ(200, res->status);
  9817. EXPECT_FALSE(progress_values.empty());
  9818. EXPECT_EQ(expected_content_size, res->body.size());
  9819. }
  9820. TEST(DownloadProgressTest, GetBasic) {
  9821. TestBasicDownloadProgress(
  9822. [](Server &svr) {
  9823. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9824. string content(1000, 'D');
  9825. res.set_content(content, "text/plain");
  9826. });
  9827. },
  9828. [](Client &cli, const string &endpoint,
  9829. DownloadProgress progress_callback) {
  9830. return cli.Get(endpoint, progress_callback);
  9831. },
  9832. "/download", 1000u);
  9833. }
  9834. // Helper function for content receiver download progress tests
  9835. template <typename SetupHandler, typename ClientCall>
  9836. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9837. ClientCall &&client_call,
  9838. const string &endpoint,
  9839. size_t expected_content_size) {
  9840. Server svr;
  9841. setup_handler(svr);
  9842. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9843. auto se = detail::scope_exit([&] {
  9844. svr.stop();
  9845. t.join();
  9846. });
  9847. svr.wait_until_ready();
  9848. Client cli(HOST, PORT);
  9849. vector<uint64_t> progress_values;
  9850. string received_body;
  9851. auto res = client_call(
  9852. cli, endpoint,
  9853. [&](const char *data, size_t data_length) -> bool {
  9854. received_body.append(data, data_length);
  9855. return true;
  9856. },
  9857. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9858. progress_values.push_back(current);
  9859. return true;
  9860. });
  9861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9862. EXPECT_EQ(200, res->status);
  9863. EXPECT_FALSE(progress_values.empty());
  9864. EXPECT_EQ(expected_content_size, received_body.size());
  9865. EXPECT_TRUE(res->body.empty());
  9866. }
  9867. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9868. TestContentReceiverDownloadProgress(
  9869. [](Server &svr) {
  9870. svr.Get("/download-receiver",
  9871. [](const Request & /*req*/, Response &res) {
  9872. string content(2000, 'R');
  9873. res.set_content(content, "text/plain");
  9874. });
  9875. },
  9876. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9877. DownloadProgress progress_callback) {
  9878. return cli.Get(endpoint, content_receiver, progress_callback);
  9879. },
  9880. "/download-receiver", 2000u);
  9881. }
  9882. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9883. // A provider reaching a pass with nothing to hand over - an empty buffer
  9884. // popped off a queue, say - must not be taken to mean the body is finished.
  9885. // It used to end the loop with the terminating chunk unwritten while the
  9886. // server still considered the response complete, so the peer waited for an
  9887. // end that never arrived.
  9888. Server svr;
  9889. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9890. auto step = std::make_shared<int>(0);
  9891. res.set_chunked_content_provider("text/plain",
  9892. [step](size_t /*offset*/, DataSink &sink) {
  9893. switch ((*step)++) {
  9894. case 0: sink.write("", 0); break;
  9895. case 1: sink.write("hello", 5); break;
  9896. default: sink.done(); break;
  9897. }
  9898. return true;
  9899. });
  9900. });
  9901. auto port = svr.bind_to_any_port(HOST);
  9902. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9903. auto listen_se = detail::scope_exit([&] {
  9904. svr.stop();
  9905. listen_thread.join();
  9906. ASSERT_FALSE(svr.is_running());
  9907. });
  9908. svr.wait_until_ready();
  9909. Client cli(HOST, port);
  9910. // Without the fix the body is never terminated, so bound the wait rather
  9911. // than letting the test hang on the default read timeout.
  9912. cli.set_read_timeout(5, 0);
  9913. auto res = cli.Get("/stream");
  9914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9915. EXPECT_EQ(StatusCode::OK_200, res->status);
  9916. EXPECT_EQ("hello", res->body);
  9917. }
  9918. TEST(StreamingTest, NoContentLengthStreaming) {
  9919. Server svr;
  9920. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9921. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9922. if (offset < 6) {
  9923. sink.os << (offset < 3 ? "a" : "b");
  9924. } else {
  9925. sink.done();
  9926. }
  9927. return true;
  9928. });
  9929. });
  9930. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9931. auto listen_se = detail::scope_exit([&] {
  9932. svr.stop();
  9933. listen_thread.join();
  9934. ASSERT_FALSE(svr.is_running());
  9935. });
  9936. svr.wait_until_ready();
  9937. Client client(HOST, PORT);
  9938. auto get_thread = std::thread([&client]() {
  9939. std::string s;
  9940. auto res =
  9941. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9942. s += std::string(data, len);
  9943. return true;
  9944. });
  9945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9946. EXPECT_EQ(StatusCode::OK_200, res->status);
  9947. EXPECT_EQ("aaabbb", s);
  9948. });
  9949. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9950. // Give GET time to get a few messages.
  9951. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9952. }
  9953. TEST(MountTest, Unmount) {
  9954. Server svr;
  9955. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9956. auto se = detail::scope_exit([&] {
  9957. svr.stop();
  9958. listen_thread.join();
  9959. ASSERT_FALSE(svr.is_running());
  9960. });
  9961. svr.wait_until_ready();
  9962. Client cli("localhost", PORT);
  9963. svr.set_mount_point("/mount2", "./www2");
  9964. auto res = cli.Get("/");
  9965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9966. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9967. res = cli.Get("/mount2/dir/test.html");
  9968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9969. EXPECT_EQ(StatusCode::OK_200, res->status);
  9970. svr.set_mount_point("/", "./www");
  9971. res = cli.Get("/dir/");
  9972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9973. EXPECT_EQ(StatusCode::OK_200, res->status);
  9974. svr.remove_mount_point("/");
  9975. res = cli.Get("/dir/");
  9976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9977. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9978. svr.remove_mount_point("/mount2");
  9979. res = cli.Get("/mount2/dir/test.html");
  9980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9981. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9982. }
  9983. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  9984. Server svr;
  9985. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  9986. svr.Get("/api/hello", [](const Request &, Response &res) {
  9987. res.set_content("api", "text/plain");
  9988. });
  9989. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9990. auto se = detail::scope_exit([&] {
  9991. svr.stop();
  9992. listen_thread.join();
  9993. ASSERT_FALSE(svr.is_running());
  9994. });
  9995. svr.wait_until_ready();
  9996. Client cli(HOST, PORT);
  9997. auto res = cli.Get("/dir/test.html");
  9998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9999. EXPECT_EQ(StatusCode::OK_200, res->status);
  10000. res = cli.Get("/api/hello");
  10001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10002. EXPECT_EQ(StatusCode::OK_200, res->status);
  10003. EXPECT_EQ("api", res->body);
  10004. }
  10005. TEST(MountTest, PathSegmentBoundary) {
  10006. Server svr;
  10007. svr.set_mount_point("/mount2", "./www2");
  10008. svr.set_mount_point("/", "./www");
  10009. auto port = svr.bind_to_any_port(HOST);
  10010. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10011. auto se = detail::scope_exit([&] {
  10012. svr.stop();
  10013. listen_thread.join();
  10014. ASSERT_FALSE(svr.is_running());
  10015. });
  10016. svr.wait_until_ready();
  10017. Client cli(HOST, port);
  10018. auto res = cli.Get("/mount2/dir/test.html");
  10019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10020. EXPECT_EQ(StatusCode::OK_200, res->status);
  10021. // "/mount2" must not match part-way through a path segment.
  10022. res = cli.Get("/mount2dir/test.html");
  10023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10024. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10025. // A mount point ending in '/' keeps matching every path below it.
  10026. res = cli.Get("/dir/test.html");
  10027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10028. EXPECT_EQ(StatusCode::OK_200, res->status);
  10029. }
  10030. TEST(MountTest, Redicect) {
  10031. Server svr;
  10032. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10033. auto se = detail::scope_exit([&] {
  10034. svr.stop();
  10035. listen_thread.join();
  10036. ASSERT_FALSE(svr.is_running());
  10037. });
  10038. svr.set_mount_point("/", "./www");
  10039. svr.wait_until_ready();
  10040. Client cli("localhost", PORT);
  10041. auto res = cli.Get("/dir/");
  10042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10043. EXPECT_EQ(StatusCode::OK_200, res->status);
  10044. res = cli.Get("/dir");
  10045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10046. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10047. res = cli.Get("/file");
  10048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10049. EXPECT_EQ(StatusCode::OK_200, res->status);
  10050. res = cli.Get("/file/");
  10051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10052. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10053. cli.set_follow_location(true);
  10054. res = cli.Get("/dir");
  10055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10056. EXPECT_EQ(StatusCode::OK_200, res->status);
  10057. }
  10058. TEST(MountTest, MultibytesPathName) {
  10059. Server svr;
  10060. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10061. auto se = detail::scope_exit([&] {
  10062. svr.stop();
  10063. listen_thread.join();
  10064. ASSERT_FALSE(svr.is_running());
  10065. });
  10066. svr.set_mount_point("/", "./www");
  10067. svr.wait_until_ready();
  10068. Client cli("localhost", PORT);
  10069. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10071. EXPECT_EQ(StatusCode::OK_200, res->status);
  10072. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10073. }
  10074. #ifdef _WIN32
  10075. // Issue #2435: mmap::open() must succeed even when another handle holds
  10076. // the file open for writing (e.g. an active log file).
  10077. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10078. const char *path = "mmap_concurrent_writer_test.txt";
  10079. const char *content = "hello";
  10080. {
  10081. std::ofstream f(path, std::ios::binary);
  10082. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10083. }
  10084. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10085. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10086. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10087. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10088. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10089. detail::mmap m(path);
  10090. ASSERT_TRUE(m.is_open());
  10091. EXPECT_EQ(strlen(content), m.size());
  10092. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  10093. }
  10094. #endif
  10095. #ifndef _WIN32
  10096. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  10097. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  10098. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  10099. TEST(MmapTest, FailedMappingIsNotOpen) {
  10100. const char *path = "./mmap_failed_mapping_test_dir";
  10101. ASSERT_EQ(0, ::mkdir(path, 0755));
  10102. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10103. detail::mmap m(path);
  10104. EXPECT_FALSE(m.is_open());
  10105. EXPECT_EQ(0U, m.size());
  10106. EXPECT_NE(static_cast<const void *>(m.data()),
  10107. static_cast<const void *>(MAP_FAILED));
  10108. }
  10109. #endif
  10110. TEST(KeepAliveTest, ReadTimeout) {
  10111. Server svr;
  10112. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10113. std::this_thread::sleep_for(std::chrono::seconds(2));
  10114. res.set_content("a", "text/plain");
  10115. });
  10116. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10117. res.set_content("b", "text/plain");
  10118. });
  10119. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10120. auto se = detail::scope_exit([&] {
  10121. svr.stop();
  10122. listen_thread.join();
  10123. ASSERT_FALSE(svr.is_running());
  10124. });
  10125. svr.wait_until_ready();
  10126. Client cli("localhost", PORT);
  10127. cli.set_keep_alive(true);
  10128. cli.set_read_timeout(std::chrono::seconds(1));
  10129. auto resa = cli.Get("/a");
  10130. ASSERT_FALSE(resa);
  10131. EXPECT_EQ(Error::Read, resa.error());
  10132. auto resb = cli.Get("/b");
  10133. ASSERT_TRUE(resb);
  10134. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10135. EXPECT_EQ("b", resb->body);
  10136. }
  10137. TEST(KeepAliveTest, MaxCount) {
  10138. size_t keep_alive_max_count = 3;
  10139. Server svr;
  10140. svr.set_keep_alive_max_count(keep_alive_max_count);
  10141. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10142. res.set_content("Hello World!", "text/plain");
  10143. });
  10144. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10145. auto se = detail::scope_exit([&] {
  10146. svr.stop();
  10147. listen_thread.join();
  10148. ASSERT_FALSE(svr.is_running());
  10149. });
  10150. svr.wait_until_ready();
  10151. Client cli(HOST, PORT);
  10152. cli.set_keep_alive(true);
  10153. for (size_t i = 0; i < 5; i++) {
  10154. auto result = cli.Get("/hi");
  10155. ASSERT_TRUE(result);
  10156. EXPECT_EQ(StatusCode::OK_200, result->status);
  10157. if (i == keep_alive_max_count - 1) {
  10158. EXPECT_EQ("close", result->get_header_value("Connection"));
  10159. } else {
  10160. EXPECT_FALSE(result->has_header("Connection"));
  10161. }
  10162. }
  10163. }
  10164. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10165. // can pull the next one into the server's buffer. The server must serve it
  10166. // without waiting for the socket to become readable again. The keep-alive
  10167. // timeout outlasts the client's read timeout, so a request left waiting for it
  10168. // shows up as a missing response.
  10169. static void serve_pipelining_routes(Server &svr,
  10170. const std::function<void(int)> &client) {
  10171. svr.set_keep_alive_timeout(5);
  10172. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10173. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10174. });
  10175. svr.Post("/echo", [](const Request &req, Response &res) {
  10176. res.set_content("echo " + req.body, "text/plain");
  10177. });
  10178. auto port = svr.bind_to_any_port(HOST);
  10179. thread t = thread([&] { svr.listen_after_bind(); });
  10180. auto se = detail::scope_exit([&] {
  10181. svr.stop();
  10182. t.join();
  10183. });
  10184. svr.wait_until_ready();
  10185. client(port);
  10186. }
  10187. static std::string
  10188. send_pipelined_requests(const std::vector<std::string> &parts) {
  10189. Server svr;
  10190. std::string res;
  10191. serve_pipelining_routes(svr, [&](int port) {
  10192. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10193. });
  10194. return res;
  10195. }
  10196. static void expect_in_order(const std::string &res,
  10197. const std::vector<std::string> &bodies) {
  10198. size_t pos = 0;
  10199. for (const auto &body : bodies) {
  10200. pos = res.find(body, pos);
  10201. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10202. pos += body.size();
  10203. }
  10204. }
  10205. TEST(KeepAliveTest, PipelinedRequests) {
  10206. auto res = send_pipelined_requests(
  10207. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10208. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10209. "Content-Length: 4\r\n\r\nbody"
  10210. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10211. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10212. }
  10213. // The second request starts in the server's buffer and ends on the socket.
  10214. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10215. auto res =
  10216. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10217. "GET /hi/2 HTTP/1.1\r\nHo",
  10218. "st: localhost\r\nConnection: close\r\n\r\n"});
  10219. expect_in_order(res, {"hi 1", "hi 2"});
  10220. }
  10221. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10222. // CRLF after a body does not turn into a 400 for the next request.
  10223. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10224. auto res = send_pipelined_requests(
  10225. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10226. "Content-Length: 4\r\n\r\nbody\r\n"
  10227. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10228. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10229. expect_in_order(res, {"echo body", "hi 2"});
  10230. }
  10231. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10232. // must not be served as the next request.
  10233. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10234. auto res = send_pipelined_requests(
  10235. {"INVALID REQUEST LINE\r\n\r\n"
  10236. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10237. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10238. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10239. }
  10240. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10241. // Over TLS, the next request is held by the TLS library as already decrypted
  10242. // data rather than on the socket.
  10243. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10244. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10245. std::string res;
  10246. serve_pipelining_routes(svr, [&](int port) {
  10247. auto error = Error::Success;
  10248. auto sock = detail::create_client_socket(
  10249. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10250. /*connection_timeout_sec=*/5, 0,
  10251. /*read_timeout_sec=*/2, 0,
  10252. /*write_timeout_sec=*/5, 0, std::string(), error);
  10253. ASSERT_NE(INVALID_SOCKET, sock);
  10254. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  10255. auto ctx = SSL_CTX_new(TLS_client_method());
  10256. auto ssl = SSL_new(ctx);
  10257. auto ssl_se = detail::scope_exit([&] {
  10258. SSL_free(ssl);
  10259. SSL_CTX_free(ctx);
  10260. });
  10261. SSL_set_fd(ssl, static_cast<int>(sock));
  10262. ASSERT_EQ(1, SSL_connect(ssl));
  10263. // One write, so all three requests arrive in one TLS record
  10264. const std::string req =
  10265. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10266. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10267. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  10268. ASSERT_EQ(static_cast<int>(req.size()),
  10269. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  10270. char buf[512];
  10271. int n;
  10272. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10273. res.append(buf, static_cast<size_t>(n));
  10274. }
  10275. });
  10276. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10277. }
  10278. #endif
  10279. TEST(KeepAliveTest, Issue1041) {
  10280. Server svr;
  10281. svr.set_keep_alive_timeout(3);
  10282. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10283. res.set_content("Hello World!", "text/plain");
  10284. });
  10285. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10286. auto se = detail::scope_exit([&] {
  10287. svr.stop();
  10288. listen_thread.join();
  10289. ASSERT_FALSE(svr.is_running());
  10290. });
  10291. svr.wait_until_ready();
  10292. Client cli(HOST, PORT);
  10293. cli.set_keep_alive(true);
  10294. auto result = cli.Get("/hi");
  10295. ASSERT_TRUE(result);
  10296. EXPECT_EQ(StatusCode::OK_200, result->status);
  10297. std::this_thread::sleep_for(std::chrono::seconds(5));
  10298. result = cli.Get("/hi");
  10299. ASSERT_TRUE(result);
  10300. EXPECT_EQ(StatusCode::OK_200, result->status);
  10301. }
  10302. TEST(KeepAliveTest, Issue1959) {
  10303. Server svr;
  10304. svr.set_keep_alive_timeout(5);
  10305. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10306. res.set_content("a", "text/plain");
  10307. });
  10308. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10309. auto se = detail::scope_exit([&] {
  10310. if (!svr.is_running()) return;
  10311. svr.stop();
  10312. listen_thread.join();
  10313. ASSERT_FALSE(svr.is_running());
  10314. });
  10315. svr.wait_until_ready();
  10316. Client cli("localhost", PORT);
  10317. cli.set_keep_alive(true);
  10318. using namespace std::chrono;
  10319. auto start = steady_clock::now();
  10320. cli.Get("/a");
  10321. svr.stop();
  10322. listen_thread.join();
  10323. auto end = steady_clock::now();
  10324. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10325. EXPECT_LT(elapsed, 5000);
  10326. }
  10327. #ifdef CPPHTTPLIB_SSL_ENABLED
  10328. TEST(KeepAliveTest, SSLClientReconnection) {
  10329. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10330. ASSERT_TRUE(svr.is_valid());
  10331. svr.set_keep_alive_timeout(1);
  10332. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10333. res.set_content("Hello World!", "text/plain");
  10334. });
  10335. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10336. auto se = detail::scope_exit([&] {
  10337. svr.stop();
  10338. listen_thread.join();
  10339. ASSERT_FALSE(svr.is_running());
  10340. });
  10341. svr.wait_until_ready();
  10342. SSLClient cli(HOST, PORT);
  10343. cli.enable_server_certificate_verification(false);
  10344. cli.set_keep_alive(true);
  10345. auto result = cli.Get("/hi");
  10346. ASSERT_TRUE(result);
  10347. EXPECT_EQ(StatusCode::OK_200, result->status);
  10348. result = cli.Get("/hi");
  10349. ASSERT_TRUE(result);
  10350. EXPECT_EQ(StatusCode::OK_200, result->status);
  10351. std::this_thread::sleep_for(std::chrono::seconds(2));
  10352. // Recoonect
  10353. result = cli.Get("/hi");
  10354. ASSERT_TRUE(result);
  10355. EXPECT_EQ(StatusCode::OK_200, result->status);
  10356. result = cli.Get("/hi");
  10357. ASSERT_TRUE(result);
  10358. EXPECT_EQ(StatusCode::OK_200, result->status);
  10359. }
  10360. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10361. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10362. ASSERT_TRUE(svr.is_valid());
  10363. svr.set_keep_alive_timeout(1);
  10364. std::string content = "reconnect";
  10365. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10366. res.set_content("Hello World!", "text/plain");
  10367. });
  10368. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10369. auto se = detail::scope_exit([&] {
  10370. svr.stop();
  10371. listen_thread.join();
  10372. ASSERT_FALSE(svr.is_running());
  10373. });
  10374. svr.wait_until_ready();
  10375. SSLClient cli(HOST, PORT);
  10376. cli.enable_server_certificate_verification(false);
  10377. cli.set_keep_alive(true);
  10378. auto result = cli.Post(
  10379. "/hi", content.size(),
  10380. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10381. sink.write(content.c_str(), content.size());
  10382. return true;
  10383. },
  10384. "text/plain");
  10385. ASSERT_TRUE(result);
  10386. EXPECT_EQ(200, result->status);
  10387. std::this_thread::sleep_for(std::chrono::seconds(2));
  10388. // Recoonect
  10389. result = cli.Post(
  10390. "/hi", content.size(),
  10391. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10392. sink.write(content.c_str(), content.size());
  10393. return true;
  10394. },
  10395. "text/plain");
  10396. ASSERT_TRUE(result);
  10397. EXPECT_EQ(200, result->status);
  10398. result = cli.Post(
  10399. "/hi", content.size(),
  10400. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10401. sink.write(content.c_str(), content.size());
  10402. return true;
  10403. },
  10404. "text/plain");
  10405. ASSERT_TRUE(result);
  10406. EXPECT_EQ(200, result->status);
  10407. }
  10408. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10409. using namespace httplib::tls;
  10410. {
  10411. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10412. ASSERT_TRUE(svr.is_valid());
  10413. svr.Get("/sni", [&](const Request &req, Response &res) {
  10414. std::string expected = req.sni();
  10415. EXPECT_EQ(expected, req.get_param_value("expected"));
  10416. res.set_content("ok", "text/plain");
  10417. });
  10418. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10419. auto se = detail::scope_exit([&] {
  10420. svr.stop();
  10421. listen_thread.join();
  10422. ASSERT_FALSE(svr.is_running());
  10423. });
  10424. svr.wait_until_ready();
  10425. {
  10426. SSLClient cli("localhost", PORT);
  10427. cli.enable_server_certificate_verification(false);
  10428. auto res = cli.Get("/sni?expected=localhost");
  10429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10430. }
  10431. {
  10432. SSLClient cli("::1", PORT);
  10433. cli.enable_server_certificate_verification(false);
  10434. auto res = cli.Get("/sni?expected=");
  10435. // NOTE: This may fail if the server is listening on IPv4 only
  10436. // (e.g., when localhost resolves to 127.0.0.1 only)
  10437. if (res) {
  10438. EXPECT_EQ(StatusCode::OK_200, res->status);
  10439. } else {
  10440. EXPECT_EQ(Error::Connection, res.error());
  10441. }
  10442. }
  10443. }
  10444. }
  10445. #endif
  10446. TEST(ClientProblemDetectionTest, ContentProvider) {
  10447. Server svr;
  10448. size_t content_length = 1024 * 1024;
  10449. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10450. res.set_content_provider(
  10451. content_length, "text/plain",
  10452. [&](size_t offset, size_t length, DataSink &sink) {
  10453. auto out_len = std::min(length, static_cast<size_t>(1024));
  10454. std::string out(out_len, '@');
  10455. sink.write(out.data(), out_len);
  10456. return offset < 4096;
  10457. },
  10458. [](bool success) { ASSERT_FALSE(success); });
  10459. });
  10460. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10461. res.set_content_provider(
  10462. 0, "text/plain",
  10463. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10464. EXPECT_TRUE(false);
  10465. return true;
  10466. },
  10467. [](bool success) { ASSERT_FALSE(success); });
  10468. });
  10469. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10470. auto se = detail::scope_exit([&] {
  10471. svr.stop();
  10472. listen_thread.join();
  10473. ASSERT_FALSE(svr.is_running());
  10474. });
  10475. svr.wait_until_ready();
  10476. Client cli("localhost", PORT);
  10477. {
  10478. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10479. size_t /*data_length*/) { return false; });
  10480. ASSERT_FALSE(res);
  10481. }
  10482. {
  10483. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10484. size_t /*data_length*/) { return false; });
  10485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10486. }
  10487. }
  10488. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10489. // A provider that reports success without writing anything and without
  10490. // calling done() used to be handed the same offset and length again on every
  10491. // pass, so it spun for as long as the peer stayed connected.
  10492. Server svr;
  10493. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10494. res.set_content("ok", "text/plain");
  10495. });
  10496. auto port = svr.bind_to_any_port(HOST);
  10497. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10498. auto se = detail::scope_exit([&] {
  10499. svr.stop();
  10500. listen_thread.join();
  10501. ASSERT_FALSE(svr.is_running());
  10502. });
  10503. svr.wait_until_ready();
  10504. std::atomic<int> call_count{0};
  10505. Client cli(HOST, port);
  10506. auto res = cli.Post(
  10507. "/", 1024,
  10508. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10509. // Give up after enough passes to show the spin, so that losing the
  10510. // check below fails this test instead of hanging it.
  10511. return ++call_count < 100;
  10512. },
  10513. "text/plain");
  10514. ASSERT_FALSE(res);
  10515. EXPECT_EQ(Error::Write, res.error());
  10516. EXPECT_EQ(1, call_count.load());
  10517. }
  10518. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10519. // A writer only has to assign `write`. The other three used to be left as
  10520. // empty std::functions, so a provider calling one threw
  10521. // std::bad_function_call out of the thread running it and took the whole
  10522. // process down.
  10523. DataSink sink;
  10524. std::string written;
  10525. sink.write = [&](const char *data, size_t data_len) {
  10526. written.append(data, data_len);
  10527. return true;
  10528. };
  10529. EXPECT_TRUE(sink.is_writable());
  10530. sink.done();
  10531. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10532. EXPECT_TRUE(written.empty());
  10533. }
  10534. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10535. // A sink that cannot carry trailers still has to finish.
  10536. DataSink sink;
  10537. auto done_count = 0;
  10538. sink.done = [&]() { done_count++; };
  10539. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10540. EXPECT_EQ(1, done_count);
  10541. }
  10542. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10543. Server svr;
  10544. const std::string body(4096, 'x');
  10545. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10546. res.set_content_provider(body.size(), "text/plain",
  10547. [&](size_t offset, size_t length, DataSink &sink) {
  10548. sink.write(body.data() + offset, length);
  10549. sink.done();
  10550. return true;
  10551. });
  10552. });
  10553. auto port = svr.bind_to_any_port(HOST);
  10554. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10555. auto se = detail::scope_exit([&] {
  10556. svr.stop();
  10557. listen_thread.join();
  10558. ASSERT_FALSE(svr.is_running());
  10559. });
  10560. svr.wait_until_ready();
  10561. Client cli(HOST, port);
  10562. auto res = cli.Get("/");
  10563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10564. EXPECT_EQ(StatusCode::OK_200, res->status);
  10565. EXPECT_EQ(body, res->body);
  10566. }
  10567. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10568. Server svr;
  10569. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10570. res.set_content_provider(
  10571. 1024, "text/plain",
  10572. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10573. sink.write("hello", 5);
  10574. sink.done(); // short of the 1024 bytes the response promised
  10575. return true;
  10576. });
  10577. });
  10578. auto port = svr.bind_to_any_port(HOST);
  10579. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10580. auto se = detail::scope_exit([&] {
  10581. svr.stop();
  10582. listen_thread.join();
  10583. ASSERT_FALSE(svr.is_running());
  10584. });
  10585. svr.wait_until_ready();
  10586. Client cli(HOST, port);
  10587. cli.set_read_timeout(5, 0);
  10588. // The response is short of its Content-Length, so the client cannot read a
  10589. // complete body. What matters is that this returns at all: a no-op done()
  10590. // would leave the writer looping over a provider that never makes progress.
  10591. auto res = cli.Get("/");
  10592. EXPECT_FALSE(res);
  10593. }
  10594. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10595. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10596. // The compressed path builds the whole body before connecting, so this
  10597. // fails client-side and never reaches a server.
  10598. Client cli(HOST, PORT);
  10599. cli.set_compress(true);
  10600. auto res = cli.Post(
  10601. "/", 1024,
  10602. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10603. sink.write("hello", 5);
  10604. sink.done(); // short of the 1024 bytes the request announced
  10605. return true;
  10606. },
  10607. "text/plain");
  10608. ASSERT_FALSE(res);
  10609. EXPECT_EQ(Error::Write, res.error());
  10610. }
  10611. #endif
  10612. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10613. Server svr;
  10614. svr.set_error_handler([](Request const &, Response &res) -> void {
  10615. res.set_chunked_content_provider(
  10616. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10617. sink.os << "hello";
  10618. sink.os << "world";
  10619. sink.done();
  10620. return true;
  10621. });
  10622. });
  10623. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10624. auto se = detail::scope_exit([&] {
  10625. svr.stop();
  10626. listen_thread.join();
  10627. ASSERT_FALSE(svr.is_running());
  10628. });
  10629. svr.wait_until_ready();
  10630. Client cli("localhost", PORT);
  10631. auto res = cli.Get("/");
  10632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10633. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10634. EXPECT_EQ("helloworld", res->body);
  10635. }
  10636. // A body set after a content provider must replace it, not be sent through it.
  10637. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  10638. Server svr;
  10639. svr.set_mount_point("/", "./www");
  10640. svr.set_file_request_handler([](const Request &req, Response &res) {
  10641. if (req.path == "/dir/test.html") {
  10642. res.status = StatusCode::Forbidden_403;
  10643. res.set_content(std::string(5000, 'D'), "text/plain");
  10644. } else if (req.path == "/file") {
  10645. res.status = StatusCode::Forbidden_403;
  10646. res.body = "Denied";
  10647. }
  10648. });
  10649. auto port = svr.bind_to_any_port(HOST);
  10650. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10651. auto se = detail::scope_exit([&] {
  10652. svr.stop();
  10653. t.join();
  10654. ASSERT_FALSE(svr.is_running());
  10655. });
  10656. svr.wait_until_ready();
  10657. Client cli(HOST, port);
  10658. {
  10659. auto res = cli.Get("/dir/test.html");
  10660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10661. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10662. EXPECT_EQ(std::string(5000, 'D'), res->body);
  10663. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  10664. }
  10665. {
  10666. auto res = cli.Get("/file");
  10667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10668. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10669. EXPECT_EQ("Denied", res->body);
  10670. }
  10671. {
  10672. auto res = cli.Get("/dir/index.html");
  10673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10674. EXPECT_EQ(StatusCode::OK_200, res->status);
  10675. EXPECT_EQ(0U, res->body.find("<html>"));
  10676. }
  10677. }
  10678. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  10679. Server svr;
  10680. std::vector<bool> released;
  10681. std::mutex released_mutex;
  10682. auto releaser = [&](bool success) {
  10683. std::lock_guard<std::mutex> guard(released_mutex);
  10684. released.push_back(success);
  10685. };
  10686. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  10687. return sink.write(&"hello"[offset], length);
  10688. };
  10689. svr.Get("/sized", [&](const Request &, Response &res) {
  10690. res.status = StatusCode::NotFound_404;
  10691. res.set_content_provider(5, "text/plain", provider, releaser);
  10692. });
  10693. svr.Get("/chunked", [&](const Request &, Response &res) {
  10694. res.status = StatusCode::ServiceUnavailable_503;
  10695. res.set_chunked_content_provider(
  10696. "text/plain",
  10697. [](size_t, DataSink &sink) {
  10698. sink.os << "chunk";
  10699. sink.done();
  10700. return true;
  10701. },
  10702. releaser);
  10703. });
  10704. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  10705. res.set_content_provider(5, "text/plain", provider, releaser);
  10706. throw std::runtime_error("after the provider");
  10707. });
  10708. svr.set_error_handler([](const Request &req, Response &res) {
  10709. // Leave the exception handler's content to it.
  10710. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  10711. res.set_content(std::string(1000, 'E'), "text/html");
  10712. return Server::HandlerResponse::Handled;
  10713. });
  10714. svr.set_exception_handler(
  10715. [](const Request &, Response &res, std::exception_ptr) {
  10716. res.status = StatusCode::InternalServerError_500;
  10717. res.set_content(std::string(1000, 'X'), "text/html");
  10718. });
  10719. auto port = svr.bind_to_any_port(HOST);
  10720. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10721. auto se = detail::scope_exit([&] {
  10722. svr.stop();
  10723. t.join();
  10724. ASSERT_FALSE(svr.is_running());
  10725. });
  10726. svr.wait_until_ready();
  10727. Client cli(HOST, port);
  10728. {
  10729. auto res = cli.Get("/sized");
  10730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10731. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10732. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10733. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  10734. }
  10735. {
  10736. auto res = cli.Get("/chunked");
  10737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10738. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  10739. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10740. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  10741. }
  10742. {
  10743. auto res = cli.Get("/throw");
  10744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10745. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  10746. EXPECT_EQ(std::string(1000, 'X'), res->body);
  10747. }
  10748. std::lock_guard<std::mutex> guard(released_mutex);
  10749. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  10750. }
  10751. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  10752. Server svr;
  10753. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  10754. return sink.write(&"abc"[offset], length);
  10755. };
  10756. svr.Get("/file-then-body", [](const Request &, Response &res) {
  10757. res.set_file_content("./www/dir/test.html");
  10758. res.set_content("body", "text/plain");
  10759. });
  10760. svr.Get("/body-then-file", [](const Request &, Response &res) {
  10761. res.set_content(std::string(100, 'B'), "text/plain");
  10762. res.set_file_content("./www/dir/test.html");
  10763. });
  10764. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  10765. res.set_content(std::string(100, 'B'), "text/plain");
  10766. res.set_content_provider(3, "text/plain", abc);
  10767. });
  10768. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  10769. res.set_content_provider(3, "text/plain", abc);
  10770. res.set_content(std::string(100, 'B'), "text/plain");
  10771. });
  10772. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  10773. res.set_content_provider(3, "text/plain", abc);
  10774. res.body = "direct";
  10775. });
  10776. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  10777. res.set_file_content("./www/dir/test.html");
  10778. res.body = "direct";
  10779. });
  10780. auto port = svr.bind_to_any_port(HOST);
  10781. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10782. auto se = detail::scope_exit([&] {
  10783. svr.stop();
  10784. t.join();
  10785. ASSERT_FALSE(svr.is_running());
  10786. });
  10787. svr.wait_until_ready();
  10788. Client cli(HOST, port);
  10789. auto expect_body = [&](const char *path, const std::string &body) {
  10790. // Uncompressed, so Content-Length can be compared with the body.
  10791. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  10792. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  10793. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10794. EXPECT_EQ(body, res->body) << path;
  10795. EXPECT_EQ(std::to_string(body.size()),
  10796. res->get_header_value("Content-Length"))
  10797. << path;
  10798. };
  10799. expect_body("/file-then-body", "body");
  10800. expect_body("/body-then-file", "test.html");
  10801. expect_body("/body-then-provider", "abc");
  10802. expect_body("/provider-then-body", std::string(100, 'B'));
  10803. expect_body("/provider-then-direct-body", "direct");
  10804. expect_body("/file-then-direct-body", "direct");
  10805. // Ranges are checked against the body, not the dropped provider.
  10806. {
  10807. auto res = cli.Get("/provider-then-direct-body",
  10808. Headers{{make_range_header({{1, 2}})}});
  10809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10810. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10811. EXPECT_EQ("ir", res->body);
  10812. }
  10813. {
  10814. auto res = cli.Get("/file-then-direct-body",
  10815. Headers{{make_range_header({{7, 8}})}});
  10816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10817. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  10818. }
  10819. }
  10820. // Forward declaration (see the base64_encode note).
  10821. namespace httplib {
  10822. namespace detail {
  10823. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  10824. const std::string &content_type,
  10825. EncodingType encoding);
  10826. } // namespace detail
  10827. } // namespace httplib
  10828. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  10829. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  10830. ASSERT_TRUE(mm->is_open());
  10831. Response res;
  10832. detail::set_file_content_provider(res, mm, "text/html",
  10833. detail::EncodingType::None);
  10834. std::string out;
  10835. DataSink sink;
  10836. sink.write = [&](const char *d, size_t l) {
  10837. out.append(d, l);
  10838. return true;
  10839. };
  10840. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  10841. EXPECT_EQ("test.html", out);
  10842. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  10843. EXPECT_EQ("test.html", out);
  10844. }
  10845. TEST(LongPollingTest, ClientCloseDetection) {
  10846. Server svr;
  10847. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10848. res.set_chunked_content_provider(
  10849. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10850. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10851. sink.os << "hello";
  10852. auto count = 10;
  10853. while (count > 0 && sink.is_writable()) {
  10854. this_thread::sleep_for(chrono::milliseconds(10));
  10855. count--;
  10856. }
  10857. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10858. return true;
  10859. });
  10860. });
  10861. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10862. auto se = detail::scope_exit([&] {
  10863. svr.stop();
  10864. listen_thread.join();
  10865. ASSERT_FALSE(svr.is_running());
  10866. });
  10867. svr.wait_until_ready();
  10868. Client cli("localhost", PORT);
  10869. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10870. EXPECT_EQ("hello", string(data, data_length));
  10871. return false; // close the socket immediately.
  10872. });
  10873. ASSERT_FALSE(res);
  10874. }
  10875. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10876. Server svr;
  10877. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10878. res.set_chunked_content_provider(
  10879. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10880. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10881. sink.os << "hello";
  10882. EXPECT_TRUE(sink.os.good());
  10883. // Wait for the client to close the connection
  10884. auto count = 10;
  10885. while (count > 0 && sink.is_writable()) {
  10886. this_thread::sleep_for(chrono::milliseconds(10));
  10887. count--;
  10888. }
  10889. // After client disconnect, write repeatedly until the socket
  10890. // write actually fails (small writes may be absorbed by the
  10891. // kernel buffer)
  10892. std::string chunk(1024, 'x');
  10893. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10894. sink.os << chunk;
  10895. }
  10896. EXPECT_TRUE(sink.os.fail());
  10897. return true;
  10898. });
  10899. });
  10900. auto port = svr.bind_to_any_port("localhost");
  10901. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10902. auto se = detail::scope_exit([&] {
  10903. svr.stop();
  10904. listen_thread.join();
  10905. ASSERT_FALSE(svr.is_running());
  10906. });
  10907. svr.wait_until_ready();
  10908. Client cli("localhost", port);
  10909. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10910. EXPECT_EQ("hello", string(data, data_length));
  10911. return false; // close the socket immediately.
  10912. });
  10913. ASSERT_FALSE(res);
  10914. }
  10915. TEST(GetWithParametersTest, GetWithParameters) {
  10916. Server svr;
  10917. svr.Get("/", [&](const Request &req, Response &) {
  10918. EXPECT_EQ("world", req.get_param_value("hello"));
  10919. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10920. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10921. });
  10922. svr.Get("/params", [&](const Request &req, Response &) {
  10923. EXPECT_EQ("world", req.get_param_value("hello"));
  10924. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10925. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10926. });
  10927. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10928. EXPECT_EQ("resource-id", req.matches[1]);
  10929. EXPECT_EQ("foo", req.get_param_value("param1"));
  10930. EXPECT_EQ("bar", req.get_param_value("param2"));
  10931. });
  10932. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10933. EXPECT_EQ("user-id", req.path_params.at("id"));
  10934. EXPECT_EQ("foo", req.get_param_value("param1"));
  10935. EXPECT_EQ("bar", req.get_param_value("param2"));
  10936. });
  10937. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10938. auto se = detail::scope_exit([&] {
  10939. svr.stop();
  10940. listen_thread.join();
  10941. ASSERT_FALSE(svr.is_running());
  10942. });
  10943. svr.wait_until_ready();
  10944. {
  10945. Client cli(HOST, PORT);
  10946. Params params;
  10947. params.emplace("hello", "world");
  10948. params.emplace("hello2", "world2");
  10949. params.emplace("hello3", "world3");
  10950. auto res = cli.Get("/", params, Headers{});
  10951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10952. EXPECT_EQ(StatusCode::OK_200, res->status);
  10953. }
  10954. {
  10955. Client cli(HOST, PORT);
  10956. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10958. EXPECT_EQ(StatusCode::OK_200, res->status);
  10959. }
  10960. {
  10961. Client cli(HOST, PORT);
  10962. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10964. EXPECT_EQ(StatusCode::OK_200, res->status);
  10965. }
  10966. {
  10967. Client cli(HOST, PORT);
  10968. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10970. EXPECT_EQ(StatusCode::OK_200, res->status);
  10971. }
  10972. }
  10973. TEST(GetWithParametersTest, GetWithParameters2) {
  10974. Server svr;
  10975. svr.Get("/", [&](const Request &req, Response &res) {
  10976. auto text = req.get_param_value("hello");
  10977. res.set_content(text, "text/plain");
  10978. });
  10979. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10980. auto se = detail::scope_exit([&] {
  10981. svr.stop();
  10982. listen_thread.join();
  10983. ASSERT_FALSE(svr.is_running());
  10984. });
  10985. svr.wait_until_ready();
  10986. Client cli("localhost", PORT);
  10987. Params params;
  10988. params.emplace("hello", "world");
  10989. std::string body;
  10990. auto res = cli.Get("/", params, Headers{},
  10991. [&](const char *data, size_t data_length) {
  10992. body.append(data, data_length);
  10993. return true;
  10994. });
  10995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10996. EXPECT_EQ(StatusCode::OK_200, res->status);
  10997. EXPECT_EQ("world", body);
  10998. }
  10999. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11000. Server svr;
  11001. svr.Get("/search", [&](const Request &req, Response &res) {
  11002. auto q = req.get_param_value("q");
  11003. res.set_content(q, "text/plain");
  11004. });
  11005. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11006. auto se = detail::scope_exit([&] {
  11007. svr.stop();
  11008. listen_thread.join();
  11009. ASSERT_FALSE(svr.is_running());
  11010. });
  11011. svr.wait_until_ready();
  11012. Client cli("localhost", PORT);
  11013. // Verify that Get(path, params) works without requiring Headers argument
  11014. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11016. EXPECT_EQ(StatusCode::OK_200, res->status);
  11017. EXPECT_EQ("cpp-httplib", res->body);
  11018. }
  11019. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11020. auto host = "httpbingo.org";
  11021. auto path = std::string{"/range/32"};
  11022. #ifdef CPPHTTPLIB_SSL_ENABLED
  11023. SSLClient cli(host);
  11024. #else
  11025. Client cli(host);
  11026. #endif
  11027. cli.set_default_headers({make_range_header({{1, 10}})});
  11028. cli.set_connection_timeout(5);
  11029. {
  11030. auto res = cli.Get(path);
  11031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11032. EXPECT_EQ("bcdefghijk", res->body);
  11033. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11034. }
  11035. {
  11036. auto res = cli.Get(path);
  11037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11038. EXPECT_EQ("bcdefghijk", res->body);
  11039. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11040. }
  11041. }
  11042. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11043. Server svr;
  11044. svr.set_default_headers({{"Hello", "World"}});
  11045. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11046. res.set_content("ok", "text/plain");
  11047. });
  11048. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11049. auto se = detail::scope_exit([&] {
  11050. svr.stop();
  11051. listen_thread.join();
  11052. ASSERT_FALSE(svr.is_running());
  11053. });
  11054. svr.wait_until_ready();
  11055. Client cli("localhost", PORT);
  11056. auto res = cli.Get("/");
  11057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11058. EXPECT_EQ(StatusCode::OK_200, res->status);
  11059. EXPECT_EQ("ok", res->body);
  11060. EXPECT_EQ("World", res->get_header_value("Hello"));
  11061. }
  11062. #ifdef CPPHTTPLIB_SSL_ENABLED
  11063. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11064. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11065. ASSERT_TRUE(svr.is_valid());
  11066. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11067. std::this_thread::sleep_for(std::chrono::seconds(2));
  11068. res.set_content("a", "text/plain");
  11069. });
  11070. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11071. res.set_content("b", "text/plain");
  11072. });
  11073. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11074. auto se = detail::scope_exit([&] {
  11075. svr.stop();
  11076. listen_thread.join();
  11077. ASSERT_FALSE(svr.is_running());
  11078. });
  11079. svr.wait_until_ready();
  11080. SSLClient cli("localhost", PORT);
  11081. cli.enable_server_certificate_verification(false);
  11082. cli.set_keep_alive(true);
  11083. cli.set_read_timeout(std::chrono::seconds(1));
  11084. auto resa = cli.Get("/a");
  11085. ASSERT_TRUE(!resa);
  11086. EXPECT_EQ(Error::Read, resa.error());
  11087. auto resb = cli.Get("/b");
  11088. ASSERT_TRUE(resb);
  11089. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11090. EXPECT_EQ("b", resb->body);
  11091. }
  11092. // Closing an idle keep-alive connection sends close_notify and returns. The
  11093. // server must not wait for the client's close_notify: an idle client never
  11094. // sends one, so the worker would be held until the read timeout expires, and
  11095. // stop() would wait for it.
  11096. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11097. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11098. ASSERT_TRUE(svr.is_valid());
  11099. svr.set_keep_alive_timeout(1);
  11100. svr.set_read_timeout(10, 0);
  11101. svr.Get("/", [](const Request &, Response &res) {
  11102. res.set_content("ok", "text/plain");
  11103. });
  11104. auto port = svr.bind_to_any_port(HOST);
  11105. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11106. auto se = detail::scope_exit([&] {
  11107. if (listen_thread.joinable()) {
  11108. svr.stop();
  11109. listen_thread.join();
  11110. }
  11111. });
  11112. svr.wait_until_ready();
  11113. SSLClient cli(HOST, port);
  11114. cli.enable_server_certificate_verification(false);
  11115. cli.set_keep_alive(true);
  11116. auto res = cli.Get("/");
  11117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11118. EXPECT_EQ(StatusCode::OK_200, res->status);
  11119. // Stay idle past the keep-alive timeout so the server closes the connection.
  11120. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11121. auto start = std::chrono::steady_clock::now();
  11122. svr.stop();
  11123. listen_thread.join();
  11124. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11125. std::chrono::steady_clock::now() - start)
  11126. .count();
  11127. EXPECT_LT(elapsed, 3000);
  11128. }
  11129. #endif
  11130. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11131. protected:
  11132. ServerTestWithAI_PASSIVE()
  11133. : cli_(HOST, PORT)
  11134. #ifdef CPPHTTPLIB_SSL_ENABLED
  11135. ,
  11136. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11137. #endif
  11138. {
  11139. #ifdef CPPHTTPLIB_SSL_ENABLED
  11140. cli_.enable_server_certificate_verification(false);
  11141. #endif
  11142. }
  11143. virtual void SetUp() {
  11144. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11145. res.set_content("Hello World!", "text/plain");
  11146. });
  11147. t_ = thread(
  11148. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11149. svr_.wait_until_ready();
  11150. }
  11151. virtual void TearDown() {
  11152. svr_.stop();
  11153. t_.join();
  11154. }
  11155. #ifdef CPPHTTPLIB_SSL_ENABLED
  11156. SSLClient cli_;
  11157. SSLServer svr_;
  11158. #else
  11159. Client cli_;
  11160. Server svr_;
  11161. #endif
  11162. thread t_;
  11163. };
  11164. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11165. auto res = cli_.Get("/hi");
  11166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11167. EXPECT_EQ(StatusCode::OK_200, res->status);
  11168. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11169. EXPECT_EQ("Hello World!", res->body);
  11170. }
  11171. class ServerUpDownTest : public ::testing::Test {
  11172. protected:
  11173. ServerUpDownTest() : cli_(HOST, PORT) {}
  11174. virtual void SetUp() {
  11175. t_ = thread([&]() {
  11176. svr_.bind_to_any_port(HOST);
  11177. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11178. ASSERT_TRUE(svr_.listen_after_bind());
  11179. });
  11180. svr_.wait_until_ready();
  11181. }
  11182. virtual void TearDown() {
  11183. svr_.stop();
  11184. t_.join();
  11185. }
  11186. Client cli_;
  11187. Server svr_;
  11188. thread t_;
  11189. };
  11190. TEST_F(ServerUpDownTest, QuickStartStop) {
  11191. // Should not crash, especially when run with
  11192. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11193. }
  11194. class PayloadMaxLengthTest : public ::testing::Test {
  11195. protected:
  11196. PayloadMaxLengthTest()
  11197. : cli_(HOST, PORT)
  11198. #ifdef CPPHTTPLIB_SSL_ENABLED
  11199. ,
  11200. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11201. #endif
  11202. {
  11203. #ifdef CPPHTTPLIB_SSL_ENABLED
  11204. cli_.enable_server_certificate_verification(false);
  11205. #endif
  11206. }
  11207. virtual void SetUp() {
  11208. svr_.set_payload_max_length(8);
  11209. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11210. res.set_content("test", "text/plain");
  11211. });
  11212. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11213. svr_.wait_until_ready();
  11214. }
  11215. virtual void TearDown() {
  11216. svr_.stop();
  11217. t_.join();
  11218. }
  11219. #ifdef CPPHTTPLIB_SSL_ENABLED
  11220. SSLClient cli_;
  11221. SSLServer svr_;
  11222. #else
  11223. Client cli_;
  11224. Server svr_;
  11225. #endif
  11226. thread t_;
  11227. };
  11228. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11229. auto res = cli_.Post("/test", "123456789", "text/plain");
  11230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11231. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11232. res = cli_.Post("/test", "12345678", "text/plain");
  11233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11234. EXPECT_EQ(StatusCode::OK_200, res->status);
  11235. }
  11236. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11237. // Test chunked encoding with payload exceeding the 8-byte limit
  11238. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11239. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11241. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11242. }
  11243. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11244. // Test chunked encoding with payload within the 8-byte limit
  11245. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11246. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11248. EXPECT_EQ(StatusCode::OK_200, res->status);
  11249. }
  11250. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11251. // Test using send_request to send chunked data exceeding payload limit
  11252. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11253. "Host: " +
  11254. std::string(HOST) + ":" + std::to_string(PORT) +
  11255. "\r\n"
  11256. "Transfer-Encoding: chunked\r\n"
  11257. "Connection: close\r\n"
  11258. "\r\n"
  11259. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11260. "0123456789\r\n"
  11261. "0\r\n" // End chunk
  11262. "\r\n";
  11263. std::string response;
  11264. bool result = send_request(1, chunked_request, &response);
  11265. if (!result) {
  11266. // If send_request fails, it might be because the server closed the
  11267. // connection due to payload limit enforcement, which is acceptable
  11268. SUCCEED()
  11269. << "Server rejected oversized chunked request (connection closed)";
  11270. } else {
  11271. // If we got a response, check if it's an error response or connection was
  11272. // closed early Short response length indicates connection was closed due to
  11273. // payload limit
  11274. if (response.length() <= 10) {
  11275. SUCCEED() << "Server closed connection for oversized chunked request";
  11276. } else {
  11277. // Check for error status codes
  11278. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11279. response.find("Payload Too Large") != std::string::npos ||
  11280. response.find("400") != std::string::npos);
  11281. }
  11282. }
  11283. }
  11284. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11285. // Test request without Content-Length header exceeding payload limit
  11286. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11287. "Host: " +
  11288. std::string(HOST) + ":" +
  11289. std::to_string(PORT) +
  11290. "\r\n"
  11291. "Connection: close\r\n"
  11292. "\r\n";
  11293. // Add payload exceeding the 8-byte limit
  11294. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11295. request_without_content_length += large_payload;
  11296. std::string response;
  11297. bool result = send_request(1, request_without_content_length, &response);
  11298. if (!result) {
  11299. // If send_request fails, server likely closed connection due to payload
  11300. // limit
  11301. SUCCEED() << "Server rejected oversized request without Content-Length "
  11302. "(connection closed)";
  11303. } else {
  11304. // Check if server responded with error or closed connection early
  11305. if (response.length() <= 10) {
  11306. SUCCEED() << "Server closed connection for oversized request without "
  11307. "Content-Length";
  11308. } else {
  11309. // Check for error status codes
  11310. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11311. response.find("Payload Too Large") != std::string::npos ||
  11312. response.find("400") != std::string::npos);
  11313. }
  11314. }
  11315. }
  11316. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11317. // Test request without Content-Length header within payload limit
  11318. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11319. "Host: " +
  11320. std::string(HOST) + ":" +
  11321. std::to_string(PORT) +
  11322. "\r\n"
  11323. "Connection: close\r\n"
  11324. "\r\n";
  11325. // Add payload within the 8-byte limit
  11326. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11327. request_without_content_length += small_payload;
  11328. std::string response;
  11329. bool result = send_request(1, request_without_content_length, &response);
  11330. // For requests without Content-Length, the server may have different behavior
  11331. // The key is that it should not reject due to payload limit for small
  11332. // payloads
  11333. if (result) {
  11334. // Check for any HTTP response (success or error, but not connection closed)
  11335. if (response.length() > 10) {
  11336. SUCCEED()
  11337. << "Server processed request without Content-Length within limit";
  11338. } else {
  11339. // Short response might indicate connection closed, which is acceptable
  11340. SUCCEED() << "Server closed connection for request without "
  11341. "Content-Length (acceptable behavior)";
  11342. }
  11343. } else {
  11344. // Connection failure might be due to protocol requirements
  11345. SUCCEED() << "Connection issue with request without Content-Length "
  11346. "(environment-specific)";
  11347. }
  11348. }
  11349. class LargePayloadMaxLengthTest : public ::testing::Test {
  11350. protected:
  11351. LargePayloadMaxLengthTest()
  11352. : cli_(HOST, PORT)
  11353. #ifdef CPPHTTPLIB_SSL_ENABLED
  11354. ,
  11355. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11356. #endif
  11357. {
  11358. #ifdef CPPHTTPLIB_SSL_ENABLED
  11359. cli_.enable_server_certificate_verification(false);
  11360. #endif
  11361. }
  11362. virtual void SetUp() {
  11363. // Set 10MB payload limit
  11364. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11365. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11366. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11367. res.set_content("Large payload test", "text/plain");
  11368. });
  11369. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11370. svr_.wait_until_ready();
  11371. }
  11372. virtual void TearDown() {
  11373. svr_.stop();
  11374. t_.join();
  11375. }
  11376. #ifdef CPPHTTPLIB_SSL_ENABLED
  11377. SSLClient cli_;
  11378. SSLServer svr_;
  11379. #else
  11380. Client cli_;
  11381. Server svr_;
  11382. #endif
  11383. thread t_;
  11384. };
  11385. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11386. // Test chunked encoding with payload within 10MB limit
  11387. std::string medium_payload(5 * 1024 * 1024,
  11388. 'A'); // 5MB payload, within 10MB limit
  11389. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11391. EXPECT_EQ(StatusCode::OK_200, res->status);
  11392. }
  11393. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11394. // Test chunked encoding with payload exceeding 10MB limit
  11395. std::string large_payload(12 * 1024 * 1024,
  11396. 'B'); // 12MB payload, exceeds 10MB limit
  11397. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11398. // Server may either return 413 or close the connection
  11399. if (res) {
  11400. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11401. } else {
  11402. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11403. }
  11404. }
  11405. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11406. // Test request without Content-Length header within 10MB limit
  11407. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11408. "Host: " +
  11409. std::string(HOST) + ":" +
  11410. std::to_string(PORT) +
  11411. "\r\n"
  11412. "Connection: close\r\n"
  11413. "\r\n";
  11414. // Add 1MB payload (within 10MB limit)
  11415. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11416. request_without_content_length += medium_payload;
  11417. std::string response;
  11418. bool result = send_request(5, request_without_content_length, &response);
  11419. if (result) {
  11420. // Should get a proper HTTP response for payloads within limit
  11421. if (response.length() > 10) {
  11422. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11423. "10MB limit";
  11424. } else {
  11425. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11426. "Content-Length)";
  11427. }
  11428. } else {
  11429. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11430. }
  11431. }
  11432. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11433. // Test request without Content-Length header exceeding 10MB limit
  11434. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11435. "Host: " +
  11436. std::string(HOST) + ":" +
  11437. std::to_string(PORT) +
  11438. "\r\n"
  11439. "Connection: close\r\n"
  11440. "\r\n";
  11441. // Add 12MB payload (exceeds 10MB limit)
  11442. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11443. request_without_content_length += large_payload;
  11444. std::string response;
  11445. bool result = send_request(10, request_without_content_length, &response);
  11446. if (!result) {
  11447. // Server should close connection due to payload limit
  11448. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11449. "(connection closed)";
  11450. } else {
  11451. // Check for error response
  11452. if (response.length() <= 10) {
  11453. SUCCEED()
  11454. << "Server closed connection for 12MB request exceeding 10MB limit";
  11455. } else {
  11456. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11457. response.find("Payload Too Large") != std::string::npos ||
  11458. response.find("400") != std::string::npos);
  11459. }
  11460. }
  11461. }
  11462. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  11463. Server svr;
  11464. svr.Get("/", [](const Request &, Response &res) {
  11465. // Claims far more than it sends, then drops the connection.
  11466. res.set_content_provider(size_t(1) << 41, "text/plain",
  11467. [](size_t, size_t, DataSink &sink) {
  11468. sink.write("abc", 3);
  11469. return false;
  11470. });
  11471. });
  11472. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11473. auto se = detail::scope_exit([&] {
  11474. svr.stop();
  11475. thread.join();
  11476. ASSERT_FALSE(svr.is_running());
  11477. });
  11478. svr.wait_until_ready();
  11479. Client cli(HOST, PORT);
  11480. cli.set_payload_max_length(0);
  11481. EXPECT_FALSE(cli.Get("/"));
  11482. }
  11483. // Accepts one connection on 127.0.0.1:port, reads the request head and sends
  11484. // back the given bytes, which httplib::Server could not be made to send.
  11485. static void serve_raw_once(int port, const std::string &response) {
  11486. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11487. default_socket_options(srv);
  11488. sockaddr_in addr{};
  11489. addr.sin_family = AF_INET;
  11490. addr.sin_port = htons(static_cast<uint16_t>(port));
  11491. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11492. int opt = 1;
  11493. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11494. #ifdef _WIN32
  11495. reinterpret_cast<const char *>(&opt),
  11496. #else
  11497. &opt,
  11498. #endif
  11499. sizeof(opt));
  11500. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11501. ::listen(srv, 1);
  11502. auto cli = ::accept(srv, nullptr, nullptr);
  11503. if (cli != INVALID_SOCKET) {
  11504. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  11505. std::string head;
  11506. char c;
  11507. while (head.find("\r\n\r\n") == std::string::npos &&
  11508. ::recv(cli, &c, 1, 0) == 1) {
  11509. head += c;
  11510. }
  11511. ::send(cli, response.data(), static_cast<int>(response.size()), 0);
  11512. detail::close_socket(cli);
  11513. }
  11514. detail::close_socket(srv);
  11515. }
  11516. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  11517. const char *responses[] = {
  11518. "HTTP/1.1 103 Early Hints\r\n"
  11519. "Link: </style.css>; rel=preload\r\n"
  11520. "\r\n"
  11521. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  11522. "HTTP/1.1 100 Continue\r\n"
  11523. "X-Note: interim\r\n"
  11524. "\r\n"
  11525. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  11526. };
  11527. for (auto response : responses) {
  11528. std::thread t([&]() { serve_raw_once(PORT, response); });
  11529. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11530. Client cli("127.0.0.1", PORT);
  11531. auto res = cli.Get("/");
  11532. t.join();
  11533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11534. EXPECT_EQ(StatusCode::OK_200, res->status);
  11535. EXPECT_EQ("ok", res->body);
  11536. }
  11537. }
  11538. #ifdef CPPHTTPLIB_SSL_ENABLED
  11539. TEST(ProxyConnectTest, OnlyARefusalIsPassedOn) {
  11540. // Anything but 200 or a refusal would read as the origin's own response.
  11541. {
  11542. std::thread t([] {
  11543. serve_raw_once(PORT, "HTTP/1.1 201 Created\r\n"
  11544. "Set-Cookie: session=from-proxy\r\n"
  11545. "Content-Length: 0\r\n\r\n");
  11546. });
  11547. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11548. SSLClient cli("example.com", 443);
  11549. cli.set_proxy("127.0.0.1", PORT);
  11550. auto res = cli.Get("/");
  11551. t.join();
  11552. EXPECT_FALSE(res);
  11553. EXPECT_EQ(Error::ProxyConnection, res.error());
  11554. }
  11555. {
  11556. std::thread t([] {
  11557. serve_raw_once(PORT, "HTTP/1.1 407 Proxy Authentication Required\r\n"
  11558. "Content-Length: 0\r\n\r\n");
  11559. });
  11560. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11561. SSLClient cli("example.com", 443);
  11562. cli.set_proxy("127.0.0.1", PORT);
  11563. auto res = cli.Get("/");
  11564. t.join();
  11565. ASSERT_TRUE(res);
  11566. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  11567. }
  11568. }
  11569. #endif
  11570. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  11571. std::atomic<bool> closed_by_client{false};
  11572. auto server_thread = std::thread([&] {
  11573. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11574. default_socket_options(srv);
  11575. sockaddr_in addr{};
  11576. addr.sin_family = AF_INET;
  11577. addr.sin_port = htons(static_cast<uint16_t>(PORT));
  11578. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11579. int opt = 1;
  11580. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11581. #ifdef _WIN32
  11582. reinterpret_cast<const char *>(&opt),
  11583. #else
  11584. &opt,
  11585. #endif
  11586. sizeof(opt));
  11587. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11588. ::listen(srv, 1);
  11589. auto cli = ::accept(srv, nullptr, nullptr);
  11590. if (cli != INVALID_SOCKET) {
  11591. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  11592. // Answer the head without asking for the body, and keep the connection.
  11593. std::string head;
  11594. char c;
  11595. while (head.find("\r\n\r\n") == std::string::npos &&
  11596. ::recv(cli, &c, 1, 0) == 1) {
  11597. head += c;
  11598. }
  11599. std::string res =
  11600. "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n";
  11601. ::send(cli, res.data(), static_cast<int>(res.size()), 0);
  11602. // Bytes here would be read as the body the first request declared.
  11603. char buf[256];
  11604. closed_by_client = ::recv(cli, buf, sizeof(buf), 0) == 0;
  11605. detail::close_socket(cli);
  11606. }
  11607. detail::close_socket(srv);
  11608. });
  11609. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11610. Client cli("127.0.0.1", PORT);
  11611. cli.set_keep_alive(true);
  11612. cli.set_read_timeout(1, 0);
  11613. // Long enough for the client to send Expect: 100-continue.
  11614. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  11615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11616. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  11617. cli.Get("/second");
  11618. server_thread.join();
  11619. EXPECT_TRUE(closed_by_client);
  11620. }
  11621. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11622. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11623. // path.
  11624. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11625. Server svr;
  11626. const size_t LIMIT = 64 * 1024; // 64KB
  11627. svr.set_payload_max_length(LIMIT);
  11628. size_t total = 0;
  11629. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11630. const ContentReader &content_reader) {
  11631. content_reader([&](const char * /*data*/, size_t len) {
  11632. total += len;
  11633. return true;
  11634. });
  11635. res.status = 200;
  11636. res.set_content("stream_ok", "text/plain");
  11637. });
  11638. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11639. auto se = detail::scope_exit([&] {
  11640. svr.stop();
  11641. thread.join();
  11642. ASSERT_FALSE(svr.is_running());
  11643. });
  11644. svr.wait_until_ready();
  11645. // Prepare 256KB raw data and gzip-compress it
  11646. std::string raw(256 * 1024, 'A');
  11647. std::string gz;
  11648. {
  11649. z_stream zs{};
  11650. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11651. Z_DEFAULT_STRATEGY);
  11652. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11653. zs.avail_in = static_cast<uInt>(raw.size());
  11654. char outbuf[4096];
  11655. int ret;
  11656. do {
  11657. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11658. zs.avail_out = sizeof(outbuf);
  11659. ret = deflate(&zs, Z_FINISH);
  11660. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11661. } while (ret != Z_STREAM_END);
  11662. deflateEnd(&zs);
  11663. }
  11664. Client cli(HOST, PORT);
  11665. cli.set_connection_timeout(std::chrono::seconds(5));
  11666. Headers headers = {{"Content-Encoding", "gzip"}};
  11667. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11668. "application/octet-stream");
  11669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11670. // Server must reject oversized decompressed payloads with 413.
  11671. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11672. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11673. EXPECT_LE(total, LIMIT);
  11674. }
  11675. #ifndef CPPHTTPLIB_SSL_ENABLED
  11676. // For a request with neither Content-Length nor Transfer-Encoding, the
  11677. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11678. // compressed wire bytes straight to the ContentReader without ever routing
  11679. // them through the decompressor, so payload_max_length_ only bounded the
  11680. // compressed size on the wire, not the decompressed size.
  11681. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11682. Server svr;
  11683. const size_t LIMIT = 64 * 1024; // 64KB
  11684. svr.set_payload_max_length(LIMIT);
  11685. size_t total = 0;
  11686. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11687. const ContentReader &content_reader) {
  11688. content_reader([&](const char * /*data*/, size_t len) {
  11689. total += len;
  11690. return true;
  11691. });
  11692. res.status = 200;
  11693. res.set_content("stream_ok", "text/plain");
  11694. });
  11695. auto port = svr.bind_to_any_port(HOST);
  11696. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11697. auto se = detail::scope_exit([&] {
  11698. svr.stop();
  11699. thread.join();
  11700. ASSERT_FALSE(svr.is_running());
  11701. });
  11702. svr.wait_until_ready();
  11703. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11704. // StreamingGzipDecompression test above.
  11705. std::string raw(256 * 1024, 'A');
  11706. std::string gz;
  11707. {
  11708. httplib::detail::gzip_compressor compressor;
  11709. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11710. [&](const char *chunk, size_t len) {
  11711. gz.append(chunk, len);
  11712. return true;
  11713. });
  11714. ASSERT_TRUE(result);
  11715. }
  11716. // Send the gzip body over raw TCP with neither Content-Length nor
  11717. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11718. // kicks in.
  11719. std::string req = "POST /stream HTTP/1.1\r\n"
  11720. "Host: " +
  11721. std::string(HOST) + ":" + std::to_string(port) +
  11722. "\r\n"
  11723. "Content-Encoding: gzip\r\n"
  11724. "Connection: close\r\n"
  11725. "\r\n" +
  11726. gz;
  11727. std::string response;
  11728. ASSERT_TRUE(send_request(5, req, &response, port));
  11729. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11730. EXPECT_LE(total, LIMIT);
  11731. }
  11732. #endif
  11733. #endif
  11734. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11735. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11736. // the payload must be passed through untouched instead of being rejected.
  11737. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11738. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11739. Server svr;
  11740. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11741. res.set_content(body, "image/jpeg");
  11742. res.set_header("Content-Encoding", "UTF-8");
  11743. });
  11744. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  11745. res.set_content(body, "image/jpeg");
  11746. res.set_header("Content-Encoding", "identity");
  11747. });
  11748. svr.Post("/echo", [](const Request &req, Response &res) {
  11749. res.set_content(req.body, "image/jpeg");
  11750. });
  11751. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11752. auto se = detail::scope_exit([&] {
  11753. svr.stop();
  11754. t.join();
  11755. ASSERT_FALSE(svr.is_running());
  11756. });
  11757. svr.wait_until_ready();
  11758. Client cli(HOST, PORT);
  11759. {
  11760. auto res = cli.Get("/image");
  11761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11762. EXPECT_EQ(StatusCode::OK_200, res->status);
  11763. EXPECT_EQ(body, res->body);
  11764. }
  11765. {
  11766. auto res = cli.Get("/identity");
  11767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11768. EXPECT_EQ(StatusCode::OK_200, res->status);
  11769. EXPECT_EQ(body, res->body);
  11770. }
  11771. {
  11772. // The same applies to a request body reaching the server.
  11773. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11774. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11776. EXPECT_EQ(StatusCode::OK_200, res->status);
  11777. EXPECT_EQ(body, res->body);
  11778. }
  11779. }
  11780. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11781. // gzip-encoded response even when the build has no zlib support.
  11782. static const char GZIPPED_HELLO_WORLD[] = {
  11783. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11784. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11785. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11786. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11787. // A content coding is a whole token, not something the field value merely
  11788. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11789. // as "fibre" look like Brotli, and turned a multi-coding value like
  11790. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11791. // it was never meant to see.
  11792. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11793. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11794. Server svr;
  11795. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11796. res.set_content(body, "image/jpeg");
  11797. res.set_header("Content-Encoding", "fibre");
  11798. });
  11799. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11800. res.set_content(body, "image/jpeg");
  11801. res.set_header("Content-Encoding", "gzip, br");
  11802. });
  11803. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11804. res.set_content(body, "image/jpeg");
  11805. res.set_header("Content-Encoding", "x-zstd-ish");
  11806. });
  11807. auto port = svr.bind_to_any_port(HOST);
  11808. thread t = thread([&]() { svr.listen_after_bind(); });
  11809. auto se = detail::scope_exit([&] {
  11810. svr.stop();
  11811. t.join();
  11812. ASSERT_FALSE(svr.is_running());
  11813. });
  11814. svr.wait_until_ready();
  11815. Client cli(HOST, port);
  11816. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11817. auto res = cli.Get(path);
  11818. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11819. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11820. // Not a coding we recognize, so the payload comes back untouched
  11821. EXPECT_EQ(body, res->body) << path;
  11822. }
  11823. }
  11824. // A content coding cpp-httplib recognizes but was not built with must be
  11825. // reported as such. Handing the still-compressed payload back to the caller
  11826. // would silently corrupt it.
  11827. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11828. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11829. Server svr;
  11830. // "image/jpeg" keeps the server from applying a content coding of its own,
  11831. // so the hand-crafted Content-Encoding below survives.
  11832. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11833. res.set_content(gzipped, "image/jpeg");
  11834. res.set_header("Content-Encoding", "gzip");
  11835. });
  11836. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11837. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11838. res.set_content(gzipped, "image/jpeg");
  11839. res.set_header("Content-Encoding", "GZIP");
  11840. });
  11841. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11842. auto se = detail::scope_exit([&] {
  11843. svr.stop();
  11844. t.join();
  11845. ASSERT_FALSE(svr.is_running());
  11846. });
  11847. svr.wait_until_ready();
  11848. Client cli(HOST, PORT);
  11849. {
  11850. auto res = cli.Get("/gzipped");
  11851. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11853. EXPECT_EQ("Hello World!", res->body);
  11854. #else
  11855. ASSERT_FALSE(res);
  11856. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11857. #endif
  11858. }
  11859. {
  11860. // open_stream() must behave the same way.
  11861. auto handle = cli.open_stream("GET", "/gzipped");
  11862. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11863. ASSERT_TRUE(handle.is_valid());
  11864. std::string received;
  11865. char buf[256];
  11866. ssize_t n;
  11867. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11868. received.append(buf, static_cast<size_t>(n));
  11869. }
  11870. EXPECT_EQ("Hello World!", received);
  11871. #else
  11872. EXPECT_FALSE(handle.is_valid());
  11873. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11874. #endif
  11875. }
  11876. {
  11877. // A differently-cased coding must not be mistaken for an unknown one, or
  11878. // the body would be handed back still compressed.
  11879. auto res = cli.Get("/gzipped-uppercase");
  11880. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11882. EXPECT_EQ("Hello World!", res->body);
  11883. #else
  11884. ASSERT_FALSE(res);
  11885. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11886. #endif
  11887. }
  11888. }
  11889. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11890. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11891. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11892. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11893. // body a second time and appending a second Content-Encoding field line, so
  11894. // clients that decode one coding per listed value handed back raw gzip bytes.
  11895. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11896. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11897. Server svr;
  11898. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11899. // keeps the server from applying a coding of its own.
  11900. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11901. res.set_content(gzipped, "text/plain");
  11902. res.set_header("Content-Encoding", "gzip");
  11903. });
  11904. auto port = svr.bind_to_any_port(HOST);
  11905. thread t = thread([&]() { svr.listen_after_bind(); });
  11906. auto se = detail::scope_exit([&] {
  11907. svr.stop();
  11908. t.join();
  11909. ASSERT_FALSE(svr.is_running());
  11910. });
  11911. svr.wait_until_ready();
  11912. Client cli(HOST, port);
  11913. Headers headers = {{"Accept-Encoding", "gzip"}};
  11914. auto res = cli.Get("/pre-gzipped", headers);
  11915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11916. EXPECT_EQ(StatusCode::OK_200, res->status);
  11917. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11918. EXPECT_EQ("Hello World!", res->body);
  11919. }
  11920. // A chunked provider settles its coding where the headers are written and
  11921. // reuses it at write time. Both ends of that have to hold: a handler's own
  11922. // Content-Encoding suppresses the coding, and a response without one is still
  11923. // compressed as it always was.
  11924. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11925. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11926. const std::string plain = "Hello World! Hello World! Hello World!";
  11927. Server svr;
  11928. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11929. res.set_header("Content-Encoding", "gzip");
  11930. res.set_chunked_content_provider(
  11931. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11932. sink.write(gzipped.data(), gzipped.size());
  11933. sink.done();
  11934. return true;
  11935. });
  11936. });
  11937. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11938. res.set_chunked_content_provider(
  11939. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11940. sink.write(plain.data(), plain.size());
  11941. sink.done();
  11942. return true;
  11943. });
  11944. });
  11945. auto port = svr.bind_to_any_port(HOST);
  11946. thread t = thread([&]() { svr.listen_after_bind(); });
  11947. auto se = detail::scope_exit([&] {
  11948. svr.stop();
  11949. t.join();
  11950. ASSERT_FALSE(svr.is_running());
  11951. });
  11952. svr.wait_until_ready();
  11953. Client cli(HOST, port);
  11954. Headers headers = {{"Accept-Encoding", "gzip"}};
  11955. {
  11956. auto res = cli.Get("/pre-gzipped", headers);
  11957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11958. EXPECT_EQ(StatusCode::OK_200, res->status);
  11959. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11960. EXPECT_EQ("Hello World!", res->body);
  11961. }
  11962. {
  11963. auto res = cli.Get("/negotiated", headers);
  11964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11965. EXPECT_EQ(StatusCode::OK_200, res->status);
  11966. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11967. EXPECT_EQ(plain, res->body);
  11968. }
  11969. }
  11970. #endif
  11971. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11972. // the same message as the comma-joined one, so both have to be read the same
  11973. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11974. // single gzip coding, and a body the sender says was encoded twice was handed
  11975. // back after one pass, still compressed but presented as decoded.
  11976. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11977. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11978. Server svr;
  11979. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11980. res.set_content(body, "image/jpeg");
  11981. res.headers.emplace("Content-Encoding", "gzip");
  11982. res.headers.emplace("Content-Encoding", "gzip");
  11983. });
  11984. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11985. res.set_content(body, "image/jpeg");
  11986. res.set_header("Content-Encoding", "gzip, gzip");
  11987. });
  11988. auto port = svr.bind_to_any_port(HOST);
  11989. thread t = thread([&]() { svr.listen_after_bind(); });
  11990. auto se = detail::scope_exit([&] {
  11991. svr.stop();
  11992. t.join();
  11993. ASSERT_FALSE(svr.is_running());
  11994. });
  11995. svr.wait_until_ready();
  11996. Client cli(HOST, port);
  11997. // Two codings is not something cpp-httplib decodes, so both representations
  11998. // take the pass-through path rather than one of them being gunzipped once.
  11999. for (const char *path : {"/split", "/joined"}) {
  12000. auto res = cli.Get(path);
  12001. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12002. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12003. EXPECT_EQ(body, res->body) << path;
  12004. }
  12005. }
  12006. // Regression test for DoS vulnerability: a malicious server sending a response
  12007. // without Content-Length header must not cause unbounded memory consumption on
  12008. // the client side. The client should stop reading after a reasonable limit,
  12009. // similar to the server-side set_payload_max_length protection.
  12010. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12011. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12012. #ifndef _WIN32
  12013. signal(SIGPIPE, SIG_IGN);
  12014. #endif
  12015. auto server_thread = std::thread([] {
  12016. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12017. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12018. default_socket_options(srv);
  12019. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12020. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12021. sockaddr_in addr{};
  12022. addr.sin_family = AF_INET;
  12023. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12024. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12025. int opt = 1;
  12026. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12027. #ifdef _WIN32
  12028. reinterpret_cast<const char *>(&opt),
  12029. #else
  12030. &opt,
  12031. #endif
  12032. sizeof(opt));
  12033. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12034. ::listen(srv, 1);
  12035. sockaddr_in cli_addr{};
  12036. socklen_t cli_len = sizeof(cli_addr);
  12037. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12038. if (cli != INVALID_SOCKET) {
  12039. char buf[4096];
  12040. ::recv(cli, buf, sizeof(buf), 0);
  12041. // Malicious response: no Content-Length, no chunked encoding
  12042. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12043. "Connection: close\r\n"
  12044. "\r\n";
  12045. ::send(cli,
  12046. #ifdef _WIN32
  12047. static_cast<const char *>(response_header.c_str()),
  12048. static_cast<int>(response_header.size()),
  12049. #else
  12050. response_header.c_str(), response_header.size(),
  12051. #endif
  12052. 0);
  12053. // Send 10MB of data
  12054. std::string chunk(64 * 1024, 'A');
  12055. size_t total_sent = 0;
  12056. while (total_sent < MALICIOUS_DATA_SIZE) {
  12057. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12058. auto sent = ::send(cli,
  12059. #ifdef _WIN32
  12060. static_cast<const char *>(chunk.c_str()),
  12061. static_cast<int>(to_send),
  12062. #else
  12063. chunk.c_str(), to_send,
  12064. #endif
  12065. 0);
  12066. if (sent <= 0) break;
  12067. total_sent += static_cast<size_t>(sent);
  12068. }
  12069. detail::close_socket(cli);
  12070. }
  12071. detail::close_socket(srv);
  12072. });
  12073. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12074. size_t total_read = 0;
  12075. {
  12076. Client cli("127.0.0.1", PORT + 2);
  12077. cli.set_read_timeout(5, 0);
  12078. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12079. auto stream = cli.open_stream("GET", "/malicious");
  12080. ASSERT_TRUE(stream.is_valid());
  12081. char buffer[64 * 1024];
  12082. ssize_t n;
  12083. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12084. total_read += static_cast<size_t>(n);
  12085. }
  12086. } // StreamHandle and Client destroyed here, closing the socket
  12087. server_thread.join();
  12088. // With set_payload_max_length, the client must stop reading before consuming
  12089. // all 10MB. The read loop should be cut off at or near the configured limit.
  12090. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12091. << "Client read " << total_read << " bytes, exceeding the configured "
  12092. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12093. }
  12094. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12095. // the entire response body without truncation.
  12096. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12097. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12098. #ifndef _WIN32
  12099. signal(SIGPIPE, SIG_IGN);
  12100. #endif
  12101. auto server_thread = std::thread([] {
  12102. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12103. default_socket_options(srv);
  12104. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12105. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12106. sockaddr_in addr{};
  12107. addr.sin_family = AF_INET;
  12108. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12109. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12110. int opt = 1;
  12111. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12112. #ifdef _WIN32
  12113. reinterpret_cast<const char *>(&opt),
  12114. #else
  12115. &opt,
  12116. #endif
  12117. sizeof(opt));
  12118. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12119. ::listen(srv, 1);
  12120. sockaddr_in cli_addr{};
  12121. socklen_t cli_len = sizeof(cli_addr);
  12122. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12123. if (cli != INVALID_SOCKET) {
  12124. char buf[4096];
  12125. ::recv(cli, buf, sizeof(buf), 0);
  12126. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12127. "Connection: close\r\n"
  12128. "\r\n";
  12129. ::send(cli,
  12130. #ifdef _WIN32
  12131. static_cast<const char *>(response_header.c_str()),
  12132. static_cast<int>(response_header.size()),
  12133. #else
  12134. response_header.c_str(), response_header.size(),
  12135. #endif
  12136. 0);
  12137. std::string chunk(64 * 1024, 'A');
  12138. size_t total_sent = 0;
  12139. while (total_sent < DATA_SIZE) {
  12140. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12141. auto sent = ::send(cli,
  12142. #ifdef _WIN32
  12143. static_cast<const char *>(chunk.c_str()),
  12144. static_cast<int>(to_send),
  12145. #else
  12146. chunk.c_str(), to_send,
  12147. #endif
  12148. 0);
  12149. if (sent <= 0) break;
  12150. total_sent += static_cast<size_t>(sent);
  12151. }
  12152. #ifdef _WIN32
  12153. ::shutdown(cli, SD_SEND);
  12154. #else
  12155. ::shutdown(cli, SHUT_WR);
  12156. #endif
  12157. // Drain until the client closes its end, ensuring all data is delivered
  12158. char drain[1024];
  12159. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12160. detail::close_socket(cli);
  12161. }
  12162. detail::close_socket(srv);
  12163. });
  12164. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12165. size_t total_read = 0;
  12166. {
  12167. Client cli("127.0.0.1", PORT + 2);
  12168. cli.set_read_timeout(5, 0);
  12169. cli.set_payload_max_length(0); // 0 means no limit
  12170. auto stream = cli.open_stream("GET", "/data");
  12171. ASSERT_TRUE(stream.is_valid());
  12172. char buffer[64 * 1024];
  12173. ssize_t n;
  12174. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12175. total_read += static_cast<size_t>(n);
  12176. }
  12177. }
  12178. server_thread.join();
  12179. EXPECT_EQ(total_read, DATA_SIZE)
  12180. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12181. << " bytes without truncation, but only read " << total_read << " bytes.";
  12182. }
  12183. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12184. // enormous Content-Length must not cause the client to pre-allocate a huge
  12185. // response body buffer. The reservation is capped at payload_max_length_, and
  12186. // the read itself fails when the body exceeds the limit.
  12187. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12188. #ifndef _WIN32
  12189. signal(SIGPIPE, SIG_IGN);
  12190. #endif
  12191. auto server_thread = std::thread([] {
  12192. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12193. default_socket_options(srv);
  12194. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12195. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12196. sockaddr_in addr{};
  12197. addr.sin_family = AF_INET;
  12198. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12199. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12200. int opt = 1;
  12201. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12202. #ifdef _WIN32
  12203. reinterpret_cast<const char *>(&opt),
  12204. #else
  12205. &opt,
  12206. #endif
  12207. sizeof(opt));
  12208. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12209. ::listen(srv, 1);
  12210. sockaddr_in cli_addr{};
  12211. socklen_t cli_len = sizeof(cli_addr);
  12212. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12213. if (cli != INVALID_SOCKET) {
  12214. char buf[4096];
  12215. ::recv(cli, buf, sizeof(buf), 0);
  12216. // Malicious response: claim a 20GB body but send only a tiny payload.
  12217. std::string response = "HTTP/1.1 200 OK\r\n"
  12218. "Content-Length: 20000000000\r\n"
  12219. "\r\n"
  12220. "abc";
  12221. ::send(cli,
  12222. #ifdef _WIN32
  12223. static_cast<const char *>(response.c_str()),
  12224. static_cast<int>(response.size()),
  12225. #else
  12226. response.c_str(), response.size(),
  12227. #endif
  12228. 0);
  12229. detail::close_socket(cli);
  12230. }
  12231. detail::close_socket(srv);
  12232. });
  12233. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12234. {
  12235. Client cli("127.0.0.1", PORT + 2);
  12236. cli.set_read_timeout(5, 0);
  12237. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12238. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12239. // (server claims more bytes than payload_max_length permits), but it must
  12240. // not exhaust memory before getting there.
  12241. auto res = cli.Get("/malicious");
  12242. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12243. }
  12244. server_thread.join();
  12245. }
  12246. // Verify that content_receiver bypasses the default payload_max_length,
  12247. // allowing streaming downloads larger than 100MB without requiring an explicit
  12248. // set_payload_max_length call.
  12249. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12250. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12251. #ifndef _WIN32
  12252. signal(SIGPIPE, SIG_IGN);
  12253. #endif
  12254. auto server_thread = std::thread([] {
  12255. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12256. default_socket_options(srv);
  12257. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12258. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12259. sockaddr_in addr{};
  12260. addr.sin_family = AF_INET;
  12261. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12262. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12263. int opt = 1;
  12264. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12265. #ifdef _WIN32
  12266. reinterpret_cast<const char *>(&opt),
  12267. #else
  12268. &opt,
  12269. #endif
  12270. sizeof(opt));
  12271. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12272. ::listen(srv, 1);
  12273. sockaddr_in cli_addr{};
  12274. socklen_t cli_len = sizeof(cli_addr);
  12275. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12276. if (cli != INVALID_SOCKET) {
  12277. char buf[4096];
  12278. ::recv(cli, buf, sizeof(buf), 0);
  12279. // Response with Content-Length larger than default 100MB limit
  12280. auto content_length = std::to_string(DATA_SIZE);
  12281. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12282. "Content-Length: " +
  12283. content_length +
  12284. "\r\n"
  12285. "Connection: close\r\n"
  12286. "\r\n";
  12287. ::send(cli,
  12288. #ifdef _WIN32
  12289. static_cast<const char *>(response_header.c_str()),
  12290. static_cast<int>(response_header.size()),
  12291. #else
  12292. response_header.c_str(), response_header.size(),
  12293. #endif
  12294. 0);
  12295. std::string chunk(64 * 1024, 'A');
  12296. size_t total_sent = 0;
  12297. while (total_sent < DATA_SIZE) {
  12298. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12299. auto sent = ::send(cli,
  12300. #ifdef _WIN32
  12301. static_cast<const char *>(chunk.c_str()),
  12302. static_cast<int>(to_send),
  12303. #else
  12304. chunk.c_str(), to_send,
  12305. #endif
  12306. 0);
  12307. if (sent <= 0) break;
  12308. total_sent += static_cast<size_t>(sent);
  12309. }
  12310. detail::close_socket(cli);
  12311. }
  12312. detail::close_socket(srv);
  12313. });
  12314. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12315. size_t total_received = 0;
  12316. {
  12317. Client cli("127.0.0.1", PORT + 2);
  12318. cli.set_read_timeout(10, 0);
  12319. // Do NOT call set_payload_max_length — use the default 100MB limit
  12320. auto res =
  12321. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12322. total_received += data_length;
  12323. return true;
  12324. });
  12325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12326. EXPECT_EQ(StatusCode::OK_200, res->status);
  12327. }
  12328. server_thread.join();
  12329. EXPECT_EQ(total_received, DATA_SIZE)
  12330. << "With content_receiver, the client should read all " << DATA_SIZE
  12331. << " bytes despite the default 100MB payload_max_length, but only read "
  12332. << total_received << " bytes.";
  12333. }
  12334. // Verify that an explicit set_payload_max_length smaller than the response is
  12335. // enforced even when a content_receiver is used.
  12336. TEST(ClientVulnerabilityTest,
  12337. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12338. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12339. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12340. #ifndef _WIN32
  12341. signal(SIGPIPE, SIG_IGN);
  12342. #endif
  12343. auto server_thread = std::thread([] {
  12344. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12345. default_socket_options(srv);
  12346. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12347. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12348. sockaddr_in addr{};
  12349. addr.sin_family = AF_INET;
  12350. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12351. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12352. int opt = 1;
  12353. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12354. #ifdef _WIN32
  12355. reinterpret_cast<const char *>(&opt),
  12356. #else
  12357. &opt,
  12358. #endif
  12359. sizeof(opt));
  12360. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12361. ::listen(srv, 1);
  12362. sockaddr_in cli_addr{};
  12363. socklen_t cli_len = sizeof(cli_addr);
  12364. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12365. if (cli != INVALID_SOCKET) {
  12366. char buf[4096];
  12367. ::recv(cli, buf, sizeof(buf), 0);
  12368. auto content_length = std::to_string(DATA_SIZE);
  12369. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12370. "Content-Length: " +
  12371. content_length +
  12372. "\r\n"
  12373. "Connection: close\r\n"
  12374. "\r\n";
  12375. ::send(cli,
  12376. #ifdef _WIN32
  12377. static_cast<const char *>(response_header.c_str()),
  12378. static_cast<int>(response_header.size()),
  12379. #else
  12380. response_header.c_str(), response_header.size(),
  12381. #endif
  12382. 0);
  12383. std::string chunk(64 * 1024, 'A');
  12384. size_t total_sent = 0;
  12385. while (total_sent < DATA_SIZE) {
  12386. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12387. auto sent = ::send(cli,
  12388. #ifdef _WIN32
  12389. static_cast<const char *>(chunk.c_str()),
  12390. static_cast<int>(to_send),
  12391. #else
  12392. chunk.c_str(), to_send,
  12393. #endif
  12394. 0);
  12395. if (sent <= 0) break;
  12396. total_sent += static_cast<size_t>(sent);
  12397. }
  12398. detail::close_socket(cli);
  12399. }
  12400. detail::close_socket(srv);
  12401. });
  12402. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12403. size_t total_received = 0;
  12404. {
  12405. Client cli("127.0.0.1", PORT + 2);
  12406. cli.set_read_timeout(10, 0);
  12407. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12408. auto res =
  12409. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12410. total_received += data_length;
  12411. return true;
  12412. });
  12413. // Should fail because 200MB exceeds the explicit 150MB limit
  12414. EXPECT_FALSE(res);
  12415. }
  12416. server_thread.join();
  12417. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12418. << "Client with content_receiver should respect the explicit "
  12419. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12420. << total_received << " bytes.";
  12421. }
  12422. // Verify that an explicit set_payload_max_length larger than the response
  12423. // allows the content_receiver to read all data successfully.
  12424. TEST(ClientVulnerabilityTest,
  12425. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12426. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12427. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12428. #ifndef _WIN32
  12429. signal(SIGPIPE, SIG_IGN);
  12430. #endif
  12431. auto server_thread = std::thread([] {
  12432. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12433. default_socket_options(srv);
  12434. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12435. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12436. sockaddr_in addr{};
  12437. addr.sin_family = AF_INET;
  12438. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12439. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12440. int opt = 1;
  12441. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12442. #ifdef _WIN32
  12443. reinterpret_cast<const char *>(&opt),
  12444. #else
  12445. &opt,
  12446. #endif
  12447. sizeof(opt));
  12448. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12449. ::listen(srv, 1);
  12450. sockaddr_in cli_addr{};
  12451. socklen_t cli_len = sizeof(cli_addr);
  12452. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12453. if (cli != INVALID_SOCKET) {
  12454. char buf[4096];
  12455. ::recv(cli, buf, sizeof(buf), 0);
  12456. auto content_length = std::to_string(DATA_SIZE);
  12457. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12458. "Content-Length: " +
  12459. content_length +
  12460. "\r\n"
  12461. "Connection: close\r\n"
  12462. "\r\n";
  12463. ::send(cli,
  12464. #ifdef _WIN32
  12465. static_cast<const char *>(response_header.c_str()),
  12466. static_cast<int>(response_header.size()),
  12467. #else
  12468. response_header.c_str(), response_header.size(),
  12469. #endif
  12470. 0);
  12471. std::string chunk(64 * 1024, 'A');
  12472. size_t total_sent = 0;
  12473. while (total_sent < DATA_SIZE) {
  12474. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12475. auto sent = ::send(cli,
  12476. #ifdef _WIN32
  12477. static_cast<const char *>(chunk.c_str()),
  12478. static_cast<int>(to_send),
  12479. #else
  12480. chunk.c_str(), to_send,
  12481. #endif
  12482. 0);
  12483. if (sent <= 0) break;
  12484. total_sent += static_cast<size_t>(sent);
  12485. }
  12486. #ifdef _WIN32
  12487. ::shutdown(cli, SD_SEND);
  12488. #else
  12489. ::shutdown(cli, SHUT_WR);
  12490. #endif
  12491. char drain[1024];
  12492. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12493. detail::close_socket(cli);
  12494. }
  12495. detail::close_socket(srv);
  12496. });
  12497. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12498. size_t total_received = 0;
  12499. {
  12500. Client cli("127.0.0.1", PORT + 2);
  12501. cli.set_read_timeout(10, 0);
  12502. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12503. auto res =
  12504. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12505. total_received += data_length;
  12506. return true;
  12507. });
  12508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12509. EXPECT_EQ(StatusCode::OK_200, res->status);
  12510. }
  12511. server_thread.join();
  12512. EXPECT_EQ(total_received, DATA_SIZE)
  12513. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12514. << " bytes (larger than " << DATA_SIZE
  12515. << " bytes response), content_receiver should read all data, but only "
  12516. "read "
  12517. << total_received << " bytes.";
  12518. }
  12519. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12520. // Regression test for "zip bomb" attack on the client side: a malicious server
  12521. // sends a small gzip-compressed response that decompresses to a huge payload.
  12522. // The client must enforce payload_max_length on the decompressed size.
  12523. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12524. constexpr size_t DECOMPRESSED_SIZE =
  12525. 10 * 1024 * 1024; // 10MB after decompression
  12526. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12527. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12528. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12529. std::string compressed;
  12530. {
  12531. httplib::detail::gzip_compressor compressor;
  12532. bool ok =
  12533. compressor.compress(uncompressed.data(), uncompressed.size(),
  12534. /*last=*/true, [&](const char *buf, size_t len) {
  12535. compressed.append(buf, len);
  12536. return true;
  12537. });
  12538. ASSERT_TRUE(ok);
  12539. }
  12540. // Sanity: compressed data should be much smaller than the decompressed size
  12541. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12542. #ifndef _WIN32
  12543. signal(SIGPIPE, SIG_IGN);
  12544. #endif
  12545. // Set up the listening socket in the main thread so the server is guaranteed
  12546. // to be ready before the client connects (eliminates race condition).
  12547. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12548. default_socket_options(srv);
  12549. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12550. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12551. sockaddr_in addr{};
  12552. addr.sin_family = AF_INET;
  12553. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12554. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12555. int opt = 1;
  12556. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12557. #ifdef _WIN32
  12558. reinterpret_cast<const char *>(&opt),
  12559. #else
  12560. &opt,
  12561. #endif
  12562. sizeof(opt));
  12563. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12564. ASSERT_EQ(0, ::listen(srv, 1));
  12565. auto server_thread = std::thread([&compressed, srv] {
  12566. sockaddr_in cli_addr{};
  12567. socklen_t cli_len = sizeof(cli_addr);
  12568. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12569. if (cli != INVALID_SOCKET) {
  12570. // Read the full HTTP request (until \r\n\r\n)
  12571. char buf[4096];
  12572. size_t total = 0;
  12573. while (total < sizeof(buf)) {
  12574. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12575. if (n <= 0) break;
  12576. total += static_cast<size_t>(n);
  12577. // Check for end of headers
  12578. if (total >= 4) {
  12579. std::string req(buf, total);
  12580. if (req.find("\r\n\r\n") != std::string::npos) break;
  12581. }
  12582. }
  12583. // Malicious response: gzip-compressed body, no Content-Length
  12584. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12585. "Content-Encoding: gzip\r\n"
  12586. "Connection: close\r\n"
  12587. "\r\n";
  12588. ::send(cli,
  12589. #ifdef _WIN32
  12590. static_cast<const char *>(response_header.c_str()),
  12591. static_cast<int>(response_header.size()),
  12592. #else
  12593. response_header.c_str(), response_header.size(),
  12594. #endif
  12595. 0);
  12596. // Send the compressed payload (small on the wire, huge when decompressed)
  12597. size_t total_sent = 0;
  12598. while (total_sent < compressed.size()) {
  12599. auto to_send = std::min(compressed.size() - total_sent,
  12600. static_cast<size_t>(64 * 1024));
  12601. auto sent =
  12602. ::send(cli,
  12603. #ifdef _WIN32
  12604. static_cast<const char *>(compressed.c_str() + total_sent),
  12605. static_cast<int>(to_send),
  12606. #else
  12607. compressed.c_str() + total_sent, to_send,
  12608. #endif
  12609. 0);
  12610. if (sent <= 0) break;
  12611. total_sent += static_cast<size_t>(sent);
  12612. }
  12613. detail::close_socket(cli);
  12614. }
  12615. });
  12616. auto se = detail::scope_exit([&] {
  12617. detail::close_socket(srv);
  12618. server_thread.join();
  12619. });
  12620. size_t total_decompressed = 0;
  12621. {
  12622. Client cli("127.0.0.1", PORT + 3);
  12623. cli.set_read_timeout(5, 0);
  12624. cli.set_decompress(true);
  12625. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12626. auto stream = cli.open_stream("GET", "/zipbomb");
  12627. ASSERT_TRUE(stream.is_valid());
  12628. char buffer[64 * 1024];
  12629. ssize_t n;
  12630. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12631. total_decompressed += static_cast<size_t>(n);
  12632. }
  12633. }
  12634. // The decompressed size must be capped by payload_max_length. Without
  12635. // protection, the client would decompress the full 10MB from a tiny
  12636. // compressed payload, enabling a zip bomb DoS attack.
  12637. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12638. << "Client decompressed " << total_decompressed
  12639. << " bytes from a gzip response. The decompressed size should be "
  12640. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12641. }
  12642. #endif
  12643. TEST(HostAndPortPropertiesTest, NoSSL) {
  12644. httplib::Client cli("www.google.com", 1234);
  12645. ASSERT_EQ("www.google.com", cli.host());
  12646. ASSERT_EQ(1234, cli.port());
  12647. }
  12648. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12649. httplib::Client cli("www.google.com:1234");
  12650. ASSERT_EQ("www.google.com", cli.host());
  12651. ASSERT_EQ(1234, cli.port());
  12652. }
  12653. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12654. // Port number that overflows int — should not crash, client becomes invalid
  12655. httplib::Client cli("http://www.google.com:99999999999999999999");
  12656. ASSERT_FALSE(cli.is_valid());
  12657. }
  12658. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12659. // Port 99999 exceeds valid range (1-65535) — should not crash
  12660. httplib::Client cli("http://www.google.com:99999");
  12661. ASSERT_FALSE(cli.is_valid());
  12662. auto res = cli.Get("/");
  12663. EXPECT_FALSE(res);
  12664. EXPECT_EQ(Error::Connection, res.error());
  12665. }
  12666. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12667. httplib::Client cli("http://www.google.com:80abc");
  12668. ASSERT_FALSE(cli.is_valid());
  12669. }
  12670. #ifdef CPPHTTPLIB_SSL_ENABLED
  12671. TEST(HostAndPortPropertiesTest, SSL) {
  12672. httplib::SSLClient cli("www.google.com");
  12673. ASSERT_EQ("www.google.com", cli.host());
  12674. ASSERT_EQ(443, cli.port());
  12675. }
  12676. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12677. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12678. std::string cert;
  12679. read_file(CA_CERT_FILE, cert);
  12680. httplib::SSLClient httplib_client("www.google.com");
  12681. // Load CA store first time
  12682. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12683. // Load CA store second time (update)
  12684. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12685. // Verify client is still valid and can make connections
  12686. httplib_client.enable_server_certificate_verification(true);
  12687. auto res = httplib_client.Get("/");
  12688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12689. // Google may return 200 or 301 depending on various factors
  12690. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12691. res->status == StatusCode::MovedPermanently_301);
  12692. }
  12693. TEST(SSLClientTest, ServerNameIndication_Online) {
  12694. auto host = "httpbingo.org";
  12695. auto path = std::string{"/get"};
  12696. SSLClient cli(host, 443);
  12697. auto res = cli.Get(path);
  12698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12699. ASSERT_EQ(StatusCode::OK_200, res->status);
  12700. }
  12701. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12702. // Use a site that will cause SSL verification failure due to self-signed cert
  12703. SSLClient cli("self-signed.badssl.com", 443);
  12704. cli.enable_server_certificate_verification(true);
  12705. auto res = cli.Get("/");
  12706. ASSERT_TRUE(!res);
  12707. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12708. // Verify backend error is captured for SSLServerVerification
  12709. // This occurs when certificate verification fails
  12710. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12711. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12712. EXPECT_NE(0UL, res.ssl_backend_error());
  12713. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12714. // For OpenSSL, ssl_error is 0 for verification errors
  12715. EXPECT_EQ(0, res.ssl_error());
  12716. #if !defined(_WIN32) || \
  12717. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12718. // On non-Windows or when Windows Schannel is disabled, the error comes
  12719. // from OpenSSL's verification
  12720. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12721. res.ssl_backend_error());
  12722. #endif
  12723. #endif
  12724. }
  12725. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12726. // Use a site where hostname doesn't match the certificate
  12727. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12728. SSLClient cli("wrong.host.badssl.com", 443);
  12729. cli.enable_server_certificate_verification(true);
  12730. cli.enable_server_hostname_verification(true);
  12731. auto res = cli.Get("/");
  12732. ASSERT_TRUE(!res);
  12733. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12734. // Verify backend error is captured for hostname verification failure
  12735. EXPECT_NE(0UL, res.ssl_backend_error());
  12736. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12737. // For OpenSSL, ssl_error is 0 for verification errors
  12738. EXPECT_EQ(0, res.ssl_error());
  12739. #if !defined(_WIN32) || \
  12740. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12741. // On non-Windows or when Windows Schannel is disabled, the error comes
  12742. // from OpenSSL's hostname verification
  12743. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12744. res.ssl_backend_error());
  12745. #endif
  12746. #endif
  12747. }
  12748. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12749. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12750. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12751. SSLClient cli("www.google.com", 443);
  12752. cli.enable_server_certificate_verification(true);
  12753. auto res = cli.Get("/");
  12754. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12755. }
  12756. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12757. SSLClient cli("www.google.com", 443);
  12758. cli.enable_server_certificate_verification(true);
  12759. cli.enable_windows_certificate_verification(false);
  12760. auto res = cli.Get("/");
  12761. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12762. }
  12763. // The server sends an intermediate cross-signed by a root Windows trusts,
  12764. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12765. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12766. SSLClient cli("accounts.spotify.com", 443);
  12767. auto res = cli.Get("/");
  12768. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12769. << " ssl_backend_error=" << res.ssl_backend_error();
  12770. }
  12771. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12772. // policy status, which no backend reports for a self-signed certificate.
  12773. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12774. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12775. ASSERT_TRUE(svr.is_valid());
  12776. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12777. auto se = detail::scope_exit([&] {
  12778. svr.stop();
  12779. t.join();
  12780. ASSERT_FALSE(svr.is_running());
  12781. });
  12782. svr.wait_until_ready();
  12783. SSLClient cli("127.0.0.1", PORT);
  12784. cli.set_connection_timeout(30);
  12785. auto res = cli.Get("/");
  12786. ASSERT_FALSE(res);
  12787. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12788. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12789. }
  12790. #endif
  12791. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12792. Client cli("https://google.com");
  12793. auto res = cli.Get("/");
  12794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12795. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12796. }
  12797. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12798. SSLClient cli("google.com");
  12799. cli.set_ca_cert_path(CA_CERT_FILE);
  12800. auto res = cli.Get("/");
  12801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12802. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12803. }
  12804. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12805. SSLClient cli("google.com");
  12806. cli.enable_server_certificate_verification(true);
  12807. cli.set_ca_cert_path("hello");
  12808. auto res = cli.Get("/");
  12809. ASSERT_TRUE(!res);
  12810. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12811. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12812. // should be set
  12813. EXPECT_EQ(0, res.ssl_error());
  12814. // Verify backend error is captured for SSLLoadingCerts
  12815. // This error occurs when loading CA certificates fails
  12816. EXPECT_NE(0UL, res.ssl_backend_error());
  12817. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12818. // OpenSSL specific error codes:
  12819. // > openssl errstr 0x80000002
  12820. // error:80000002:system library::No such file or directory
  12821. // > openssl errstr 0xA000126
  12822. // error:0A000126:SSL routines::unexpected eof while reading
  12823. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12824. res.ssl_backend_error() == 0xA000126);
  12825. #endif
  12826. }
  12827. TEST(SSLClientTest, ServerCertificateVerification4) {
  12828. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12829. ASSERT_TRUE(svr.is_valid());
  12830. svr.Get("/test", [&](const Request &, Response &res) {
  12831. res.set_content("test", "text/plain");
  12832. svr.stop();
  12833. ASSERT_TRUE(true);
  12834. });
  12835. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12836. auto se = detail::scope_exit([&] {
  12837. t.join();
  12838. ASSERT_FALSE(svr.is_running());
  12839. });
  12840. svr.wait_until_ready();
  12841. SSLClient cli("127.0.0.1", PORT);
  12842. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12843. cli.enable_server_certificate_verification(true);
  12844. cli.set_connection_timeout(30);
  12845. auto res = cli.Get("/test");
  12846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12847. ASSERT_EQ(StatusCode::OK_200, res->status);
  12848. }
  12849. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12850. std::string cert;
  12851. read_file(CA_CERT_FILE, cert);
  12852. SSLClient cli("google.com");
  12853. cli.load_ca_cert_store(cert.data(), cert.size());
  12854. const auto res = cli.Get("/");
  12855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12856. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12857. }
  12858. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12859. // clang-format off
  12860. static constexpr char cert[] =
  12861. "GlobalSign Root CA\n"
  12862. "==================\n"
  12863. "-----BEGIN CERTIFICATE-----\n"
  12864. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12865. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12866. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12867. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12868. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12869. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12870. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12871. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12872. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12873. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12874. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12875. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12876. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12877. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12878. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12879. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12880. "-----END CERTIFICATE-----\n";
  12881. // clang-format on
  12882. SSLClient cli("google.com");
  12883. cli.load_ca_cert_store(cert, sizeof(cert));
  12884. const auto res = cli.Get("/");
  12885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12886. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12887. }
  12888. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12889. SSLClient cli("www.youtube.com");
  12890. cli.set_ca_cert_path(CA_CERT_FILE);
  12891. cli.enable_server_certificate_verification(true);
  12892. cli.set_follow_location(true);
  12893. auto res = cli.Get("/");
  12894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12895. ASSERT_EQ(StatusCode::OK_200, res->status);
  12896. }
  12897. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12898. SSLClient cli("wWw.YouTube.Com");
  12899. cli.set_ca_cert_path(CA_CERT_FILE);
  12900. cli.enable_server_certificate_verification(true);
  12901. cli.enable_server_hostname_verification(true);
  12902. cli.set_follow_location(true);
  12903. auto res = cli.Get("/");
  12904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12905. ASSERT_EQ(StatusCode::OK_200, res->status);
  12906. }
  12907. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12908. SSLClient cli("gOoGlE.COm");
  12909. cli.enable_server_certificate_verification(true);
  12910. cli.enable_server_hostname_verification(true);
  12911. cli.set_follow_location(true);
  12912. auto res = cli.Get("/");
  12913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12914. ASSERT_EQ(StatusCode::OK_200, res->status);
  12915. }
  12916. TEST(SSLClientTest, Issue2004_Online) {
  12917. Client client("https://google.com");
  12918. client.set_follow_location(true);
  12919. auto res = client.Get("/");
  12920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12921. ASSERT_EQ(StatusCode::OK_200, res->status);
  12922. auto body = res->body;
  12923. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12924. }
  12925. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12926. // Create SSLClient with invalid cert/key to make is_valid() return false
  12927. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12928. "nonexistent_key.pem");
  12929. // is_valid() should be false due to cert loading failure
  12930. ASSERT_FALSE(cli.is_valid());
  12931. auto res = cli.Get("/");
  12932. ASSERT_FALSE(res);
  12933. EXPECT_EQ(Error::SSLConnection, res.error());
  12934. }
  12935. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12936. // Test for Issue #2251: SSL error not properly reported when client cert
  12937. // and key paths are swapped or mismatched
  12938. // This simulates the scenario where user accidentally swaps the cert and key
  12939. // files
  12940. // Using client cert file as private key and vice versa (completely wrong)
  12941. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12942. // Should fail validation due to cert/key mismatch
  12943. ASSERT_FALSE(cli.is_valid());
  12944. // Attempt to make a request should fail with proper error
  12945. auto res = cli.Get("/");
  12946. ASSERT_FALSE(res);
  12947. EXPECT_EQ(Error::SSLConnection, res.error());
  12948. // SSL error should be recorded in the Result object (this is the key fix for
  12949. // Issue #2251)
  12950. auto backend_error = res.ssl_backend_error();
  12951. EXPECT_NE(0u, backend_error);
  12952. }
  12953. // Tests cert/key mismatch detection at the TLS context level
  12954. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12955. // Test that using mismatched cert/key causes connection failure.
  12956. // We verify this at the SSLClient level rather than through internal
  12957. // TLS API functions.
  12958. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12959. cli.enable_server_certificate_verification(false);
  12960. cli.set_connection_timeout(2);
  12961. // The mismatch should cause a connection or handshake error
  12962. auto res = cli.Get("/test");
  12963. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12964. // Either way, the request should fail
  12965. EXPECT_FALSE(res);
  12966. }
  12967. #endif
  12968. #if 0
  12969. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12970. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12971. ASSERT_TRUE(cli != nullptr);
  12972. cli->set_address_family(AF_INET6);
  12973. cli->set_interface("en0");
  12974. auto res = cli->Get("/get");
  12975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12976. ASSERT_EQ(StatusCode::OK_200, res->status);
  12977. }
  12978. #endif
  12979. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12980. #ifdef CPPHTTPLIB_SSL_ENABLED
  12981. void ClientCertPresent(
  12982. const std::string &client_cert_file,
  12983. const std::string &client_private_key_file,
  12984. const std::string &client_encrypted_private_key_pass = std::string()) {
  12985. using namespace httplib::tls;
  12986. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12987. CLIENT_CA_CERT_DIR);
  12988. ASSERT_TRUE(svr.is_valid());
  12989. svr.Get("/test", [&](const Request &req, Response &res) {
  12990. res.set_content("test", "text/plain");
  12991. auto cert = req.peer_cert();
  12992. ASSERT_TRUE(static_cast<bool>(cert));
  12993. std::string common_name = cert.subject_cn();
  12994. EXPECT_EQ("Common Name", common_name);
  12995. });
  12996. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12997. auto se = detail::scope_exit([&] {
  12998. svr.stop();
  12999. t.join();
  13000. ASSERT_FALSE(svr.is_running());
  13001. });
  13002. svr.wait_until_ready();
  13003. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  13004. client_encrypted_private_key_pass);
  13005. cli.enable_server_certificate_verification(false);
  13006. cli.set_connection_timeout(30);
  13007. auto res = cli.Get("/test");
  13008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13009. ASSERT_EQ(StatusCode::OK_200, res->status);
  13010. }
  13011. TEST(SSLClientServerTest, ClientCertPresent) {
  13012. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13013. }
  13014. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13015. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13016. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13017. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13018. }
  13019. // PEM memory-based constructor tests (works with all TLS backends)
  13020. void PemMemoryClientCertPresent(
  13021. const std::string &client_cert_file,
  13022. const std::string &client_private_key_file,
  13023. const std::string &client_encrypted_private_key_pass = std::string()) {
  13024. // Read PEM files into memory
  13025. std::string server_cert_pem, server_key_pem;
  13026. std::string client_ca_pem;
  13027. std::string client_cert_pem, client_key_pem;
  13028. read_file(SERVER_CERT_FILE, server_cert_pem);
  13029. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13030. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13031. read_file(client_cert_file, client_cert_pem);
  13032. read_file(client_private_key_file, client_key_pem);
  13033. // Create server with PEM memory
  13034. SSLServer::PemMemory server_pem = {
  13035. server_cert_pem.c_str(),
  13036. server_cert_pem.size(),
  13037. server_key_pem.c_str(),
  13038. server_key_pem.size(),
  13039. client_ca_pem.c_str(),
  13040. client_ca_pem.size(),
  13041. nullptr // no password for server key
  13042. };
  13043. SSLServer svr(server_pem);
  13044. ASSERT_TRUE(svr.is_valid());
  13045. svr.Get("/test", [&](const Request &, Response &res) {
  13046. res.set_content("test", "text/plain");
  13047. });
  13048. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13049. auto se = detail::scope_exit([&] {
  13050. svr.stop();
  13051. t.join();
  13052. ASSERT_FALSE(svr.is_running());
  13053. });
  13054. svr.wait_until_ready();
  13055. // Create client with PEM memory
  13056. const char *password = client_encrypted_private_key_pass.empty()
  13057. ? nullptr
  13058. : client_encrypted_private_key_pass.c_str();
  13059. SSLClient::PemMemory client_pem = {
  13060. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  13061. client_key_pem.size(), password};
  13062. SSLClient cli(HOST, PORT, client_pem);
  13063. cli.enable_server_certificate_verification(false);
  13064. cli.set_connection_timeout(30);
  13065. auto res = cli.Get("/test");
  13066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13067. ASSERT_EQ(StatusCode::OK_200, res->status);
  13068. }
  13069. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13070. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13071. }
  13072. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13073. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13074. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13075. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13076. }
  13077. TEST(SSLClientServerTest, ClientCertMissing) {
  13078. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13079. CLIENT_CA_CERT_DIR);
  13080. ASSERT_TRUE(svr.is_valid());
  13081. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  13082. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13083. auto se = detail::scope_exit([&] {
  13084. svr.stop();
  13085. t.join();
  13086. ASSERT_FALSE(svr.is_running());
  13087. });
  13088. svr.wait_until_ready();
  13089. SSLClient cli(HOST, PORT);
  13090. cli.set_connection_timeout(30);
  13091. // cert.pem does not match HOST. Skip the hostname check, which runs before
  13092. // the chain check on Windows, so the result does not depend on the order.
  13093. cli.enable_server_hostname_verification(false);
  13094. auto res = cli.Get("/test");
  13095. ASSERT_TRUE(!res);
  13096. // When client cert is missing and server requires it, connection fails
  13097. // Error type depends on backend implementation
  13098. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13099. res.error() == Error::SSLConnection);
  13100. // Verify backend error is captured
  13101. // Note: This test may have different error codes depending on the exact
  13102. // verification failure
  13103. EXPECT_NE(0UL, res.ssl_backend_error());
  13104. }
  13105. TEST(SSLClientServerTest, TrustDirOptional) {
  13106. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13107. ASSERT_TRUE(svr.is_valid());
  13108. svr.Get("/test", [&](const Request &, Response &res) {
  13109. res.set_content("test", "text/plain");
  13110. });
  13111. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13112. auto se = detail::scope_exit([&] {
  13113. svr.stop();
  13114. t.join();
  13115. ASSERT_FALSE(svr.is_running());
  13116. });
  13117. svr.wait_until_ready();
  13118. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13119. cli.enable_server_certificate_verification(false);
  13120. cli.set_connection_timeout(30);
  13121. auto res = cli.Get("/test");
  13122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13123. ASSERT_EQ(StatusCode::OK_200, res->status);
  13124. }
  13125. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13126. class NoListenSSLServer : public SSLServer {
  13127. public:
  13128. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13129. const char *client_ca_cert_file_path,
  13130. const char *client_ca_cert_dir_path = nullptr)
  13131. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13132. client_ca_cert_dir_path),
  13133. stop_(false) {}
  13134. std::atomic_bool stop_;
  13135. private:
  13136. bool process_and_close_socket(socket_t /*sock*/) override {
  13137. // Don't create SSL context
  13138. while (!stop_.load()) {
  13139. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13140. }
  13141. return true;
  13142. }
  13143. };
  13144. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13145. CLIENT_CA_CERT_FILE);
  13146. ASSERT_TRUE(svr.is_valid());
  13147. svr.Get("/test", [&](const Request &, Response &res) {
  13148. res.set_content("test", "text/plain");
  13149. });
  13150. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13151. auto se = detail::scope_exit([&] {
  13152. svr.stop_ = true;
  13153. svr.stop();
  13154. t.join();
  13155. ASSERT_FALSE(svr.is_running());
  13156. });
  13157. svr.wait_until_ready();
  13158. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13159. cli.enable_server_certificate_verification(false);
  13160. cli.set_connection_timeout(1);
  13161. auto res = cli.Get("/test");
  13162. ASSERT_TRUE(!res);
  13163. EXPECT_EQ(Error::SSLConnection, res.error());
  13164. // Timeout results in WantRead error code (maps to backend-specific value)
  13165. EXPECT_NE(0, res.ssl_error());
  13166. }
  13167. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13168. // Test SSLServer with client certificate verification using the standard
  13169. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13170. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13171. CLIENT_CA_CERT_DIR);
  13172. ASSERT_TRUE(svr.is_valid());
  13173. svr.Get("/test", [&](const Request &req, Response &res) {
  13174. res.set_content("test", "text/plain");
  13175. auto cert = req.peer_cert();
  13176. ASSERT_TRUE(static_cast<bool>(cert));
  13177. auto common_name = cert.subject_cn();
  13178. EXPECT_EQ("Common Name", common_name);
  13179. });
  13180. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13181. auto se = detail::scope_exit([&] {
  13182. svr.stop();
  13183. t.join();
  13184. ASSERT_FALSE(svr.is_running());
  13185. });
  13186. svr.wait_until_ready();
  13187. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13188. cli.enable_server_certificate_verification(false);
  13189. cli.set_connection_timeout(30);
  13190. auto res = cli.Get("/test");
  13191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13192. ASSERT_EQ(StatusCode::OK_200, res->status);
  13193. }
  13194. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13195. // Verifies that wildcard matching and exact matching work consistently
  13196. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13197. using namespace httplib::tls;
  13198. // We need a running server to test against
  13199. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13200. ASSERT_TRUE(svr.is_valid());
  13201. svr.Get("/test", [](const Request &, Response &res) {
  13202. res.set_content("ok", "text/plain");
  13203. });
  13204. thread t([&]() { svr.listen(HOST, PORT); });
  13205. auto se = detail::scope_exit([&] {
  13206. svr.stop();
  13207. t.join();
  13208. });
  13209. svr.wait_until_ready();
  13210. bool verify_callback_called = false;
  13211. bool verify_result_wrong = false;
  13212. SSLClient cli(HOST, PORT);
  13213. cli.enable_server_certificate_verification(true);
  13214. cli.set_ca_cert_path(CA_CERT_FILE);
  13215. cli.set_connection_timeout(5);
  13216. // Note: Test certificate has CN="Common Name", not "localhost"
  13217. bool verify_result_cn = false;
  13218. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13219. verify_callback_called = true;
  13220. if (!ctx.cert) return false;
  13221. // Test 1: "Common Name" should match (our test server cert CN)
  13222. verify_result_cn = ctx.check_hostname("Common Name");
  13223. // Test 2: wrong hostname should not match
  13224. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13225. return true; // Accept for the purpose of this test
  13226. });
  13227. auto res = cli.Get("/test");
  13228. // The request may succeed or fail depending on cert configuration
  13229. // but the callback should have been called
  13230. ASSERT_TRUE(verify_callback_called)
  13231. << "Verify callback should have been called";
  13232. // CN="Common Name" should match our test certificate
  13233. //
  13234. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13235. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13236. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13237. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13238. // <openssl/base.h>, which is included transitively when
  13239. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13240. #if defined(OPENSSL_IS_BORINGSSL)
  13241. EXPECT_FALSE(verify_result_cn)
  13242. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13243. #else
  13244. EXPECT_TRUE(verify_result_cn)
  13245. << "verify_hostname should match 'Common Name' (certificate CN)";
  13246. #endif
  13247. // Wrong hostname should not match
  13248. EXPECT_FALSE(verify_result_wrong)
  13249. << "verify_hostname should not match 'wronghost.example.com'";
  13250. }
  13251. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13252. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13253. // X509_check_ip behavior and must hold for every backend.
  13254. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13255. using namespace httplib::tls;
  13256. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13257. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13258. ASSERT_TRUE(svr.is_valid());
  13259. svr.Get("/test", [](const Request &, Response &res) {
  13260. res.set_content("ok", "text/plain");
  13261. });
  13262. thread t([&]() { svr.listen(HOST, PORT); });
  13263. auto se = detail::scope_exit([&] {
  13264. svr.stop();
  13265. t.join();
  13266. });
  13267. svr.wait_until_ready();
  13268. bool verify_callback_called = false;
  13269. bool ip_matched_via_cn = true;
  13270. SSLClient cli(HOST, PORT);
  13271. cli.enable_server_certificate_verification(true);
  13272. cli.set_ca_cert_path(CA_CERT_FILE);
  13273. cli.set_connection_timeout(5);
  13274. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13275. verify_callback_called = true;
  13276. if (!ctx.cert) return false;
  13277. // The IP appears only in the CN, so it must NOT be accepted.
  13278. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13279. return true; // Accept for the purpose of this test
  13280. });
  13281. cli.Get("/test");
  13282. ASSERT_TRUE(verify_callback_called)
  13283. << "Verify callback should have been called";
  13284. EXPECT_FALSE(ip_matched_via_cn)
  13285. << "An IP host must not be authenticated via the certificate CN";
  13286. }
  13287. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13288. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13289. using namespace httplib::tls;
  13290. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13291. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13292. ASSERT_TRUE(svr.is_valid());
  13293. svr.Get("/test", [](const Request &, Response &res) {
  13294. res.set_content("ok", "text/plain");
  13295. });
  13296. thread t([&]() { svr.listen(HOST, PORT); });
  13297. auto se = detail::scope_exit([&] {
  13298. svr.stop();
  13299. t.join();
  13300. });
  13301. svr.wait_until_ready();
  13302. bool verify_callback_called = false;
  13303. bool san_matched = false;
  13304. bool wrong_ipv6_matched = true;
  13305. bool cn_ipv6_matched = true;
  13306. SSLClient cli(HOST, PORT);
  13307. cli.enable_server_certificate_verification(true);
  13308. cli.set_ca_cert_path(CA_CERT_FILE);
  13309. cli.set_connection_timeout(5);
  13310. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13311. verify_callback_called = true;
  13312. if (!ctx.cert) return false;
  13313. // Matches the IPv6 iPAddress SAN.
  13314. san_matched = ctx.check_hostname("2001:db8::1");
  13315. // A different IPv6 address must not match.
  13316. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13317. // "::1" lives only in the CN, so it must not be accepted.
  13318. cn_ipv6_matched = ctx.check_hostname("::1");
  13319. return true; // Accept for the purpose of this test
  13320. });
  13321. cli.Get("/test");
  13322. ASSERT_TRUE(verify_callback_called)
  13323. << "Verify callback should have been called";
  13324. EXPECT_TRUE(san_matched)
  13325. << "verify_hostname should match an IPv6 iPAddress SAN";
  13326. EXPECT_FALSE(wrong_ipv6_matched)
  13327. << "verify_hostname should not match a non-matching IPv6 address";
  13328. EXPECT_FALSE(cn_ipv6_matched)
  13329. << "An IPv6 host must not be authenticated via the certificate CN";
  13330. }
  13331. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13332. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13333. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13334. using namespace httplib::tls;
  13335. // SANs: DNS:a.zz, IP:42.46.122.122
  13336. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13337. ASSERT_TRUE(svr.is_valid());
  13338. svr.Get("/test", [](const Request &, Response &res) {
  13339. res.set_content("ok", "text/plain");
  13340. });
  13341. auto port = svr.bind_to_any_port(HOST);
  13342. thread t([&]() { svr.listen_after_bind(); });
  13343. auto se = detail::scope_exit([&] {
  13344. svr.stop();
  13345. t.join();
  13346. });
  13347. svr.wait_until_ready();
  13348. bool verify_callback_called = false;
  13349. bool dns_san_matched = false;
  13350. bool ip_san_matched = false;
  13351. bool ip_matched_via_dns_san = true;
  13352. bool dns_matched_via_ip_san = true;
  13353. SSLClient cli(HOST, port);
  13354. cli.enable_server_certificate_verification(true);
  13355. cli.set_ca_cert_path(CA_CERT_FILE);
  13356. cli.set_connection_timeout(5);
  13357. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13358. verify_callback_called = true;
  13359. if (!ctx.cert) return false;
  13360. dns_san_matched = ctx.check_hostname("a.zz");
  13361. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13362. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13363. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13364. return true; // Accept for the purpose of this test
  13365. });
  13366. cli.Get("/test");
  13367. ASSERT_TRUE(verify_callback_called)
  13368. << "Verify callback should have been called";
  13369. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13370. EXPECT_TRUE(ip_san_matched)
  13371. << "verify_hostname should match an iPAddress SAN";
  13372. EXPECT_FALSE(ip_matched_via_dns_san)
  13373. << "An IP host must not be authenticated via a dNSName SAN";
  13374. EXPECT_FALSE(dns_matched_via_ip_san)
  13375. << "A DNS host must not be authenticated via an iPAddress SAN";
  13376. }
  13377. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13378. // "www.*.example.test" names one host and not every host under example.test.
  13379. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13380. using namespace httplib::tls;
  13381. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13382. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13383. ASSERT_TRUE(svr.is_valid());
  13384. svr.Get("/test", [](const Request &, Response &res) {
  13385. res.set_content("ok", "text/plain");
  13386. });
  13387. auto port = svr.bind_to_any_port(HOST);
  13388. thread t([&]() { svr.listen_after_bind(); });
  13389. auto se = detail::scope_exit([&] {
  13390. svr.stop();
  13391. t.join();
  13392. });
  13393. svr.wait_until_ready();
  13394. bool verify_callback_called = false;
  13395. bool leftmost_wildcard_matched = false;
  13396. bool wildcard_spanned_labels = true;
  13397. bool inner_wildcard_matched = true;
  13398. SSLClient cli(HOST, port);
  13399. cli.enable_server_certificate_verification(true);
  13400. cli.set_ca_cert_path(CA_CERT_FILE);
  13401. cli.set_connection_timeout(5);
  13402. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13403. verify_callback_called = true;
  13404. if (!ctx.cert) return false;
  13405. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13406. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13407. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13408. return true; // Accept for the purpose of this test
  13409. });
  13410. cli.Get("/test");
  13411. ASSERT_TRUE(verify_callback_called)
  13412. << "Verify callback should have been called";
  13413. EXPECT_TRUE(leftmost_wildcard_matched)
  13414. << "A leftmost wildcard should match a single label";
  13415. EXPECT_FALSE(wildcard_spanned_labels)
  13416. << "A wildcard label must not match more than one label";
  13417. EXPECT_FALSE(inner_wildcard_matched)
  13418. << "A wildcard outside the leftmost label must not be honoured";
  13419. }
  13420. // sans() must report each SAN entry under its own type.
  13421. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13422. using namespace httplib::tls;
  13423. // SANs: DNS:a.zz, IP:42.46.122.122
  13424. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13425. ASSERT_TRUE(svr.is_valid());
  13426. svr.Get("/test", [](const Request &, Response &res) {
  13427. res.set_content("ok", "text/plain");
  13428. });
  13429. auto port = svr.bind_to_any_port(HOST);
  13430. thread t([&]() { svr.listen_after_bind(); });
  13431. auto se = detail::scope_exit([&] {
  13432. svr.stop();
  13433. t.join();
  13434. });
  13435. svr.wait_until_ready();
  13436. bool verify_callback_called = false;
  13437. std::vector<SanEntry> sans;
  13438. SSLClient cli(HOST, port);
  13439. cli.enable_server_certificate_verification(true);
  13440. cli.set_ca_cert_path(CA_CERT_FILE);
  13441. cli.set_connection_timeout(5);
  13442. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13443. verify_callback_called = true;
  13444. if (!ctx.cert) return false;
  13445. sans = ctx.sans();
  13446. return true; // Accept for the purpose of this test
  13447. });
  13448. cli.Get("/test");
  13449. ASSERT_TRUE(verify_callback_called)
  13450. << "Verify callback should have been called";
  13451. auto has_san = [&](SanType type, const std::string &value) {
  13452. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13453. return san.type == type && san.value == value;
  13454. });
  13455. };
  13456. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13457. << "sans() should report the dNSName SAN";
  13458. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13459. << "sans() should report the iPAddress SAN";
  13460. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13461. << "sans() must not report the dNSName SAN as an address";
  13462. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13463. << "sans() must not report the iPAddress SAN as a DNS name";
  13464. }
  13465. #endif
  13466. // mbedTLS-specific callback constructor test
  13467. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13468. #ifdef CPPHTTPLIB_SSL_ENABLED
  13469. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13470. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13471. ASSERT_TRUE(svr.is_valid());
  13472. // Set up a handler to verify client certificate is present
  13473. bool client_cert_verified = false;
  13474. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13475. // Verify that client certificate was provided
  13476. client_cert_verified = true;
  13477. res.set_content("success", "text/plain");
  13478. });
  13479. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13480. auto se = detail::scope_exit([&] {
  13481. svr.stop();
  13482. t.join();
  13483. ASSERT_FALSE(svr.is_running());
  13484. });
  13485. svr.wait_until_ready();
  13486. // Client with certificate
  13487. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13488. cli.enable_server_certificate_verification(false);
  13489. cli.set_connection_timeout(30);
  13490. auto res = cli.Get("/test");
  13491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13492. ASSERT_EQ(StatusCode::OK_200, res->status);
  13493. ASSERT_TRUE(client_cert_verified);
  13494. EXPECT_EQ("success", res->body);
  13495. }
  13496. #endif
  13497. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13498. // backends
  13499. #ifdef CPPHTTPLIB_SSL_ENABLED
  13500. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13501. using namespace httplib::tls;
  13502. // Test that when client CA cert file is provided,
  13503. // the server properly requests and validates client certificates
  13504. // Create a server with client authentication
  13505. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13506. ASSERT_TRUE(svr.is_valid());
  13507. bool handler_called = false;
  13508. svr.Get("/test", [&](const Request &req, Response &res) {
  13509. handler_called = true;
  13510. // Verify that a client certificate was provided
  13511. auto cert = req.peer_cert();
  13512. ASSERT_TRUE(static_cast<bool>(cert));
  13513. // Get the issuer name
  13514. std::string issuer_str = cert.issuer_name();
  13515. ASSERT_FALSE(issuer_str.empty());
  13516. // The client certificate should be issued by our test CA
  13517. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13518. res.set_content("authenticated", "text/plain");
  13519. });
  13520. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13521. auto se = detail::scope_exit([&] {
  13522. svr.stop();
  13523. t.join();
  13524. ASSERT_FALSE(svr.is_running());
  13525. });
  13526. svr.wait_until_ready();
  13527. // Connect with a client certificate issued by the CA
  13528. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13529. cli.enable_server_certificate_verification(false);
  13530. cli.set_connection_timeout(30);
  13531. auto res = cli.Get("/test");
  13532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13533. ASSERT_EQ(StatusCode::OK_200, res->status);
  13534. ASSERT_TRUE(handler_called);
  13535. EXPECT_EQ("authenticated", res->body);
  13536. }
  13537. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13538. using namespace httplib::tls;
  13539. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13540. ASSERT_TRUE(svr.is_valid());
  13541. svr.Get("/test", [](const Request &, Response &res) {
  13542. res.set_content("ok", "text/plain");
  13543. });
  13544. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13545. auto se = detail::scope_exit([&] {
  13546. svr.stop();
  13547. t.join();
  13548. });
  13549. svr.wait_until_ready();
  13550. SSLClient cli(HOST, PORT);
  13551. cli.enable_server_certificate_verification(false);
  13552. cli.set_connection_timeout(30);
  13553. bool cert_checked = false;
  13554. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13555. if (ctx.cert) {
  13556. auto sans = ctx.sans();
  13557. // Test certificate may or may not have SANs - just verify the API
  13558. // works If SANs exist, verify the types are valid
  13559. for (const auto &san : sans) {
  13560. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13561. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13562. san.type == SanType::OTHER);
  13563. EXPECT_FALSE(san.value.empty());
  13564. }
  13565. cert_checked = true;
  13566. }
  13567. return true;
  13568. });
  13569. auto res = cli.Get("/test");
  13570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13571. EXPECT_TRUE(cert_checked);
  13572. }
  13573. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13574. using namespace httplib::tls;
  13575. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13576. ASSERT_TRUE(svr.is_valid());
  13577. svr.Get("/test", [](const Request &, Response &res) {
  13578. res.set_content("ok", "text/plain");
  13579. });
  13580. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13581. auto se = detail::scope_exit([&] {
  13582. svr.stop();
  13583. t.join();
  13584. });
  13585. svr.wait_until_ready();
  13586. SSLClient cli(HOST, PORT);
  13587. cli.enable_server_certificate_verification(false);
  13588. cli.set_connection_timeout(30);
  13589. bool validity_checked = false;
  13590. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13591. if (ctx.cert) {
  13592. time_t not_before = 0, not_after = 0;
  13593. bool result = ctx.validity(not_before, not_after);
  13594. EXPECT_TRUE(result);
  13595. // Verify that not_before < now < not_after for a valid cert
  13596. time_t now = time(nullptr);
  13597. EXPECT_LT(not_before, now);
  13598. EXPECT_GT(not_after, now);
  13599. validity_checked = true;
  13600. }
  13601. return true;
  13602. });
  13603. auto res = cli.Get("/test");
  13604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13605. EXPECT_TRUE(validity_checked);
  13606. }
  13607. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13608. using namespace httplib::tls;
  13609. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13610. ASSERT_TRUE(svr.is_valid());
  13611. svr.Get("/test", [](const Request &, Response &res) {
  13612. res.set_content("ok", "text/plain");
  13613. });
  13614. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13615. auto se = detail::scope_exit([&] {
  13616. svr.stop();
  13617. t.join();
  13618. });
  13619. svr.wait_until_ready();
  13620. SSLClient cli(HOST, PORT);
  13621. cli.enable_server_certificate_verification(false);
  13622. cli.set_connection_timeout(30);
  13623. bool serial_checked = false;
  13624. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13625. if (ctx.cert) {
  13626. std::string serial = ctx.serial();
  13627. EXPECT_FALSE(serial.empty());
  13628. // Serial should be a hex string
  13629. for (char c : serial) {
  13630. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13631. (c >= 'a' && c <= 'f'));
  13632. }
  13633. serial_checked = true;
  13634. }
  13635. return true;
  13636. });
  13637. auto res = cli.Get("/test");
  13638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13639. EXPECT_TRUE(serial_checked);
  13640. }
  13641. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13642. // Test 1: Valid CA file - no error should be recorded
  13643. {
  13644. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13645. CLIENT_CA_CERT_FILE);
  13646. ASSERT_TRUE(svr.is_valid());
  13647. // With valid setup, last_ssl_error should be 0
  13648. EXPECT_EQ(0, svr.ssl_last_error());
  13649. }
  13650. // Test 2: Invalid CA file content
  13651. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13652. {
  13653. // Create a temporary file with completely invalid content
  13654. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13655. {
  13656. std::ofstream ofs(temp_invalid_ca);
  13657. ofs << "This is not a certificate file at all\n";
  13658. ofs << "Just plain text content\n";
  13659. }
  13660. // Create server with invalid CA file
  13661. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13662. // Clean up temporary file
  13663. std::remove(temp_invalid_ca);
  13664. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13665. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13666. // Note: SSL_CTX_load_verify_locations typically fails first,
  13667. // but our error handling code path is still exercised
  13668. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13669. }
  13670. }
  13671. TEST(VerifyCallbackTest, VerifyContextFields) {
  13672. using namespace httplib::tls;
  13673. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13674. ASSERT_TRUE(svr.is_valid());
  13675. svr.Get("/test", [](const Request &, Response &res) {
  13676. res.set_content("ok", "text/plain");
  13677. });
  13678. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13679. auto se = detail::scope_exit([&] {
  13680. svr.stop();
  13681. t.join();
  13682. });
  13683. svr.wait_until_ready();
  13684. SSLClient cli(HOST, PORT);
  13685. cli.enable_server_certificate_verification(false);
  13686. cli.set_connection_timeout(30);
  13687. int callback_count = 0;
  13688. bool saw_leaf_cert = false;
  13689. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13690. if (ctx.cert) {
  13691. callback_count++;
  13692. // We should see at least one certificate (the leaf)
  13693. std::string cn = ctx.subject_cn();
  13694. if (!cn.empty()) { saw_leaf_cert = true; }
  13695. // Verify context fields are populated
  13696. EXPECT_NE(ctx.session, nullptr);
  13697. EXPECT_GE(ctx.depth, 0);
  13698. }
  13699. return true;
  13700. });
  13701. auto res = cli.Get("/test");
  13702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13703. EXPECT_GT(callback_count, 0);
  13704. EXPECT_TRUE(saw_leaf_cert);
  13705. }
  13706. // A verifier belongs to the client that set it, not to the thread that set it.
  13707. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13708. using namespace httplib::tls;
  13709. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13710. ASSERT_TRUE(svr.is_valid());
  13711. svr.Get("/test", [](const Request &, Response &res) {
  13712. res.set_content("ok", "text/plain");
  13713. });
  13714. auto port = svr.bind_to_any_port(HOST);
  13715. thread t([&]() { svr.listen_after_bind(); });
  13716. auto se = detail::scope_exit([&] {
  13717. svr.stop();
  13718. t.join();
  13719. });
  13720. svr.wait_until_ready();
  13721. auto rejecting_calls = 0;
  13722. SSLClient rejecting(HOST, port);
  13723. rejecting.enable_server_certificate_verification(false);
  13724. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13725. rejecting_calls++;
  13726. return false;
  13727. });
  13728. auto accepting_calls = 0;
  13729. SSLClient accepting(HOST, port);
  13730. accepting.enable_server_certificate_verification(false);
  13731. // Set on another thread than the requests below.
  13732. thread([&]() {
  13733. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13734. accepting_calls++;
  13735. return true;
  13736. });
  13737. }).join();
  13738. // Requested on another thread than the verifier was set on.
  13739. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13740. EXPECT_GT(rejecting_calls, 0);
  13741. auto res = accepting.Get("/test");
  13742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13743. EXPECT_GT(accepting_calls, 0);
  13744. }
  13745. // VerifyContext::session is the same handle the other tls:: functions take.
  13746. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13747. using namespace httplib::tls;
  13748. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13749. ASSERT_TRUE(svr.is_valid());
  13750. svr.Get("/test", [](const Request &, Response &res) {
  13751. res.set_content("ok", "text/plain");
  13752. });
  13753. auto port = svr.bind_to_any_port(HOST);
  13754. thread t([&]() { svr.listen_after_bind(); });
  13755. auto se = detail::scope_exit([&] {
  13756. svr.stop();
  13757. t.join();
  13758. });
  13759. svr.wait_until_ready();
  13760. SSLClient cli(HOST, port);
  13761. cli.enable_server_certificate_verification(false);
  13762. session_t verifier_session = nullptr;
  13763. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  13764. verifier_session = ctx.session;
  13765. return true;
  13766. });
  13767. session_t session_verifier_session = nullptr;
  13768. cli.set_session_verifier([&](session_t session) {
  13769. session_verifier_session = session;
  13770. return SSLVerifierResponse::NoDecisionMade;
  13771. });
  13772. auto res = cli.Get("/test");
  13773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13774. EXPECT_NE(nullptr, verifier_session);
  13775. EXPECT_EQ(session_verifier_session, verifier_session);
  13776. }
  13777. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13778. using httplib::tls::TlsError;
  13779. // Test that verify_error_to_string returns empty for success
  13780. std::string success_str = TlsError::verify_error_to_string(0);
  13781. EXPECT_TRUE(success_str.empty());
  13782. // Test that verify_error_to_string returns non-empty for error codes
  13783. // Using a common error code (certificate expired)
  13784. std::string error_str =
  13785. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13786. EXPECT_FALSE(error_str.empty());
  13787. }
  13788. TEST(SessionVerifierTest, CertificateAccepted) {
  13789. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13790. ASSERT_TRUE(svr.is_valid());
  13791. svr.Get("/test", [](const Request &, Response &res) {
  13792. res.set_content("ok", "text/plain");
  13793. });
  13794. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13795. auto se = detail::scope_exit([&] {
  13796. svr.stop();
  13797. t.join();
  13798. });
  13799. svr.wait_until_ready();
  13800. SSLClient cli(HOST, PORT);
  13801. cli.enable_server_certificate_verification(false);
  13802. cli.set_connection_timeout(30);
  13803. bool callback_called = false;
  13804. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13805. EXPECT_NE(session, nullptr);
  13806. callback_called = true;
  13807. return SSLVerifierResponse::CertificateAccepted;
  13808. });
  13809. auto res = cli.Get("/test");
  13810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13811. EXPECT_EQ(200, res->status);
  13812. EXPECT_TRUE(callback_called);
  13813. }
  13814. TEST(SessionVerifierTest, CertificateRejected) {
  13815. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13816. ASSERT_TRUE(svr.is_valid());
  13817. svr.Get("/test", [](const Request &, Response &res) {
  13818. res.set_content("ok", "text/plain");
  13819. });
  13820. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13821. auto se = detail::scope_exit([&] {
  13822. svr.stop();
  13823. t.join();
  13824. });
  13825. svr.wait_until_ready();
  13826. SSLClient cli(HOST, PORT);
  13827. cli.enable_server_certificate_verification(false);
  13828. cli.set_connection_timeout(30);
  13829. bool callback_called = false;
  13830. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13831. EXPECT_NE(session, nullptr);
  13832. callback_called = true;
  13833. return SSLVerifierResponse::CertificateRejected;
  13834. });
  13835. auto res = cli.Get("/test");
  13836. EXPECT_FALSE(res);
  13837. EXPECT_TRUE(callback_called);
  13838. }
  13839. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13840. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13841. ASSERT_TRUE(svr.is_valid());
  13842. svr.Get("/test", [](const Request &, Response &res) {
  13843. res.set_content("ok", "text/plain");
  13844. });
  13845. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13846. auto se = detail::scope_exit([&] {
  13847. svr.stop();
  13848. t.join();
  13849. });
  13850. svr.wait_until_ready();
  13851. // NoDecisionMade with verification disabled should succeed (no default check)
  13852. SSLClient cli(HOST, PORT);
  13853. cli.enable_server_certificate_verification(false);
  13854. cli.set_connection_timeout(30);
  13855. bool callback_called = false;
  13856. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13857. EXPECT_NE(session, nullptr);
  13858. callback_called = true;
  13859. return SSLVerifierResponse::NoDecisionMade;
  13860. });
  13861. auto res = cli.Get("/test");
  13862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13863. EXPECT_EQ(200, res->status);
  13864. EXPECT_TRUE(callback_called);
  13865. }
  13866. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  13867. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13868. ASSERT_TRUE(svr.is_valid());
  13869. svr.Get("/test", [](const Request &, Response &res) {
  13870. res.set_content("ok", "text/plain");
  13871. });
  13872. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13873. auto se = detail::scope_exit([&] {
  13874. svr.stop();
  13875. t.join();
  13876. });
  13877. svr.wait_until_ready();
  13878. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13879. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13880. // so we only check that the request fails, not whether the callback was
  13881. // called.
  13882. SSLClient cli(HOST, PORT);
  13883. cli.enable_server_certificate_verification(true);
  13884. cli.set_connection_timeout(30);
  13885. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13886. EXPECT_NE(session, nullptr);
  13887. return SSLVerifierResponse::NoDecisionMade;
  13888. });
  13889. auto res = cli.Get("/test");
  13890. EXPECT_FALSE(res);
  13891. }
  13892. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13893. // Test SSL server using PemMemory constructor with client CA certificates
  13894. // Read PEM files
  13895. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13896. read_file(SERVER_CERT_FILE, server_cert_pem);
  13897. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13898. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13899. // Create SSLServer with PemMemory constructor including client CA
  13900. SSLServer::PemMemory server_pem = {
  13901. server_cert_pem.c_str(),
  13902. server_cert_pem.size(),
  13903. server_key_pem.c_str(),
  13904. server_key_pem.size(),
  13905. client_ca_pem.c_str(),
  13906. client_ca_pem.size(),
  13907. nullptr // no password for server key
  13908. };
  13909. SSLServer svr(server_pem);
  13910. ASSERT_TRUE(svr.is_valid());
  13911. // No SSL error should be recorded for valid setup
  13912. EXPECT_EQ(0, svr.ssl_last_error());
  13913. // Set up server endpoints
  13914. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13915. res.set_content("ok", "text/plain");
  13916. });
  13917. // Start server in a thread
  13918. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13919. svr.wait_until_ready();
  13920. // Connect with client certificate (using constructor with paths)
  13921. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13922. cli.enable_server_certificate_verification(false);
  13923. auto res = cli.Get("/test-pem-ca");
  13924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13925. EXPECT_EQ(200, res->status);
  13926. EXPECT_EQ("ok", res->body);
  13927. svr.stop();
  13928. server_thread.join();
  13929. }
  13930. #endif
  13931. #ifdef _WIN32
  13932. TEST(CleanupTest, WSACleanup) {
  13933. int ret = WSACleanup();
  13934. ASSERT_EQ(0, ret);
  13935. }
  13936. #endif
  13937. #ifndef CPPHTTPLIB_SSL_ENABLED
  13938. TEST(NoSSLSupport, SimpleInterface) {
  13939. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13940. }
  13941. #endif
  13942. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13943. TEST(InvalidScheme, SimpleInterface) {
  13944. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13945. }
  13946. #endif
  13947. TEST(NoScheme, SimpleInterface) {
  13948. Client cli("yahoo.com:80");
  13949. ASSERT_TRUE(cli.is_valid());
  13950. }
  13951. TEST(SendAPI, SimpleInterface_Online) {
  13952. Client cli("http://yahoo.com");
  13953. Request req;
  13954. req.method = "GET";
  13955. req.path = "/";
  13956. auto res = cli.send(req);
  13957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13958. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13959. }
  13960. TEST(SendAPI, WithParamsInRequest) {
  13961. Server svr;
  13962. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13963. EXPECT_TRUE(req.has_param("test"));
  13964. EXPECT_EQ("test_value", req.get_param_value("test"));
  13965. });
  13966. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13967. auto se = detail::scope_exit([&] {
  13968. svr.stop();
  13969. t.join();
  13970. ASSERT_FALSE(svr.is_running());
  13971. });
  13972. svr.wait_until_ready();
  13973. Client cli(HOST, PORT);
  13974. {
  13975. Request req;
  13976. req.method = "GET";
  13977. req.path = "/";
  13978. req.params.emplace("test", "test_value");
  13979. auto res = cli.send(req);
  13980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13981. }
  13982. {
  13983. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13985. }
  13986. }
  13987. TEST(ClientImplMethods, GetSocketTest) {
  13988. httplib::Server svr;
  13989. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13990. res.status = StatusCode::OK_200;
  13991. });
  13992. auto port = svr.bind_to_any_port("127.0.0.1");
  13993. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13994. auto se = detail::scope_exit([&] {
  13995. svr.stop();
  13996. thread.join();
  13997. ASSERT_FALSE(svr.is_running());
  13998. });
  13999. svr.wait_until_ready();
  14000. {
  14001. httplib::Client cli("127.0.0.1", port);
  14002. cli.set_keep_alive(true);
  14003. // Use the behavior of cpp-httplib of opening the connection
  14004. // only when the first request happens. If that changes,
  14005. // this test would be obsolete.
  14006. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14007. // This also implicitly tests the server. But other tests would fail much
  14008. // earlier than this one to be considered.
  14009. auto res = cli.Get("/");
  14010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14011. EXPECT_EQ(StatusCode::OK_200, res->status);
  14012. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14013. }
  14014. }
  14015. #ifdef CPPHTTPLIB_SSL_ENABLED
  14016. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14017. Client cli("http://yahoo.com");
  14018. auto res = cli.Get("/");
  14019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14020. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14021. cli.set_follow_location(true);
  14022. res = cli.Get("/");
  14023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14024. EXPECT_EQ(StatusCode::OK_200, res->status);
  14025. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14026. }
  14027. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14028. Client cli("https://yahoo.com");
  14029. auto res = cli.Get("/");
  14030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14031. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14032. cli.set_follow_location(true);
  14033. res = cli.Get("/");
  14034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14035. EXPECT_EQ(StatusCode::OK_200, res->status);
  14036. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14037. }
  14038. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14039. Client cli("https://yahoo.com");
  14040. auto res = cli.Get("/");
  14041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14042. ASSERT_FALSE(!res);
  14043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14044. ASSERT_FALSE(res == nullptr);
  14045. ASSERT_TRUE(res != nullptr);
  14046. EXPECT_EQ(Error::Success, res.error());
  14047. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14048. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14049. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14050. cli.set_follow_location(true);
  14051. res = cli.Get("/");
  14052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14053. EXPECT_EQ(Error::Success, res.error());
  14054. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14055. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14056. EXPECT_EQ(StatusCode::OK_200, res->status);
  14057. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14058. }
  14059. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14060. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14061. Client cli("https://cdnjs.cloudflare.com");
  14062. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14063. Headers{{"Accept-Encoding", "br"}});
  14064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14065. EXPECT_EQ(StatusCode::OK_200, res->status);
  14066. EXPECT_EQ(287630U, res->body.size());
  14067. EXPECT_EQ("application/javascript; charset=utf-8",
  14068. res->get_header_value("Content-Type"));
  14069. }
  14070. #endif
  14071. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14072. #undef REDIR_HOST // Silence compiler warning
  14073. #define REDIR_HOST "https://httpbingo.org"
  14074. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14075. Client cli(REDIR_HOST);
  14076. cli.set_follow_location(true);
  14077. auto res =
  14078. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14080. EXPECT_EQ(StatusCode::OK_200, res->status);
  14081. }
  14082. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14083. Client cli(REDIR_HOST);
  14084. cli.set_follow_location(true);
  14085. Params params;
  14086. params.emplace("url", "http://example.com");
  14087. params.emplace("status_code", "302");
  14088. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14090. EXPECT_EQ(StatusCode::OK_200, res->status);
  14091. }
  14092. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14093. Client cli(REDIR_HOST);
  14094. cli.set_follow_location(true);
  14095. Params params;
  14096. params.emplace("url", "http://example.com");
  14097. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14099. EXPECT_EQ(StatusCode::OK_200, res->status);
  14100. }
  14101. TEST(HttpToHttpsRedirectTest, CertFile) {
  14102. auto ssl_port = PORT + 1;
  14103. Server svr;
  14104. ASSERT_TRUE(svr.is_valid());
  14105. svr.Get("/index", [&](const Request &, Response &res) {
  14106. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14107. "/index");
  14108. svr.stop();
  14109. });
  14110. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14111. ASSERT_TRUE(ssl_svr.is_valid());
  14112. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14113. res.set_content("test", "text/plain");
  14114. ssl_svr.stop();
  14115. });
  14116. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14117. thread t2 =
  14118. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14119. auto se = detail::scope_exit([&] {
  14120. t2.join();
  14121. t.join();
  14122. ASSERT_FALSE(svr.is_running());
  14123. });
  14124. svr.wait_until_ready();
  14125. ssl_svr.wait_until_ready();
  14126. Client cli("127.0.0.1", PORT);
  14127. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14128. cli.enable_server_certificate_verification(true);
  14129. cli.set_follow_location(true);
  14130. cli.set_connection_timeout(30);
  14131. auto res = cli.Get("/index");
  14132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14133. ASSERT_EQ(StatusCode::OK_200, res->status);
  14134. }
  14135. TEST(SSLClientRedirectTest, CertFile) {
  14136. auto ssl_port = PORT + 1;
  14137. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14138. ASSERT_TRUE(ssl_svr1.is_valid());
  14139. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14140. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14141. "/index");
  14142. ssl_svr1.stop();
  14143. });
  14144. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14145. ASSERT_TRUE(ssl_svr2.is_valid());
  14146. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14147. res.set_content("test", "text/plain");
  14148. ssl_svr2.stop();
  14149. });
  14150. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14151. thread t2 =
  14152. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14153. auto se = detail::scope_exit([&] {
  14154. t2.join();
  14155. t.join();
  14156. ASSERT_FALSE(ssl_svr1.is_running());
  14157. });
  14158. ssl_svr1.wait_until_ready();
  14159. ssl_svr2.wait_until_ready();
  14160. SSLClient cli("127.0.0.1", PORT);
  14161. std::string cert;
  14162. read_file(SERVER_CERT2_FILE, cert);
  14163. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14164. cli.enable_server_certificate_verification(true);
  14165. cli.set_follow_location(true);
  14166. cli.set_connection_timeout(30);
  14167. auto res = cli.Get("/index");
  14168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14169. ASSERT_EQ(StatusCode::OK_200, res->status);
  14170. }
  14171. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14172. // another port, so the client follows it with a new client.
  14173. static Result GetThroughTlsRedirectToDifferentPort(
  14174. const std::function<void(SSLClient &)> &setup,
  14175. const char *target_cert = SERVER_CERT2_FILE) {
  14176. auto ssl_port = PORT + 1;
  14177. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14178. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14179. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14180. "/index");
  14181. });
  14182. SSLServer ssl_svr2(target_cert, SERVER_PRIVATE_KEY_FILE);
  14183. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14184. res.set_content("test", "text/plain");
  14185. });
  14186. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14187. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14188. auto se = detail::scope_exit([&] {
  14189. ssl_svr2.stop();
  14190. ssl_svr1.stop();
  14191. t2.join();
  14192. t.join();
  14193. });
  14194. ssl_svr1.wait_until_ready();
  14195. ssl_svr2.wait_until_ready();
  14196. SSLClient cli("127.0.0.1", PORT);
  14197. cli.set_follow_location(true);
  14198. cli.set_connection_timeout(30);
  14199. setup(cli);
  14200. return cli.Get("/index");
  14201. }
  14202. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14203. auto calls = 0;
  14204. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14205. cli.enable_server_certificate_verification(false);
  14206. // Accept the first server only.
  14207. cli.set_session_verifier([&](tls::session_t) {
  14208. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14209. : SSLVerifierResponse::CertificateRejected;
  14210. });
  14211. });
  14212. EXPECT_FALSE(res);
  14213. EXPECT_EQ(2, calls);
  14214. }
  14215. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14216. std::string pinned;
  14217. auto res = GetThroughTlsRedirectToDifferentPort(
  14218. [&](SSLClient &cli) {
  14219. cli.enable_server_certificate_verification(false);
  14220. // Pin the first certificate seen.
  14221. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14222. if (pinned.empty()) { pinned = ctx.serial(); }
  14223. return ctx.serial() == pinned;
  14224. });
  14225. },
  14226. // A certificate other than the first server's.
  14227. SERVER_CERT_FILE);
  14228. EXPECT_FALSE(res);
  14229. EXPECT_FALSE(pinned.empty());
  14230. }
  14231. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14232. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14233. std::string cert;
  14234. read_file(SERVER_CERT2_FILE, cert);
  14235. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14236. });
  14237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14238. EXPECT_EQ(StatusCode::OK_200, res->status);
  14239. }
  14240. #endif
  14241. #ifdef CPPHTTPLIB_SSL_ENABLED
  14242. // Test that set_ca_cert_store() skips system certs (consistent with
  14243. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  14244. // should be trusted - system certs should NOT be loaded.
  14245. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  14246. // Load a specific cert that is NOT a system CA cert
  14247. std::string cert;
  14248. read_file(SERVER_CERT2_FILE, cert);
  14249. SSLClient cli("google.com");
  14250. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14251. cli.enable_server_certificate_verification(true);
  14252. // This should FAIL because:
  14253. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  14254. // 2. System certs should NOT be loaded when custom store is set
  14255. // If system certs WERE loaded, this would succeed
  14256. auto res = cli.Get("/");
  14257. ASSERT_FALSE(res);
  14258. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14259. }
  14260. // Same as above, but through the native store handle path. Regression test:
  14261. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  14262. // merged system certs into the user-provided store.
  14263. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  14264. std::string cert;
  14265. read_file(SERVER_CERT2_FILE, cert);
  14266. SSLClient cli("google.com");
  14267. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14268. cli.enable_server_certificate_verification(true);
  14269. auto res = cli.Get("/");
  14270. ASSERT_FALSE(res);
  14271. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14272. }
  14273. // A custom store set via the native handle must still verify a server whose
  14274. // cert it does contain.
  14275. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  14276. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14277. ASSERT_TRUE(svr.is_valid());
  14278. svr.Get("/test", [&](const Request &, Response &res) {
  14279. res.set_content("test", "text/plain");
  14280. });
  14281. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14282. auto se = detail::scope_exit([&] {
  14283. svr.stop();
  14284. t.join();
  14285. ASSERT_FALSE(svr.is_running());
  14286. });
  14287. svr.wait_until_ready();
  14288. SSLClient cli("127.0.0.1", PORT);
  14289. std::string cert;
  14290. read_file(SERVER_CERT2_FILE, cert);
  14291. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14292. cli.enable_server_certificate_verification(true);
  14293. cli.set_connection_timeout(30);
  14294. auto res = cli.Get("/test");
  14295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14296. ASSERT_EQ(StatusCode::OK_200, res->status);
  14297. }
  14298. // CA certs loaded through the universal Client must be transferred to the
  14299. // client created internally for following an HTTPS redirect. Regression test:
  14300. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  14301. // the CA data for redirect transfer.
  14302. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  14303. auto ssl_port = PORT + 1;
  14304. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14305. ASSERT_TRUE(ssl_svr1.is_valid());
  14306. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14307. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14308. "/index");
  14309. });
  14310. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14311. ASSERT_TRUE(ssl_svr2.is_valid());
  14312. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14313. res.set_content("test", "text/plain");
  14314. });
  14315. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14316. thread t2 =
  14317. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14318. auto se = detail::scope_exit([&] {
  14319. ssl_svr2.stop();
  14320. ssl_svr1.stop();
  14321. t2.join();
  14322. t.join();
  14323. ASSERT_FALSE(ssl_svr1.is_running());
  14324. });
  14325. ssl_svr1.wait_until_ready();
  14326. ssl_svr2.wait_until_ready();
  14327. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14328. std::string cert;
  14329. read_file(SERVER_CERT2_FILE, cert);
  14330. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14331. cli.enable_server_certificate_verification(true);
  14332. cli.set_follow_location(true);
  14333. cli.set_connection_timeout(30);
  14334. auto res = cli.Get("/index");
  14335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14336. ASSERT_EQ(StatusCode::OK_200, res->status);
  14337. }
  14338. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14339. // so a host signed by a system CA verifies even though a custom CA is set
  14340. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14341. std::string cert;
  14342. read_file(SERVER_CERT2_FILE, cert);
  14343. SSLClient cli("google.com");
  14344. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14345. cli.enable_system_ca(true);
  14346. cli.enable_server_certificate_verification(true);
  14347. auto res = cli.Get("/");
  14348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14349. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14350. }
  14351. // The custom CA remains effective when combined with the system CA
  14352. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14353. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14354. ASSERT_TRUE(svr.is_valid());
  14355. svr.Get("/test", [&](const Request &, Response &res) {
  14356. res.set_content("test", "text/plain");
  14357. });
  14358. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14359. auto se = detail::scope_exit([&] {
  14360. svr.stop();
  14361. t.join();
  14362. ASSERT_FALSE(svr.is_running());
  14363. });
  14364. svr.wait_until_ready();
  14365. SSLClient cli("127.0.0.1", PORT);
  14366. std::string cert;
  14367. read_file(SERVER_CERT2_FILE, cert);
  14368. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14369. cli.enable_system_ca(true);
  14370. cli.enable_server_certificate_verification(true);
  14371. cli.set_connection_timeout(30);
  14372. auto res = cli.Get("/test");
  14373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14374. ASSERT_EQ(StatusCode::OK_200, res->status);
  14375. }
  14376. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14377. // skip chain verification entirely (only the certificate identity was
  14378. // checked), so a server presenting an untrusted certificate with a matching
  14379. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14380. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14381. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14382. ASSERT_TRUE(svr.is_valid());
  14383. svr.Get("/test", [&](const Request &, Response &res) {
  14384. res.set_content("test", "text/plain");
  14385. });
  14386. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14387. auto se = detail::scope_exit([&] {
  14388. svr.stop();
  14389. t.join();
  14390. ASSERT_FALSE(svr.is_running());
  14391. });
  14392. svr.wait_until_ready();
  14393. SSLClient cli("127.0.0.1", PORT);
  14394. std::string cert;
  14395. // A trusted CA that did not sign the server certificate. The server cert
  14396. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14397. // this connection.
  14398. read_file(CLIENT_CA_CERT_FILE, cert);
  14399. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14400. cli.enable_server_certificate_verification(true);
  14401. cli.set_connection_timeout(30);
  14402. auto res = cli.Get("/test");
  14403. ASSERT_FALSE(res);
  14404. }
  14405. // enable_system_ca(false) prevents system CA loading entirely
  14406. TEST(SSLClientTest, DisableSystemCa_Online) {
  14407. SSLClient cli("google.com");
  14408. cli.enable_system_ca(false);
  14409. cli.enable_server_certificate_verification(true);
  14410. auto res = cli.Get("/");
  14411. ASSERT_FALSE(res);
  14412. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14413. // itself when the CA chain is empty
  14414. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14415. res.error() == Error::SSLConnection);
  14416. }
  14417. // The universal Client forwards enable_system_ca()
  14418. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14419. std::string cert;
  14420. read_file(SERVER_CERT2_FILE, cert);
  14421. Client cli("https://google.com");
  14422. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14423. cli.enable_system_ca(true);
  14424. cli.enable_server_certificate_verification(true);
  14425. auto res = cli.Get("/");
  14426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14427. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14428. }
  14429. // The system CA policy must carry over to the client created internally for
  14430. // following a cross-host HTTPS redirect
  14431. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14432. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14433. ASSERT_TRUE(svr.is_valid());
  14434. svr.Get("/index", [&](const Request &, Response &res) {
  14435. res.set_redirect("https://www.google.com/");
  14436. });
  14437. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14438. auto se = detail::scope_exit([&] {
  14439. svr.stop();
  14440. t.join();
  14441. ASSERT_FALSE(svr.is_running());
  14442. });
  14443. svr.wait_until_ready();
  14444. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14445. std::string cert;
  14446. read_file(SERVER_CERT2_FILE, cert);
  14447. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14448. cli.enable_system_ca(true);
  14449. cli.enable_server_certificate_verification(true);
  14450. cli.set_follow_location(true);
  14451. cli.set_connection_timeout(30);
  14452. // Receiving any response proves the redirect client completed the TLS
  14453. // handshake with a system-CA-signed host
  14454. auto res = cli.Get("/index");
  14455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14456. }
  14457. TEST(MultipartFormDataTest, LargeData) {
  14458. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14459. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14460. const ContentReader &content_reader) {
  14461. if (req.is_multipart_form_data()) {
  14462. std::vector<FormData> items;
  14463. content_reader(
  14464. [&](const FormData &file) {
  14465. items.push_back(file);
  14466. return true;
  14467. },
  14468. [&](const char *data, size_t data_length) {
  14469. items.back().content.append(data, data_length);
  14470. return true;
  14471. });
  14472. EXPECT_TRUE(std::string(items[0].name) == "document");
  14473. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14474. EXPECT_TRUE(items[0].filename == "2MB_data");
  14475. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14476. EXPECT_TRUE(items[1].name == "hello");
  14477. EXPECT_TRUE(items[1].content == "world");
  14478. EXPECT_TRUE(items[1].filename == "");
  14479. EXPECT_TRUE(items[1].content_type == "");
  14480. } else {
  14481. std::string body;
  14482. content_reader([&](const char *data, size_t data_length) {
  14483. body.append(data, data_length);
  14484. return true;
  14485. });
  14486. }
  14487. });
  14488. auto port = svr.bind_to_any_port(HOST);
  14489. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14490. auto se = detail::scope_exit([&] {
  14491. svr.stop();
  14492. t.join();
  14493. ASSERT_FALSE(svr.is_running());
  14494. });
  14495. svr.wait_until_ready();
  14496. {
  14497. std::string data(1024 * 1024 * 2, '.');
  14498. std::stringstream buffer;
  14499. buffer << data;
  14500. SSLClient cli(HOST, port);
  14501. cli.enable_server_certificate_verification(false);
  14502. UploadFormDataItems items{
  14503. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14504. {"hello", "world", "", ""},
  14505. };
  14506. auto res = cli.Post("/post", items);
  14507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14508. ASSERT_EQ(StatusCode::OK_200, res->status);
  14509. }
  14510. }
  14511. TEST(MultipartFormDataTest, DataProviderItems) {
  14512. std::random_device seed_gen;
  14513. std::mt19937 random(seed_gen());
  14514. std::string rand1;
  14515. rand1.resize(1000);
  14516. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14517. std::string rand2;
  14518. rand2.resize(3000);
  14519. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14520. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14521. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14522. const ContentReader &content_reader) {
  14523. ASSERT_FALSE(req.is_multipart_form_data());
  14524. std::string body;
  14525. content_reader([&](const char *data, size_t data_length) {
  14526. body.append(data, data_length);
  14527. return true;
  14528. });
  14529. EXPECT_EQ(body, "");
  14530. });
  14531. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14532. const ContentReader &content_reader) {
  14533. ASSERT_TRUE(req.is_multipart_form_data());
  14534. std::vector<FormData> items;
  14535. content_reader(
  14536. [&](const FormData &file) {
  14537. items.push_back(file);
  14538. return true;
  14539. },
  14540. [&](const char *data, size_t data_length) {
  14541. items.back().content.append(data, data_length);
  14542. return true;
  14543. });
  14544. ASSERT_TRUE(items.size() == 2);
  14545. EXPECT_EQ(std::string(items[0].name), "name1");
  14546. EXPECT_EQ(items[0].content, "Testing123");
  14547. EXPECT_EQ(items[0].filename, "filename1");
  14548. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14549. EXPECT_EQ(items[1].name, "name2");
  14550. EXPECT_EQ(items[1].content, "Testing456");
  14551. EXPECT_EQ(items[1].filename, "");
  14552. EXPECT_EQ(items[1].content_type, "");
  14553. });
  14554. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14555. const ContentReader &content_reader) {
  14556. ASSERT_TRUE(req.is_multipart_form_data());
  14557. std::vector<FormData> items;
  14558. content_reader(
  14559. [&](const FormData &file) {
  14560. items.push_back(file);
  14561. return true;
  14562. },
  14563. [&](const char *data, size_t data_length) {
  14564. items.back().content.append(data, data_length);
  14565. return true;
  14566. });
  14567. ASSERT_TRUE(items.size() == 2);
  14568. EXPECT_EQ(items[0].name, "name3");
  14569. EXPECT_EQ(items[0].content, rand1);
  14570. EXPECT_EQ(items[0].filename, "filename3");
  14571. EXPECT_EQ(items[0].content_type, "");
  14572. EXPECT_EQ(items[1].name, "name4");
  14573. EXPECT_EQ(items[1].content, rand2);
  14574. EXPECT_EQ(items[1].filename, "filename4");
  14575. EXPECT_EQ(items[1].content_type, "");
  14576. });
  14577. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14578. const ContentReader &content_reader) {
  14579. ASSERT_TRUE(req.is_multipart_form_data());
  14580. std::vector<FormData> items;
  14581. content_reader(
  14582. [&](const FormData &file) {
  14583. items.push_back(file);
  14584. return true;
  14585. },
  14586. [&](const char *data, size_t data_length) {
  14587. items.back().content.append(data, data_length);
  14588. return true;
  14589. });
  14590. ASSERT_TRUE(items.size() == 4);
  14591. EXPECT_EQ(std::string(items[0].name), "name1");
  14592. EXPECT_EQ(items[0].content, "Testing123");
  14593. EXPECT_EQ(items[0].filename, "filename1");
  14594. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14595. EXPECT_EQ(items[1].name, "name2");
  14596. EXPECT_EQ(items[1].content, "Testing456");
  14597. EXPECT_EQ(items[1].filename, "");
  14598. EXPECT_EQ(items[1].content_type, "");
  14599. EXPECT_EQ(items[2].name, "name3");
  14600. EXPECT_EQ(items[2].content, rand1);
  14601. EXPECT_EQ(items[2].filename, "filename3");
  14602. EXPECT_EQ(items[2].content_type, "");
  14603. EXPECT_EQ(items[3].name, "name4");
  14604. EXPECT_EQ(items[3].content, rand2);
  14605. EXPECT_EQ(items[3].filename, "filename4");
  14606. EXPECT_EQ(items[3].content_type, "");
  14607. });
  14608. auto port = svr.bind_to_any_port("localhost");
  14609. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14610. auto se = detail::scope_exit([&] {
  14611. svr.stop();
  14612. t.join();
  14613. ASSERT_FALSE(svr.is_running());
  14614. });
  14615. svr.wait_until_ready();
  14616. {
  14617. SSLClient cli("localhost", port);
  14618. cli.enable_server_certificate_verification(false);
  14619. UploadFormDataItems items{
  14620. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14621. {"name2", "Testing456", "", ""}, // not a file
  14622. };
  14623. {
  14624. auto res = cli.Post("/post-none", {}, {}, {});
  14625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14626. ASSERT_EQ(StatusCode::OK_200, res->status);
  14627. }
  14628. FormDataProviderItems providers;
  14629. {
  14630. auto res =
  14631. cli.Post("/post-items", {}, items, providers); // empty providers
  14632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14633. ASSERT_EQ(StatusCode::OK_200, res->status);
  14634. }
  14635. providers.push_back({"name3",
  14636. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14637. // test the offset is given correctly at each step
  14638. if (!offset)
  14639. sink.os.write(rand1.data(), 30);
  14640. else if (offset == 30)
  14641. sink.os.write(rand1.data() + 30, 300);
  14642. else if (offset == 330)
  14643. sink.os.write(rand1.data() + 330, 670);
  14644. else if (offset == rand1.size())
  14645. sink.done();
  14646. return true;
  14647. },
  14648. "filename3",
  14649. {}});
  14650. providers.push_back({"name4",
  14651. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14652. // test the offset is given correctly at each step
  14653. if (!offset)
  14654. sink.os.write(rand2.data(), 2000);
  14655. else if (offset == 2000)
  14656. sink.os.write(rand2.data() + 2000, 1);
  14657. else if (offset == 2001)
  14658. sink.os.write(rand2.data() + 2001, 999);
  14659. else if (offset == rand2.size())
  14660. sink.done();
  14661. return true;
  14662. },
  14663. "filename4",
  14664. {}});
  14665. {
  14666. auto res = cli.Post("/post-providers", {}, {}, providers);
  14667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14668. ASSERT_EQ(StatusCode::OK_200, res->status);
  14669. }
  14670. {
  14671. auto res = cli.Post("/post-both", {}, items, providers);
  14672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14673. ASSERT_EQ(StatusCode::OK_200, res->status);
  14674. }
  14675. }
  14676. }
  14677. TEST(MultipartFormDataTest, BadHeader) {
  14678. Server svr;
  14679. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14680. res.set_content("ok", "text/plain");
  14681. });
  14682. thread t = thread([&] { svr.listen(HOST, PORT); });
  14683. auto se = detail::scope_exit([&] {
  14684. svr.stop();
  14685. t.join();
  14686. ASSERT_FALSE(svr.is_running());
  14687. });
  14688. svr.wait_until_ready();
  14689. const std::string body =
  14690. "This is the preamble. It is to be ignored, though it\r\n"
  14691. "is a handy place for composition agents to include an\r\n"
  14692. "explanatory note to non-MIME conformant readers.\r\n"
  14693. "\r\n"
  14694. "\r\n"
  14695. "--simple boundary\r\n"
  14696. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14697. ": BAD...\r\n"
  14698. "\r\n"
  14699. "value1\r\n"
  14700. "--simple boundary\r\n"
  14701. "Content-Disposition: form-data; name=\"field2\"; "
  14702. "filename=\"example.txt\"\r\n"
  14703. "\r\n"
  14704. "value2\r\n"
  14705. "--simple boundary--\r\n"
  14706. "This is the epilogue. It is also to be ignored.\r\n";
  14707. std::string content_type =
  14708. R"(multipart/form-data; boundary="simple boundary")";
  14709. Client cli(HOST, PORT);
  14710. auto res = cli.Post("/post", body, content_type.c_str());
  14711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14712. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14713. }
  14714. TEST(MultipartFormDataTest, WithPreamble) {
  14715. Server svr;
  14716. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14717. res.set_content("ok", "text/plain");
  14718. });
  14719. thread t = thread([&] { svr.listen(HOST, PORT); });
  14720. auto se = detail::scope_exit([&] {
  14721. svr.stop();
  14722. t.join();
  14723. ASSERT_FALSE(svr.is_running());
  14724. });
  14725. svr.wait_until_ready();
  14726. const std::string body =
  14727. "This is the preamble. It is to be ignored, though it\r\n"
  14728. "is a handy place for composition agents to include an\r\n"
  14729. "explanatory note to non-MIME conformant readers.\r\n"
  14730. "\r\n"
  14731. "\r\n"
  14732. "--simple boundary\r\n"
  14733. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14734. "\r\n"
  14735. "value1\r\n"
  14736. "--simple boundary\r\n"
  14737. "Content-Disposition: form-data; name=\"field2\"; "
  14738. "filename=\"example.txt\"\r\n"
  14739. "\r\n"
  14740. "value2\r\n"
  14741. "--simple boundary--\r\n"
  14742. "This is the epilogue. It is also to be ignored.\r\n";
  14743. std::string content_type =
  14744. R"(multipart/form-data; boundary="simple boundary")";
  14745. Client cli(HOST, PORT);
  14746. auto res = cli.Post("/post", body, content_type.c_str());
  14747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14748. EXPECT_EQ(StatusCode::OK_200, res->status);
  14749. }
  14750. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14751. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14752. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14753. const ContentReader &content_reader) {
  14754. if (req.is_multipart_form_data()) {
  14755. std::vector<FormData> items;
  14756. content_reader(
  14757. [&](const FormData &file) {
  14758. items.push_back(file);
  14759. return true;
  14760. },
  14761. [&](const char *data, size_t data_length) {
  14762. items.back().content.append(data, data_length);
  14763. return true;
  14764. });
  14765. EXPECT_TRUE(std::string(items[0].name) == "document");
  14766. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14767. EXPECT_TRUE(items[0].filename == "2MB_data");
  14768. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14769. EXPECT_TRUE(items[1].name == "hello");
  14770. EXPECT_TRUE(items[1].content == "world");
  14771. EXPECT_TRUE(items[1].filename == "");
  14772. EXPECT_TRUE(items[1].content_type == "");
  14773. } else {
  14774. std::string body;
  14775. content_reader([&](const char *data, size_t data_length) {
  14776. body.append(data, data_length);
  14777. return true;
  14778. });
  14779. }
  14780. });
  14781. auto port = svr.bind_to_any_port("localhost");
  14782. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14783. auto se = detail::scope_exit([&] {
  14784. svr.stop();
  14785. t.join();
  14786. ASSERT_FALSE(svr.is_running());
  14787. });
  14788. svr.wait_until_ready();
  14789. {
  14790. std::string data(1024 * 1024 * 2, '.');
  14791. std::stringstream buffer;
  14792. buffer << data;
  14793. SSLClient cli("localhost", port);
  14794. cli.enable_server_certificate_verification(false);
  14795. UploadFormDataItems items{
  14796. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14797. {"hello", "world", "", ""},
  14798. };
  14799. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14801. ASSERT_EQ(StatusCode::OK_200, res->status);
  14802. }
  14803. }
  14804. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14805. std::string data(1024 * 1024 * 2, '&');
  14806. std::stringstream buffer;
  14807. buffer << data;
  14808. Client cli("https://localhost:8080");
  14809. UploadFormDataItems items{
  14810. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14811. {"hello", "world", "", ""},
  14812. };
  14813. for (const char &c : " \t\r\n") {
  14814. auto res =
  14815. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14816. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14817. ASSERT_FALSE(res);
  14818. }
  14819. }
  14820. TEST(MultipartFormDataTest, PutFormData) {
  14821. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14822. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14823. const ContentReader &content_reader) {
  14824. if (req.is_multipart_form_data()) {
  14825. std::vector<FormData> items;
  14826. content_reader(
  14827. [&](const FormData &file) {
  14828. items.push_back(file);
  14829. return true;
  14830. },
  14831. [&](const char *data, size_t data_length) {
  14832. items.back().content.append(data, data_length);
  14833. return true;
  14834. });
  14835. EXPECT_TRUE(std::string(items[0].name) == "document");
  14836. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14837. EXPECT_TRUE(items[0].filename == "2MB_data");
  14838. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14839. EXPECT_TRUE(items[1].name == "hello");
  14840. EXPECT_TRUE(items[1].content == "world");
  14841. EXPECT_TRUE(items[1].filename == "");
  14842. EXPECT_TRUE(items[1].content_type == "");
  14843. } else {
  14844. std::string body;
  14845. content_reader([&](const char *data, size_t data_length) {
  14846. body.append(data, data_length);
  14847. return true;
  14848. });
  14849. }
  14850. });
  14851. auto port = svr.bind_to_any_port("localhost");
  14852. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14853. auto se = detail::scope_exit([&] {
  14854. svr.stop();
  14855. t.join();
  14856. ASSERT_FALSE(svr.is_running());
  14857. });
  14858. svr.wait_until_ready();
  14859. {
  14860. std::string data(1024 * 1024 * 2, '&');
  14861. std::stringstream buffer;
  14862. buffer << data;
  14863. SSLClient cli("localhost", port);
  14864. cli.enable_server_certificate_verification(false);
  14865. UploadFormDataItems items{
  14866. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14867. {"hello", "world", "", ""},
  14868. };
  14869. auto res = cli.Put("/put", items);
  14870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14871. ASSERT_EQ(StatusCode::OK_200, res->status);
  14872. }
  14873. }
  14874. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14875. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14876. svr.Put("/put_customboundary",
  14877. [&](const Request &req, const Response & /*res*/,
  14878. const ContentReader &content_reader) {
  14879. if (req.is_multipart_form_data()) {
  14880. std::vector<FormData> items;
  14881. content_reader(
  14882. [&](const FormData &file) {
  14883. items.push_back(file);
  14884. return true;
  14885. },
  14886. [&](const char *data, size_t data_length) {
  14887. items.back().content.append(data, data_length);
  14888. return true;
  14889. });
  14890. EXPECT_TRUE(std::string(items[0].name) == "document");
  14891. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14892. EXPECT_TRUE(items[0].filename == "2MB_data");
  14893. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14894. EXPECT_TRUE(items[1].name == "hello");
  14895. EXPECT_TRUE(items[1].content == "world");
  14896. EXPECT_TRUE(items[1].filename == "");
  14897. EXPECT_TRUE(items[1].content_type == "");
  14898. } else {
  14899. std::string body;
  14900. content_reader([&](const char *data, size_t data_length) {
  14901. body.append(data, data_length);
  14902. return true;
  14903. });
  14904. }
  14905. });
  14906. auto port = svr.bind_to_any_port("localhost");
  14907. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14908. auto se = detail::scope_exit([&] {
  14909. svr.stop();
  14910. t.join();
  14911. ASSERT_FALSE(svr.is_running());
  14912. });
  14913. svr.wait_until_ready();
  14914. {
  14915. std::string data(1024 * 1024 * 2, '&');
  14916. std::stringstream buffer;
  14917. buffer << data;
  14918. SSLClient cli("localhost", port);
  14919. cli.enable_server_certificate_verification(false);
  14920. UploadFormDataItems items{
  14921. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14922. {"hello", "world", "", ""},
  14923. };
  14924. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14926. ASSERT_EQ(StatusCode::OK_200, res->status);
  14927. }
  14928. }
  14929. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14930. std::string data(1024 * 1024 * 2, '&');
  14931. std::stringstream buffer;
  14932. buffer << data;
  14933. Client cli("https://localhost:8080");
  14934. cli.enable_server_certificate_verification(false);
  14935. UploadFormDataItems items{
  14936. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14937. {"hello", "world", "", ""},
  14938. };
  14939. for (const char &c : " \t\r\n") {
  14940. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14941. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14942. ASSERT_FALSE(res);
  14943. }
  14944. }
  14945. TEST(MultipartFormDataTest, AlternateFilename) {
  14946. auto handled = false;
  14947. Server svr;
  14948. svr.Post("/test", [&](const Request &req, Response &res) {
  14949. ASSERT_EQ(2u, req.form.files.size());
  14950. ASSERT_EQ(1u, req.form.fields.size());
  14951. // Test files
  14952. const auto &file1 = req.form.get_file("file1");
  14953. ASSERT_EQ("file1", file1.name);
  14954. ASSERT_EQ("A.txt", file1.filename);
  14955. ASSERT_EQ("text/plain", file1.content_type);
  14956. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14957. const auto &file2 = req.form.get_file("file2");
  14958. ASSERT_EQ("file2", file2.name);
  14959. ASSERT_EQ("a.html", file2.filename);
  14960. ASSERT_EQ("text/html", file2.content_type);
  14961. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14962. file2.content);
  14963. // Test text field
  14964. const auto &text = req.form.get_field("text");
  14965. ASSERT_EQ("text default", text);
  14966. res.set_content("ok", "text/plain");
  14967. handled = true;
  14968. });
  14969. thread t = thread([&] { svr.listen(HOST, PORT); });
  14970. auto se = detail::scope_exit([&] {
  14971. svr.stop();
  14972. t.join();
  14973. ASSERT_FALSE(svr.is_running());
  14974. ASSERT_TRUE(handled);
  14975. });
  14976. svr.wait_until_ready();
  14977. auto req = "POST /test HTTP/1.1\r\n"
  14978. "Host: localhost\r\n"
  14979. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14980. "Content-Length: 399\r\n"
  14981. "\r\n"
  14982. "----------\r\n"
  14983. "Content-Disposition: form-data; name=\"text\"\r\n"
  14984. "\r\n"
  14985. "text default\r\n"
  14986. "----------\r\n"
  14987. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14988. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14989. "Content-Type: text/plain\r\n"
  14990. "\r\n"
  14991. "Content of a.txt.\r\n"
  14992. "\r\n"
  14993. "----------\r\n"
  14994. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14995. "\"a.html\"\r\n"
  14996. "Content-Type: text/html\r\n"
  14997. "\r\n"
  14998. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14999. "\r\n"
  15000. "------------\r\n";
  15001. ASSERT_TRUE(send_request(1, req));
  15002. }
  15003. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15004. auto handled = false;
  15005. Server svr;
  15006. svr.Post("/test", [&](const Request &req, Response &res) {
  15007. // Case-insensitive "utf-8''" prefix with a long value
  15008. const auto &file = req.form.get_file("file1");
  15009. ASSERT_EQ("file1", file.name);
  15010. // 8000 chars exercises both the Content-Disposition parser and the
  15011. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15012. // Prior to the fix, std::regex_match on this header would cause O(N)
  15013. // stack recursion in libstdc++, leading to SIGSEGV.
  15014. std::string expected_filename(8000, 'A');
  15015. ASSERT_EQ(expected_filename, file.filename);
  15016. res.set_content("ok", "text/plain");
  15017. handled = true;
  15018. });
  15019. thread t = thread([&] { svr.listen(HOST, PORT); });
  15020. auto se = detail::scope_exit([&] {
  15021. svr.stop();
  15022. t.join();
  15023. ASSERT_FALSE(svr.is_running());
  15024. ASSERT_TRUE(handled);
  15025. });
  15026. svr.wait_until_ready();
  15027. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15028. // Regression test for GHSA-qq6v-r583-3h69
  15029. std::string long_filename(8000, 'A');
  15030. std::string body = "----------\r\n"
  15031. "Content-Disposition: form-data; name=\"file1\"; "
  15032. "filename*=\"Utf-8''" +
  15033. long_filename +
  15034. "\"\r\n"
  15035. "\r\n"
  15036. "hello\r\n"
  15037. "------------\r\n";
  15038. auto req = "POST /test HTTP/1.1\r\n"
  15039. "Host: localhost\r\n"
  15040. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15041. "Content-Length: " +
  15042. std::to_string(body.size()) + "\r\n\r\n" + body;
  15043. ASSERT_TRUE(send_request(1, req));
  15044. }
  15045. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15046. auto handled = false;
  15047. Server svr;
  15048. svr.Post("/test", [&](const Request &req, Response &) {
  15049. ASSERT_EQ(2u, req.form.fields.size());
  15050. const auto &text1 = req.form.get_field("text1");
  15051. ASSERT_EQ("text1", text1);
  15052. const auto &text2 = req.form.get_field("text2");
  15053. ASSERT_EQ("text2", text2);
  15054. handled = true;
  15055. });
  15056. thread t = thread([&] { svr.listen(HOST, PORT); });
  15057. auto se = detail::scope_exit([&] {
  15058. svr.stop();
  15059. t.join();
  15060. ASSERT_FALSE(svr.is_running());
  15061. ASSERT_TRUE(handled);
  15062. });
  15063. svr.wait_until_ready();
  15064. auto req = "POST /test HTTP/1.1\r\n"
  15065. "Host: localhost\r\n"
  15066. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15067. "Content-Length: 146\r\n"
  15068. "\r\n----------\r\n"
  15069. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15070. "\r\n"
  15071. "text1"
  15072. "\r\n----------\r\n"
  15073. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15074. "\r\n"
  15075. "text2"
  15076. "\r\n------------";
  15077. std::string response;
  15078. ASSERT_TRUE(send_request(1, req, &response));
  15079. ASSERT_EQ("200", response.substr(9, 3));
  15080. }
  15081. TEST(MultipartFormDataTest, ContentLength) {
  15082. auto handled = false;
  15083. Server svr;
  15084. svr.Post("/test", [&](const Request &req, Response &) {
  15085. ASSERT_EQ(2u, req.form.fields.size());
  15086. const auto &text1 = req.form.get_field("text1");
  15087. ASSERT_EQ("text1", text1);
  15088. const auto &text2 = req.form.get_field("text2");
  15089. ASSERT_EQ("text2", text2);
  15090. handled = true;
  15091. });
  15092. thread t = thread([&] { svr.listen(HOST, PORT); });
  15093. auto se = detail::scope_exit([&] {
  15094. svr.stop();
  15095. t.join();
  15096. ASSERT_FALSE(svr.is_running());
  15097. ASSERT_TRUE(handled);
  15098. });
  15099. svr.wait_until_ready();
  15100. auto req = "POST /test HTTP/1.1\r\n"
  15101. "Host: localhost\r\n"
  15102. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15103. "Content-Length: 167\r\n"
  15104. "\r\n----------\r\n"
  15105. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15106. "Content-Length: 5\r\n"
  15107. "\r\n"
  15108. "text1"
  15109. "\r\n----------\r\n"
  15110. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15111. "\r\n"
  15112. "text2"
  15113. "\r\n------------\r\n";
  15114. std::string response;
  15115. ASSERT_TRUE(send_request(1, req, &response));
  15116. ASSERT_EQ("200", response.substr(9, 3));
  15117. }
  15118. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15119. auto handled = false;
  15120. Server svr;
  15121. svr.Post("/test", [&](const Request &req, Response &) {
  15122. ASSERT_EQ(2u, req.form.fields.size());
  15123. const auto &text1 = req.form.get_field("text1");
  15124. ASSERT_EQ("text1", text1);
  15125. // TODO: Add header access for text fields if needed
  15126. const auto &text2 = req.form.get_field("text2");
  15127. ASSERT_EQ("text2", text2);
  15128. // TODO: Header access for text fields needs to be implemented
  15129. // auto &headers = it->second.headers;
  15130. // ASSERT_EQ(3U, headers.size());
  15131. // auto custom_header = headers.find("x-whatever");
  15132. // ASSERT_TRUE(custom_header != headers.end());
  15133. // ASSERT_NE("customvalue", custom_header->second);
  15134. // ASSERT_EQ("CustomValue", custom_header->second);
  15135. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15136. handled = true;
  15137. });
  15138. thread t = thread([&] { svr.listen(HOST, PORT); });
  15139. auto se = detail::scope_exit([&] {
  15140. svr.stop();
  15141. t.join();
  15142. ASSERT_FALSE(svr.is_running());
  15143. ASSERT_TRUE(handled);
  15144. });
  15145. svr.wait_until_ready();
  15146. auto req = "POST /test HTTP/1.1\r\n"
  15147. "Host: localhost\r\n"
  15148. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15149. "Content-Length: 232\r\n"
  15150. "\r\n----------\r\n"
  15151. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15152. "Content-Length: 5\r\n"
  15153. "X-Test: 1\r\n"
  15154. "\r\n"
  15155. "text1"
  15156. "\r\n----------\r\n"
  15157. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15158. "Content-Type: text/plain\r\n"
  15159. "X-Whatever: CustomValue\r\n"
  15160. "\r\n"
  15161. "text2"
  15162. "\r\n------------\r\n"
  15163. "That should be disregarded. Not even read";
  15164. std::string response;
  15165. ASSERT_TRUE(send_request(1, req, &response));
  15166. ASSERT_EQ("200", response.substr(9, 3));
  15167. }
  15168. TEST(MultipartFormDataTest, LargeHeader) {
  15169. auto handled = false;
  15170. Server svr;
  15171. svr.Post("/test", [&](const Request &req, Response &) {
  15172. ASSERT_EQ(1u, req.form.fields.size());
  15173. const auto &text = req.form.get_field("name1");
  15174. ASSERT_EQ("text1", text);
  15175. handled = true;
  15176. });
  15177. thread t = thread([&] { svr.listen(HOST, PORT); });
  15178. auto se = detail::scope_exit([&] {
  15179. svr.stop();
  15180. t.join();
  15181. ASSERT_FALSE(svr.is_running());
  15182. ASSERT_TRUE(handled);
  15183. });
  15184. svr.wait_until_ready();
  15185. auto boundary = std::string("cpp-httplib-multipart-data");
  15186. std::string content = "--" + boundary +
  15187. "\r\n"
  15188. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15189. "\r\n"
  15190. "text1\r\n"
  15191. "--" +
  15192. boundary + "--\r\n";
  15193. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15194. "Host: localhost\r\n"
  15195. "Content-Type: multipart/form-data;boundary=" +
  15196. boundary +
  15197. "\r\n"
  15198. "Content-Length: " +
  15199. std::to_string(content.size()) +
  15200. "\r\n"
  15201. "Dummy-Header: ";
  15202. std::string header_suffix = "\r\n"
  15203. "\r\n";
  15204. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  15205. size_t header_dummy_size =
  15206. read_buff_size -
  15207. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  15208. auto header_dummy = std::string(header_dummy_size, '@');
  15209. auto req = header_prefix + header_dummy + header_suffix + content;
  15210. std::string response;
  15211. ASSERT_TRUE(send_request(1, req, &response));
  15212. ASSERT_EQ("200", response.substr(9, 3));
  15213. }
  15214. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  15215. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  15216. // (not chunked Transfer-Encoding) after the streaming refactor.
  15217. auto handled = false;
  15218. Server svr;
  15219. svr.Post("/upload", [&](const Request &req, Response &res) {
  15220. auto cl_it = req.headers.find("Content-Length");
  15221. EXPECT_TRUE(cl_it != req.headers.end());
  15222. auto te_it = req.headers.find("Transfer-Encoding");
  15223. EXPECT_TRUE(te_it == req.headers.end());
  15224. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15225. res.set_content("ok", "text/plain");
  15226. handled = true;
  15227. });
  15228. auto port = svr.bind_to_any_port(HOST);
  15229. auto t = thread([&] { svr.listen_after_bind(); });
  15230. auto se = detail::scope_exit([&] {
  15231. svr.stop();
  15232. t.join();
  15233. ASSERT_FALSE(svr.is_running());
  15234. ASSERT_TRUE(handled);
  15235. });
  15236. svr.wait_until_ready();
  15237. UploadFormDataItems items = {
  15238. {"field1", "hello", "", "text/plain"},
  15239. {"file1", "world", "test.txt", "application/octet-stream"},
  15240. };
  15241. Client cli(HOST, port);
  15242. auto res = cli.Post("/upload", {}, items);
  15243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15244. EXPECT_EQ(StatusCode::OK_200, res->status);
  15245. }
  15246. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  15247. // Verify that make_multipart_content_provider coalesces many small segments
  15248. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  15249. constexpr size_t kItemCount = 1000;
  15250. UploadFormDataItems items;
  15251. items.reserve(kItemCount);
  15252. for (size_t i = 0; i < kItemCount; i++) {
  15253. items.push_back(
  15254. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15255. }
  15256. const std::string boundary = "----test-boundary";
  15257. auto content_length = detail::get_multipart_content_length(items, boundary);
  15258. auto provider = detail::make_multipart_content_provider(items, boundary);
  15259. // Drive the provider the same way write_content_with_progress does
  15260. size_t write_count = 0;
  15261. size_t total_bytes = 0;
  15262. DataSink sink;
  15263. size_t offset = 0;
  15264. sink.write = [&](const char *d, size_t l) -> bool {
  15265. (void)d;
  15266. write_count++;
  15267. total_bytes += l;
  15268. offset += l;
  15269. return true;
  15270. };
  15271. sink.is_writable = []() -> bool { return true; };
  15272. while (offset < content_length) {
  15273. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  15274. }
  15275. EXPECT_EQ(content_length, total_bytes);
  15276. // The total number of segments is 3 * kItemCount + 1 = 3001.
  15277. // With buffering into 64KB blocks, write_count should be much smaller.
  15278. auto segment_count = 3 * kItemCount + 1;
  15279. EXPECT_LT(write_count, segment_count / 10);
  15280. }
  15281. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  15282. // Integration test: send many UploadFormDataItems and verify the server
  15283. // receives all of them correctly (#2410).
  15284. constexpr size_t kItemCount = 500;
  15285. auto handled = false;
  15286. Server svr;
  15287. svr.Post("/upload", [&](const Request &req, Response &res) {
  15288. EXPECT_EQ(kItemCount, req.form.fields.size());
  15289. for (size_t i = 0; i < kItemCount; i++) {
  15290. auto key = "field" + std::to_string(i);
  15291. auto val = "value" + std::to_string(i);
  15292. auto it = req.form.fields.find(key);
  15293. if (it != req.form.fields.end()) {
  15294. EXPECT_EQ(val, it->second.content);
  15295. } else {
  15296. ADD_FAILURE() << "Missing field: " << key;
  15297. }
  15298. }
  15299. res.set_content("ok", "text/plain");
  15300. handled = true;
  15301. });
  15302. auto port = svr.bind_to_any_port(HOST);
  15303. auto t = thread([&] { svr.listen_after_bind(); });
  15304. auto se = detail::scope_exit([&] {
  15305. svr.stop();
  15306. t.join();
  15307. ASSERT_FALSE(svr.is_running());
  15308. ASSERT_TRUE(handled);
  15309. });
  15310. svr.wait_until_ready();
  15311. UploadFormDataItems items;
  15312. items.reserve(kItemCount);
  15313. for (size_t i = 0; i < kItemCount; i++) {
  15314. items.push_back(
  15315. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15316. }
  15317. Client cli(HOST, port);
  15318. auto res = cli.Post("/upload", items);
  15319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15320. EXPECT_EQ(StatusCode::OK_200, res->status);
  15321. }
  15322. TEST(MultipartFormDataTest, MakeFileProvider) {
  15323. // Verify make_file_provider sends a file's contents correctly.
  15324. const std::string file_content(4096, 'Z');
  15325. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  15326. {
  15327. std::ofstream ofs(tmp_path, std::ios::binary);
  15328. ofs.write(file_content.data(),
  15329. static_cast<std::streamsize>(file_content.size()));
  15330. }
  15331. auto handled = false;
  15332. Server svr;
  15333. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  15334. const ContentReader &content_reader) {
  15335. ASSERT_TRUE(req.is_multipart_form_data());
  15336. std::vector<FormData> items;
  15337. content_reader(
  15338. [&](const FormData &file) {
  15339. items.push_back(file);
  15340. return true;
  15341. },
  15342. [&](const char *data, size_t data_length) {
  15343. items.back().content.append(data, data_length);
  15344. return true;
  15345. });
  15346. ASSERT_EQ(1u, items.size());
  15347. EXPECT_EQ("myfile", items[0].name);
  15348. EXPECT_EQ("data.bin", items[0].filename);
  15349. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15350. EXPECT_EQ(file_content, items[0].content);
  15351. handled = true;
  15352. });
  15353. auto port = svr.bind_to_any_port(HOST);
  15354. auto t = thread([&] { svr.listen_after_bind(); });
  15355. auto se = detail::scope_exit([&] {
  15356. svr.stop();
  15357. t.join();
  15358. ASSERT_FALSE(svr.is_running());
  15359. ASSERT_TRUE(handled);
  15360. std::remove(tmp_path.c_str());
  15361. });
  15362. svr.wait_until_ready();
  15363. FormDataProviderItems providers;
  15364. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15365. "application/octet-stream"));
  15366. Client cli(HOST, port);
  15367. auto res = cli.Post("/upload", {}, {}, providers);
  15368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15369. EXPECT_EQ(StatusCode::OK_200, res->status);
  15370. }
  15371. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15372. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15373. // (100) headers is rejected with a 400 Bad Request response.
  15374. Server svr;
  15375. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15376. res.set_content("ok", "text/plain");
  15377. });
  15378. thread t = thread([&] { svr.listen(HOST, PORT); });
  15379. auto se = detail::scope_exit([&] {
  15380. svr.stop();
  15381. t.join();
  15382. ASSERT_FALSE(svr.is_running());
  15383. });
  15384. svr.wait_until_ready();
  15385. // Build a multipart part with 101 custom headers (exceeding
  15386. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15387. std::stringstream body;
  15388. body << "--simpleboundary\r\n"
  15389. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15390. for (int i = 0; i < 101; i++) {
  15391. body << "X-Custom-Header-" << i << ": value\r\n";
  15392. }
  15393. body << "\r\n"
  15394. << "value1\r\n"
  15395. << "--simpleboundary--\r\n";
  15396. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15397. Client cli(HOST, PORT);
  15398. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15400. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15401. }
  15402. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15403. // A body that never contains the declared boundary must not be accumulated
  15404. // while the parser waits for it. Buffering it would also make every read
  15405. // rescan everything seen so far, which is quadratic in the body size.
  15406. Server svr;
  15407. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15408. res.set_content("ok", "text/plain");
  15409. });
  15410. auto port = svr.bind_to_any_port(HOST);
  15411. thread t = thread([&] { svr.listen_after_bind(); });
  15412. auto se = detail::scope_exit([&] {
  15413. svr.stop();
  15414. t.join();
  15415. ASSERT_FALSE(svr.is_running());
  15416. });
  15417. svr.wait_until_ready();
  15418. Client cli(HOST, port);
  15419. cli.set_read_timeout(60, 0);
  15420. cli.set_write_timeout(60, 0);
  15421. // '-' is the worst case: it matches the first character of the boundary, so
  15422. // every position has to be checked against it.
  15423. auto post_dashes = [&](size_t size) {
  15424. const std::string body(size, '-');
  15425. auto start = std::chrono::steady_clock::now();
  15426. auto res =
  15427. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15428. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15429. std::chrono::steady_clock::now() - start)
  15430. .count();
  15431. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15432. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15433. return ms;
  15434. };
  15435. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15436. // Windows.
  15437. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15438. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15439. // Comparing the two sizes rather than checking an absolute duration keeps
  15440. // this meaningful across build types and CI load, both of which move the
  15441. // absolute numbers by more than an order of magnitude. Four times the bytes
  15442. // costs about four times the time when parsing is linear, and about sixteen
  15443. // times when the body is buffered and rescanned.
  15444. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15445. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15446. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15447. << "ms, which suggests the body is being buffered and rescanned";
  15448. }
  15449. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15450. // A boundary can only be followed by CRLF or by "--", so anything else is
  15451. // malformed no matter what comes next. The parser must say so right away
  15452. // instead of buffering the rest of the declared body.
  15453. Server svr;
  15454. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15455. res.set_content("ok", "text/plain");
  15456. });
  15457. auto port = svr.bind_to_any_port(HOST);
  15458. thread t = thread([&] { svr.listen_after_bind(); });
  15459. auto se = detail::scope_exit([&] {
  15460. svr.stop();
  15461. t.join();
  15462. ASSERT_FALSE(svr.is_running());
  15463. });
  15464. svr.wait_until_ready();
  15465. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15466. // buffers instead of failing would still be waiting for the remaining bytes.
  15467. const std::string body = "--zzzz\r\n"
  15468. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15469. "\r\n"
  15470. "text1"
  15471. "\r\n--zzzzXX";
  15472. const std::string req = "POST /post HTTP/1.1\r\n"
  15473. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15474. "Content-Length: 1048576\r\n"
  15475. "\r\n" +
  15476. body;
  15477. std::string response;
  15478. ASSERT_TRUE(send_request(3, req, &response, port));
  15479. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15480. EXPECT_EQ("400", response.substr(9, 3));
  15481. }
  15482. // Posts a multipart body split into two writes, so that the server sees the
  15483. // split at whatever offset the caller chose, and expects the single "text1"
  15484. // field to come through.
  15485. static void expect_split_multipart_ok(const std::string &body1,
  15486. const std::string &body2) {
  15487. auto handled = false;
  15488. Server svr;
  15489. svr.Post("/post", [&](const Request &req, Response &) {
  15490. EXPECT_EQ(1u, req.form.fields.size());
  15491. EXPECT_EQ("text1", req.form.get_field("text1"));
  15492. handled = true;
  15493. });
  15494. auto port = svr.bind_to_any_port(HOST);
  15495. thread t = thread([&] { svr.listen_after_bind(); });
  15496. auto se = detail::scope_exit([&] {
  15497. svr.stop();
  15498. t.join();
  15499. ASSERT_FALSE(svr.is_running());
  15500. ASSERT_TRUE(handled);
  15501. });
  15502. svr.wait_until_ready();
  15503. // "Connection: close" makes the server close once it has answered, so the
  15504. // response drain ends immediately instead of idling until the read timeout.
  15505. const std::string head =
  15506. "POST /post HTTP/1.1\r\n"
  15507. "Host: localhost\r\n"
  15508. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15509. "Connection: close\r\n"
  15510. "Content-Length: " +
  15511. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15512. std::string response;
  15513. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15514. ASSERT_GE(response.size(), 12u) << "no response";
  15515. EXPECT_EQ("200", response.substr(9, 3));
  15516. }
  15517. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15518. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15519. // ignored, including when it does not arrive in the same read as the
  15520. // close-delimiter itself.
  15521. expect_split_multipart_ok("--zzzz\r\n"
  15522. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15523. "\r\n"
  15524. "text1"
  15525. "\r\n--zzzz--",
  15526. "\r\nthis epilogue must be ignored\r\n");
  15527. }
  15528. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15529. // The initial boundary may be preceded by a preamble of any length and may
  15530. // straddle a read boundary. Discarding data while waiting for it must not
  15531. // throw away a partial boundary sitting at the end of the buffer.
  15532. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15533. "zz\r\n"
  15534. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15535. "\r\n"
  15536. "text1"
  15537. "\r\n--zzzz--\r\n");
  15538. }
  15539. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15540. // The received boundary was only checked for being non-empty, so it could be
  15541. // as long as a header is allowed to be. The parser scans the body for
  15542. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15543. // costs a nearly full comparison at nearly every position, making the
  15544. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15545. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15546. Server svr;
  15547. svr.Post("/post", [](const Request &req, Response &res) {
  15548. EXPECT_EQ(1u, req.form.fields.size());
  15549. EXPECT_EQ("text1", req.form.get_field("text1"));
  15550. res.set_content("ok", "text/plain");
  15551. });
  15552. auto port = svr.bind_to_any_port(HOST);
  15553. thread t = thread([&] { svr.listen_after_bind(); });
  15554. auto se = detail::scope_exit([&] {
  15555. svr.stop();
  15556. t.join();
  15557. ASSERT_FALSE(svr.is_running());
  15558. });
  15559. svr.wait_until_ready();
  15560. Client cli(HOST, port);
  15561. auto post_with_boundary_of_length = [&](size_t len) {
  15562. const std::string boundary(len, 'a');
  15563. const std::string body =
  15564. "--" + boundary +
  15565. "\r\n"
  15566. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15567. "\r\n"
  15568. "text1"
  15569. "\r\n--" +
  15570. boundary + "--\r\n";
  15571. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15572. };
  15573. auto res = post_with_boundary_of_length(70);
  15574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15575. EXPECT_EQ(StatusCode::OK_200, res->status);
  15576. res = post_with_boundary_of_length(71);
  15577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15578. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15579. }
  15580. TEST(MakeFileBodyTest, Basic) {
  15581. const std::string file_content(4096, 'Z');
  15582. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15583. {
  15584. std::ofstream ofs(tmp_path, std::ios::binary);
  15585. ofs.write(file_content.data(),
  15586. static_cast<std::streamsize>(file_content.size()));
  15587. }
  15588. auto handled = false;
  15589. Server svr;
  15590. svr.Post("/upload", [&](const Request &req, Response &res) {
  15591. EXPECT_EQ(file_content, req.body);
  15592. handled = true;
  15593. res.status = StatusCode::OK_200;
  15594. });
  15595. auto port = svr.bind_to_any_port(HOST);
  15596. auto t = thread([&] { svr.listen_after_bind(); });
  15597. auto se = detail::scope_exit([&] {
  15598. svr.stop();
  15599. t.join();
  15600. ASSERT_FALSE(svr.is_running());
  15601. ASSERT_TRUE(handled);
  15602. std::remove(tmp_path.c_str());
  15603. });
  15604. svr.wait_until_ready();
  15605. auto fb = make_file_body(tmp_path);
  15606. ASSERT_GT(fb.first, 0u);
  15607. Client cli(HOST, port);
  15608. auto res =
  15609. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15611. EXPECT_EQ(StatusCode::OK_200, res->status);
  15612. }
  15613. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15614. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15615. {
  15616. std::ofstream ofs(path, std::ios::binary);
  15617. const std::string content(100, 'A');
  15618. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15619. }
  15620. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15621. auto body = make_file_body(path);
  15622. ASSERT_EQ(100u, body.first);
  15623. ASSERT_TRUE(static_cast<bool>(body.second));
  15624. // Rewritten shorter after its length was measured - and, on a server, after
  15625. // that length has already gone out as Content-Length.
  15626. {
  15627. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15628. const std::string content(10, 'A');
  15629. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15630. }
  15631. std::string written;
  15632. DataSink sink;
  15633. sink.write = [&](const char *d, size_t l) {
  15634. written.append(d, l);
  15635. return true;
  15636. };
  15637. // The provider has to report failure. write_content_with_progress() advances
  15638. // its offset only by what was written, so a provider that returns true
  15639. // without completing the length it promised is called again straight away,
  15640. // and again.
  15641. EXPECT_FALSE(body.second(0, body.first, sink));
  15642. EXPECT_EQ(std::string(10, 'A'), written);
  15643. }
  15644. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15645. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15646. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15647. {
  15648. std::ofstream ofs(path, std::ios::binary);
  15649. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15650. }
  15651. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15652. auto body = make_file_body(path);
  15653. ASSERT_EQ(content.size(), body.first);
  15654. ASSERT_TRUE(static_cast<bool>(body.second));
  15655. std::string written;
  15656. DataSink sink;
  15657. sink.write = [&](const char *d, size_t l) {
  15658. written.append(d, l);
  15659. return true;
  15660. };
  15661. EXPECT_TRUE(body.second(0, body.first, sink));
  15662. EXPECT_EQ(content, written);
  15663. }
  15664. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15665. static constexpr unsigned int number_of_tasks{1000000};
  15666. std::atomic_uint count{0};
  15667. std::unique_ptr<TaskQueue> task_queue{
  15668. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15669. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15670. auto queued = task_queue->enqueue(
  15671. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15672. EXPECT_TRUE(queued);
  15673. }
  15674. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15675. task_queue->shutdown();
  15676. #else
  15677. EXPECT_NO_THROW(task_queue->shutdown());
  15678. #endif
  15679. EXPECT_EQ(number_of_tasks, count.load());
  15680. }
  15681. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15682. static constexpr unsigned int number_of_tasks{1000000};
  15683. static constexpr unsigned int qlimit{2};
  15684. unsigned int queued_count{0};
  15685. std::atomic_uint count{0};
  15686. std::unique_ptr<TaskQueue> task_queue{
  15687. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15688. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15689. if (task_queue->enqueue(
  15690. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15691. queued_count++;
  15692. }
  15693. }
  15694. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15695. task_queue->shutdown();
  15696. #else
  15697. EXPECT_NO_THROW(task_queue->shutdown());
  15698. #endif
  15699. EXPECT_EQ(queued_count, count.load());
  15700. EXPECT_TRUE(queued_count <= number_of_tasks);
  15701. EXPECT_TRUE(queued_count >= qlimit);
  15702. }
  15703. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15704. // Use a short idle timeout so a dynamic thread spawns, times out and
  15705. // exits during the test, and the pool keeps working afterwards.
  15706. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15707. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15708. /*idle_timeout_sec=*/1}};
  15709. std::atomic_uint count{0};
  15710. std::condition_variable cv;
  15711. std::mutex mtx;
  15712. bool release = false;
  15713. // Block the base thread so the second task spawns a dynamic thread.
  15714. EXPECT_TRUE(task_queue->enqueue([&] {
  15715. std::unique_lock<std::mutex> lock(mtx);
  15716. while (!release) {
  15717. cv.wait(lock);
  15718. }
  15719. count++;
  15720. }));
  15721. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15722. // Let the dynamic thread finish its task and exceed the idle timeout.
  15723. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15724. {
  15725. std::unique_lock<std::mutex> lock(mtx);
  15726. release = true;
  15727. }
  15728. cv.notify_all();
  15729. // The pool must still accept and run tasks after the dynamic thread exited.
  15730. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15731. task_queue->shutdown();
  15732. EXPECT_EQ(3u, count.load());
  15733. }
  15734. TEST(TaskQueueTest, MaxQueuedRequests) {
  15735. static constexpr unsigned int qlimit{3};
  15736. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15737. std::condition_variable sem_cv;
  15738. std::mutex sem_mtx;
  15739. int credits = 0;
  15740. bool queued;
  15741. /* Fill up the queue with tasks that will block until we give them credits to
  15742. * complete. */
  15743. for (unsigned int n = 0; n <= qlimit;) {
  15744. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15745. std::unique_lock<std::mutex> lock(sem_mtx);
  15746. while (credits <= 0) {
  15747. sem_cv.wait(lock);
  15748. }
  15749. /* Consume the credit and signal the test code if they are all gone. */
  15750. if (--credits == 0) { sem_cv.notify_one(); }
  15751. });
  15752. if (n < qlimit) {
  15753. /* The first qlimit enqueues must succeed. */
  15754. EXPECT_TRUE(queued);
  15755. } else {
  15756. /* The last one will succeed only when the worker thread
  15757. * starts and dequeues the first blocking task. Although
  15758. * not necessary for the correctness of this test, we sleep for
  15759. * a short while to avoid busy waiting. */
  15760. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15761. }
  15762. if (queued) { n++; }
  15763. }
  15764. /* Further enqueues must fail since the queue is full. */
  15765. for (auto i = 0; i < 4; i++) {
  15766. queued = task_queue->enqueue([] {});
  15767. EXPECT_FALSE(queued);
  15768. }
  15769. /* Give the credits to allow the previous tasks to complete. */
  15770. {
  15771. std::unique_lock<std::mutex> lock(sem_mtx);
  15772. credits += qlimit + 1;
  15773. }
  15774. sem_cv.notify_all();
  15775. /* Wait for all the credits to be consumed. */
  15776. {
  15777. std::unique_lock<std::mutex> lock(sem_mtx);
  15778. while (credits > 0) {
  15779. sem_cv.wait(lock);
  15780. }
  15781. }
  15782. /* Check that we are able again to enqueue at least qlimit tasks. */
  15783. for (unsigned int i = 0; i < qlimit; i++) {
  15784. queued = task_queue->enqueue([] {});
  15785. EXPECT_TRUE(queued);
  15786. }
  15787. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15788. task_queue->shutdown();
  15789. #else
  15790. EXPECT_NO_THROW(task_queue->shutdown());
  15791. #endif
  15792. }
  15793. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15794. Server svr;
  15795. std::string method;
  15796. std::string body;
  15797. auto has_content_length = false;
  15798. auto has_transfer_encoding = false;
  15799. std::atomic<int> bad_requests{0};
  15800. // Leftover body bytes get parsed as a malformed request and answered with
  15801. // 400
  15802. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15803. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15804. });
  15805. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15806. res.set_redirect("/down", StatusCode::SeeOther_303);
  15807. });
  15808. svr.Get("/down", [&](const Request &req, Response &res) {
  15809. method = req.method;
  15810. body = req.body;
  15811. has_content_length = req.has_header("Content-Length");
  15812. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15813. res.set_content("ok", "text/plain");
  15814. });
  15815. auto port = svr.bind_to_any_port(HOST);
  15816. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15817. auto se = detail::scope_exit([&] {
  15818. svr.stop();
  15819. thread.join();
  15820. ASSERT_FALSE(svr.is_running());
  15821. });
  15822. svr.wait_until_ready();
  15823. const std::string payload = "SECRET-BODY";
  15824. auto check = [&](Client &cli, const Result &res) {
  15825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15826. EXPECT_EQ(StatusCode::OK_200, res->status);
  15827. EXPECT_EQ("ok", res->body);
  15828. EXPECT_EQ("GET", method);
  15829. EXPECT_TRUE(body.empty());
  15830. EXPECT_FALSE(has_content_length);
  15831. EXPECT_FALSE(has_transfer_encoding);
  15832. // Nothing of the original body may be left on the connection
  15833. auto res2 = cli.Get("/down");
  15834. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15835. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15836. EXPECT_EQ("ok", res2->body);
  15837. EXPECT_EQ(0, bad_requests);
  15838. };
  15839. // With content length
  15840. {
  15841. Client cli(HOST, port);
  15842. cli.set_keep_alive(true);
  15843. cli.set_follow_location(true);
  15844. auto res = cli.Post(
  15845. "/up", payload.size(),
  15846. [&](size_t offset, size_t length, DataSink &sink) {
  15847. return sink.write(payload.data() + offset, length);
  15848. },
  15849. "text/plain");
  15850. check(cli, res);
  15851. }
  15852. // Without content length (chunked)
  15853. {
  15854. Client cli(HOST, port);
  15855. cli.set_keep_alive(true);
  15856. cli.set_follow_location(true);
  15857. auto res = cli.Post(
  15858. "/up",
  15859. [&](size_t /*offset*/, DataSink &sink) {
  15860. sink.write(payload.data(), payload.size());
  15861. sink.done();
  15862. return true;
  15863. },
  15864. "text/plain");
  15865. check(cli, res);
  15866. }
  15867. }
  15868. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15869. Server svr;
  15870. std::string target;
  15871. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15872. // Echo the still-encoded name back in the Location
  15873. const std::string prefix = "/start/";
  15874. res.status = StatusCode::Found_302;
  15875. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15876. });
  15877. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15878. target = req.target;
  15879. res.set_content("ok", "text/plain");
  15880. });
  15881. auto port = svr.bind_to_any_port(HOST);
  15882. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15883. auto se = detail::scope_exit([&] {
  15884. svr.stop();
  15885. thread.join();
  15886. ASSERT_FALSE(svr.is_running());
  15887. });
  15888. svr.wait_until_ready();
  15889. // Decoding the Location path would turn the first four into a path
  15890. // separator, a query delimiter, a fragment delimiter and a different
  15891. // percent-encoded octet. The rest must keep reaching the server as they are.
  15892. const std::vector<std::string> names = {
  15893. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15894. };
  15895. for (auto path_encode : {true, false}) {
  15896. Client cli(HOST, port);
  15897. cli.set_follow_location(true);
  15898. cli.set_path_encode(path_encode);
  15899. for (const auto &name : names) {
  15900. target.clear();
  15901. auto res = cli.Get("/start/" + name);
  15902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15903. EXPECT_EQ(StatusCode::OK_200, res->status);
  15904. EXPECT_EQ("/dest/" + name, target);
  15905. }
  15906. }
  15907. }
  15908. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15909. Server svr;
  15910. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15911. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15912. });
  15913. svr.Get("/hello", [](const Request &req, Response &res) {
  15914. res.set_content(req.get_param_value("key"), "text/plain");
  15915. });
  15916. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15917. auto se = detail::scope_exit([&] {
  15918. svr.stop();
  15919. thread.join();
  15920. ASSERT_FALSE(svr.is_running());
  15921. });
  15922. svr.wait_until_ready();
  15923. {
  15924. Client cli(HOST, PORT);
  15925. cli.set_follow_location(true);
  15926. auto res = cli.Get("/");
  15927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15928. EXPECT_EQ(StatusCode::OK_200, res->status);
  15929. EXPECT_EQ("val&key2=val2", res->body);
  15930. }
  15931. }
  15932. #endif
  15933. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15934. Server svr;
  15935. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15936. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15937. });
  15938. svr.Get("/hello", [](const Request &req, Response &res) {
  15939. res.set_content(req.get_param_value("key"), "text/plain");
  15940. });
  15941. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15942. auto se = detail::scope_exit([&] {
  15943. svr.stop();
  15944. thread.join();
  15945. ASSERT_FALSE(svr.is_running());
  15946. });
  15947. svr.wait_until_ready();
  15948. {
  15949. Client cli(HOST, PORT);
  15950. cli.set_follow_location(true);
  15951. auto res = cli.Get("/");
  15952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15953. EXPECT_EQ(StatusCode::OK_200, res->status);
  15954. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15955. }
  15956. }
  15957. TEST(RedirectTest, RedirectWithPlusInPath) {
  15958. Server svr;
  15959. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15960. res.set_redirect("/a+b");
  15961. });
  15962. // Route pattern uses regex; escape + as \\+
  15963. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15964. res.set_content(req.path, "text/plain");
  15965. });
  15966. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15967. auto se = detail::scope_exit([&] {
  15968. svr.stop();
  15969. thread.join();
  15970. ASSERT_FALSE(svr.is_running());
  15971. });
  15972. svr.wait_until_ready();
  15973. {
  15974. Client cli(HOST, PORT);
  15975. cli.set_follow_location(true);
  15976. auto res = cli.Get("/");
  15977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15978. EXPECT_EQ(StatusCode::OK_200, res->status);
  15979. EXPECT_EQ("/a+b", res->body);
  15980. }
  15981. }
  15982. TEST(RedirectTest, ResolveRelativeLocation) {
  15983. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15984. const std::vector<std::pair<std::string, std::string>> cases = {
  15985. {"g", "/b/c/g"},
  15986. {"./g", "/b/c/g"},
  15987. {"g/", "/b/c/g/"},
  15988. {"?y", "/b/c/d;p?y"},
  15989. {"g?y", "/b/c/g?y"},
  15990. {"#s", "/b/c/d;p?q#s"},
  15991. {"g#s", "/b/c/g#s"},
  15992. {"g?y#s", "/b/c/g?y#s"},
  15993. {";x", "/b/c/;x"},
  15994. {"g;x", "/b/c/g;x"},
  15995. {".", "/b/c/"},
  15996. {"./", "/b/c/"},
  15997. {"..", "/b/"},
  15998. {"../", "/b/"},
  15999. {"../g", "/b/g"},
  16000. {"../..", "/"},
  16001. {"../../", "/"},
  16002. {"../../g", "/g"},
  16003. {"../../../g", "/g"},
  16004. {"g.", "/b/c/g."},
  16005. {".g", "/b/c/.g"},
  16006. {"g..", "/b/c/g.."},
  16007. {"..g", "/b/c/..g"},
  16008. {"./../g", "/b/g"},
  16009. {"./g/.", "/b/c/g/"},
  16010. {"g/./h", "/b/c/g/h"},
  16011. {"g/../h", "/b/c/h"},
  16012. {"g;x=1/./y", "/b/c/g;x=1/y"},
  16013. {"g;x=1/../y", "/b/c/y"},
  16014. {"g?y/./x", "/b/c/g?y/./x"},
  16015. {"g#s/../x", "/b/c/g#s/../x"},
  16016. // Not relative-path references, so left for parse_url.
  16017. {"/g", "/g"},
  16018. {"//g", "//g"},
  16019. {"http://g/x", "http://g/x"},
  16020. {"g:h", "g:h"},
  16021. };
  16022. for (const auto &c : cases) {
  16023. EXPECT_EQ(c.second,
  16024. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  16025. << c.first;
  16026. }
  16027. }
  16028. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  16029. Server svr;
  16030. svr.Get("/dir/page", [](const Request &req, Response &res) {
  16031. res.set_redirect(req.get_param_value("to"));
  16032. });
  16033. svr.Get("/dir/next", [](const Request &req, Response &res) {
  16034. res.set_content(req.target, "text/plain");
  16035. });
  16036. svr.Get("/other", [](const Request &req, Response &res) {
  16037. res.set_content(req.target, "text/plain");
  16038. });
  16039. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16040. auto se = detail::scope_exit([&] {
  16041. svr.stop();
  16042. thread.join();
  16043. ASSERT_FALSE(svr.is_running());
  16044. });
  16045. svr.wait_until_ready();
  16046. const std::vector<std::pair<std::string, std::string>> cases = {
  16047. {"next", "/dir/next"},
  16048. {"./next?x=1", "/dir/next?x=1"},
  16049. {"../other", "/other"},
  16050. };
  16051. for (const auto &c : cases) {
  16052. Client cli(HOST, PORT);
  16053. cli.set_follow_location(true);
  16054. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  16055. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  16056. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16057. EXPECT_EQ(c.second, res->body) << c.first;
  16058. }
  16059. }
  16060. #ifdef CPPHTTPLIB_SSL_ENABLED
  16061. TEST(RedirectTest, Issue2185_Online) {
  16062. SSLClient client("github.com");
  16063. client.set_follow_location(true);
  16064. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16065. "Coollab-Windows.zip");
  16066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16067. EXPECT_EQ(StatusCode::OK_200, res->status);
  16068. EXPECT_EQ(9920427U, res->body.size());
  16069. }
  16070. #endif
  16071. TEST(VulnerabilityTest, CRLFInjection) {
  16072. Server svr;
  16073. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16074. res.set_content("Hello 1", "text/plain");
  16075. });
  16076. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16077. res.set_content("Hello 2", "text/plain");
  16078. });
  16079. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16080. res.set_content("Hello 3", "text/plain");
  16081. });
  16082. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16083. res.set_content("Hello 4", "text/plain");
  16084. });
  16085. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16086. for (const auto &x : req.headers) {
  16087. auto key = x.first;
  16088. EXPECT_STRNE("evil", key.c_str());
  16089. }
  16090. });
  16091. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16092. auto se = detail::scope_exit([&] {
  16093. svr.stop();
  16094. thread.join();
  16095. ASSERT_FALSE(svr.is_running());
  16096. });
  16097. svr.wait_until_ready();
  16098. {
  16099. Client cli(HOST, PORT);
  16100. cli.Post("/test1", "A=B",
  16101. "application/x-www-form-urlencoded\r\nevil: hello1");
  16102. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16103. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16104. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16105. }
  16106. }
  16107. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16108. auto server_thread = std::thread([] {
  16109. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16110. default_socket_options(srv);
  16111. sockaddr_in addr{};
  16112. addr.sin_family = AF_INET;
  16113. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16114. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16115. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  16116. ::listen(srv, 1);
  16117. sockaddr_in cli_addr{};
  16118. socklen_t cli_len = sizeof(cli_addr);
  16119. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16120. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  16121. std::string buf_all;
  16122. char buf[2048];
  16123. ssize_t n;
  16124. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  16125. buf_all.append(buf, static_cast<size_t>(n));
  16126. size_t pos;
  16127. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  16128. auto request_block = buf_all.substr(0, pos + 4); // include separator
  16129. auto e = request_block.find("\r\n");
  16130. if (e != std::string::npos) {
  16131. auto request_line = request_block.substr(0, e);
  16132. std::string msg =
  16133. "CRLF injection detected in request line: '" + request_line + "'";
  16134. EXPECT_FALSE(true) << msg;
  16135. }
  16136. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  16137. ::send(cli,
  16138. #ifdef _WIN32
  16139. static_cast<const char *>(resp.c_str()),
  16140. static_cast<int>(resp.size()),
  16141. #else
  16142. resp.c_str(), resp.size(),
  16143. #endif
  16144. 0);
  16145. buf_all.erase(0, pos + 4);
  16146. }
  16147. }
  16148. detail::close_socket(cli);
  16149. detail::close_socket(srv);
  16150. });
  16151. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16152. auto cli = Client("127.0.0.1", PORT + 1);
  16153. auto headers = Headers{
  16154. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  16155. {"Connection", "keep-alive"}};
  16156. auto res = cli.Get("/hi", headers);
  16157. EXPECT_FALSE(res);
  16158. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16159. server_thread.join();
  16160. }
  16161. // A request rejected before any byte reaches the socket must fail right away
  16162. // instead of waiting for a response the server will never send.
  16163. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  16164. // The kernel completes the TCP handshake from the listen backlog, so the
  16165. // client connects, but nothing ever reads, responds or closes.
  16166. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16167. default_socket_options(srv);
  16168. sockaddr_in addr{};
  16169. addr.sin_family = AF_INET;
  16170. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16171. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16172. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16173. ASSERT_EQ(0, ::listen(srv, 8));
  16174. auto cli = Client("127.0.0.1", PORT + 1);
  16175. cli.set_read_timeout(10, 0);
  16176. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  16177. return std::chrono::duration_cast<std::chrono::milliseconds>(
  16178. std::chrono::steady_clock::now() - start)
  16179. .count();
  16180. };
  16181. {
  16182. Request req;
  16183. req.method = "GE T";
  16184. req.path = "/";
  16185. auto start = std::chrono::steady_clock::now();
  16186. auto res = cli.send(req);
  16187. EXPECT_FALSE(res);
  16188. EXPECT_EQ(Error::Write, res.error());
  16189. EXPECT_LT(elapsed_ms(start), 1000);
  16190. }
  16191. {
  16192. auto start = std::chrono::steady_clock::now();
  16193. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  16194. EXPECT_FALSE(res);
  16195. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16196. EXPECT_LT(elapsed_ms(start), 1000);
  16197. }
  16198. EXPECT_FALSE(cli.is_socket_open());
  16199. detail::close_socket(srv);
  16200. }
  16201. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  16202. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16203. default_socket_options(srv);
  16204. sockaddr_in addr{};
  16205. addr.sin_family = AF_INET;
  16206. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16207. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16208. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16209. ASSERT_EQ(0, ::listen(srv, 1));
  16210. std::string received;
  16211. auto server_thread = std::thread([&] {
  16212. auto sock = ::accept(srv, nullptr, nullptr);
  16213. if (sock == INVALID_SOCKET) { return; }
  16214. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  16215. char buf[2048];
  16216. ssize_t n;
  16217. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  16218. received.append(buf, static_cast<size_t>(n));
  16219. }
  16220. detail::close_socket(sock);
  16221. });
  16222. {
  16223. auto cli = Client("127.0.0.1", PORT + 1);
  16224. // "Z" sorts after the default headers, so writing straight to the socket
  16225. // would have sent the request line and those headers before the rejection.
  16226. auto handle =
  16227. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  16228. EXPECT_FALSE(handle.is_valid());
  16229. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  16230. }
  16231. server_thread.join();
  16232. detail::close_socket(srv);
  16233. EXPECT_TRUE(received.empty()) << received;
  16234. }
  16235. TEST(PathParamsTest, StaticMatch) {
  16236. const auto pattern = "/users/all";
  16237. detail::PathParamsMatcher matcher(pattern);
  16238. Request request;
  16239. request.path = "/users/all";
  16240. ASSERT_TRUE(matcher.match(request));
  16241. std::unordered_map<std::string, std::string> expected_params = {};
  16242. EXPECT_EQ(request.path_params, expected_params);
  16243. }
  16244. TEST(PathParamsTest, StaticMismatch) {
  16245. const auto pattern = "/users/all";
  16246. detail::PathParamsMatcher matcher(pattern);
  16247. Request request;
  16248. request.path = "/users/1";
  16249. ASSERT_FALSE(matcher.match(request));
  16250. }
  16251. TEST(PathParamsTest, SingleParamInTheMiddle) {
  16252. const auto pattern = "/users/:id/subscriptions";
  16253. detail::PathParamsMatcher matcher(pattern);
  16254. Request request;
  16255. request.path = "/users/42/subscriptions";
  16256. ASSERT_TRUE(matcher.match(request));
  16257. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16258. EXPECT_EQ(request.path_params, expected_params);
  16259. }
  16260. TEST(PathParamsTest, SingleParamInTheEnd) {
  16261. const auto pattern = "/users/:id";
  16262. detail::PathParamsMatcher matcher(pattern);
  16263. Request request;
  16264. request.path = "/users/24";
  16265. ASSERT_TRUE(matcher.match(request));
  16266. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  16267. EXPECT_EQ(request.path_params, expected_params);
  16268. }
  16269. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  16270. const auto pattern = "/users/:id/";
  16271. detail::PathParamsMatcher matcher(pattern);
  16272. Request request;
  16273. request.path = "/users/42/";
  16274. ASSERT_TRUE(matcher.match(request));
  16275. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16276. EXPECT_EQ(request.path_params, expected_params);
  16277. }
  16278. TEST(PathParamsTest, EmptyParam) {
  16279. const auto pattern = "/users/:id/";
  16280. detail::PathParamsMatcher matcher(pattern);
  16281. Request request;
  16282. request.path = "/users//";
  16283. ASSERT_TRUE(matcher.match(request));
  16284. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  16285. EXPECT_EQ(request.path_params, expected_params);
  16286. }
  16287. TEST(PathParamsTest, FragmentMismatch) {
  16288. const auto pattern = "/users/:id/";
  16289. detail::PathParamsMatcher matcher(pattern);
  16290. Request request;
  16291. request.path = "/admins/24/";
  16292. ASSERT_FALSE(matcher.match(request));
  16293. }
  16294. TEST(PathParamsTest, ExtraFragments) {
  16295. const auto pattern = "/users/:id";
  16296. detail::PathParamsMatcher matcher(pattern);
  16297. Request request;
  16298. request.path = "/users/42/subscriptions";
  16299. ASSERT_FALSE(matcher.match(request));
  16300. }
  16301. TEST(PathParamsTest, MissingTrailingParam) {
  16302. const auto pattern = "/users/:id";
  16303. detail::PathParamsMatcher matcher(pattern);
  16304. Request request;
  16305. request.path = "/users";
  16306. ASSERT_FALSE(matcher.match(request));
  16307. }
  16308. TEST(PathParamsTest, MissingParamInTheMiddle) {
  16309. const auto pattern = "/users/:id/subscriptions";
  16310. detail::PathParamsMatcher matcher(pattern);
  16311. Request request;
  16312. request.path = "/users/subscriptions";
  16313. ASSERT_FALSE(matcher.match(request));
  16314. }
  16315. TEST(PathParamsTest, MultipleParams) {
  16316. const auto pattern = "/users/:userid/subscriptions/:subid";
  16317. detail::PathParamsMatcher matcher(pattern);
  16318. Request request;
  16319. request.path = "/users/42/subscriptions/2";
  16320. ASSERT_TRUE(matcher.match(request));
  16321. std::unordered_map<std::string, std::string> expected_params = {
  16322. {"userid", "42"}, {"subid", "2"}};
  16323. EXPECT_EQ(request.path_params, expected_params);
  16324. }
  16325. TEST(PathParamsTest, SequenceOfParams) {
  16326. const auto pattern = "/values/:x/:y/:z";
  16327. detail::PathParamsMatcher matcher(pattern);
  16328. Request request;
  16329. request.path = "/values/1/2/3";
  16330. ASSERT_TRUE(matcher.match(request));
  16331. std::unordered_map<std::string, std::string> expected_params = {
  16332. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  16333. EXPECT_EQ(request.path_params, expected_params);
  16334. }
  16335. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  16336. const auto pattern = "/prefix:suffix";
  16337. detail::PathParamsMatcher matcher(pattern);
  16338. Request request;
  16339. request.path = "/prefix:suffix";
  16340. ASSERT_TRUE(matcher.match(request));
  16341. const std::unordered_map<std::string, std::string> expected_params = {};
  16342. EXPECT_EQ(request.path_params, expected_params);
  16343. }
  16344. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16345. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16346. // calling thread's stack on a long enough path for a quantified pattern;
  16347. // RegexMatcher must refuse to run regex matching on paths beyond
  16348. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16349. detail::RegexMatcher matcher("/files/(.*)");
  16350. Request within_limit;
  16351. within_limit.path = "/files/" + std::string(10, 'A');
  16352. EXPECT_TRUE(matcher.match(within_limit));
  16353. Request over_limit;
  16354. over_limit.path =
  16355. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16356. EXPECT_FALSE(matcher.match(over_limit));
  16357. }
  16358. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16359. Server svr;
  16360. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16361. res.set_content("ok", "text/plain");
  16362. });
  16363. auto port = svr.bind_to_any_port(HOST);
  16364. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16365. auto se = detail::scope_exit([&] {
  16366. svr.stop();
  16367. thread.join();
  16368. ASSERT_FALSE(svr.is_running());
  16369. });
  16370. svr.wait_until_ready();
  16371. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16372. // request URI limit; this used to be able to crash the process.
  16373. std::string path =
  16374. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16375. std::string req = "GET " + path +
  16376. " HTTP/1.1\r\n"
  16377. "Host: " +
  16378. std::string(HOST) + ":" + std::to_string(port) +
  16379. "\r\n"
  16380. "Connection: close\r\n"
  16381. "\r\n";
  16382. std::string response;
  16383. ASSERT_TRUE(send_request(5, req, &response, port));
  16384. EXPECT_NE(std::string::npos, response.find("404"));
  16385. }
  16386. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16387. Server svr;
  16388. auto handler = [](const Request & /*req*/, Response &res) {
  16389. res.set_content("hit", "text/plain");
  16390. };
  16391. // No regex metacharacter, so this one is compared literally
  16392. svr.Get("/literal/route", handler);
  16393. // '.' is a regex metacharacter, so this one must keep regex semantics
  16394. svr.Get("/a.c", handler);
  16395. auto port = svr.bind_to_any_port(HOST);
  16396. std::thread t([&]() { svr.listen_after_bind(); });
  16397. auto se = detail::scope_exit([&] {
  16398. svr.stop();
  16399. t.join();
  16400. ASSERT_FALSE(svr.is_running());
  16401. });
  16402. svr.wait_until_ready();
  16403. Client cli(HOST, port);
  16404. struct {
  16405. const char *path;
  16406. int status;
  16407. } cases[] = {
  16408. {"/literal/route", StatusCode::OK_200},
  16409. {"/literal/routes", StatusCode::NotFound_404},
  16410. {"/literal/rout", StatusCode::NotFound_404},
  16411. {"/abc", StatusCode::OK_200},
  16412. {"/a.c", StatusCode::OK_200},
  16413. };
  16414. for (const auto &x : cases) {
  16415. auto res = cli.Get(x.path);
  16416. ASSERT_TRUE(res) << x.path;
  16417. EXPECT_EQ(x.status, res->status) << x.path;
  16418. }
  16419. }
  16420. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16421. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16422. // from exhausting the stack, so it must only constrain routes that actually
  16423. // run a regular expression. A literal route is matched by comparison and
  16424. // stays usable at any length.
  16425. Server svr;
  16426. const std::string pattern =
  16427. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16428. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16429. res.set_content("hit", "text/plain");
  16430. });
  16431. auto port = svr.bind_to_any_port(HOST);
  16432. std::thread t([&]() { svr.listen_after_bind(); });
  16433. auto se = detail::scope_exit([&] {
  16434. svr.stop();
  16435. t.join();
  16436. ASSERT_FALSE(svr.is_running());
  16437. });
  16438. svr.wait_until_ready();
  16439. Client cli(HOST, port);
  16440. auto res = cli.Get(pattern);
  16441. ASSERT_TRUE(res);
  16442. EXPECT_EQ(StatusCode::OK_200, res->status);
  16443. }
  16444. TEST(ParseUrlTest, VariousPatterns) {
  16445. {
  16446. detail::UrlComponents uc;
  16447. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16448. EXPECT_EQ("http", uc.scheme);
  16449. EXPECT_EQ("example.com", uc.host);
  16450. EXPECT_EQ("8080", uc.port);
  16451. EXPECT_EQ("/path", uc.path);
  16452. EXPECT_EQ("?q=1", uc.query);
  16453. }
  16454. {
  16455. detail::UrlComponents uc;
  16456. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16457. EXPECT_EQ("https", uc.scheme);
  16458. EXPECT_EQ("example.com", uc.host);
  16459. EXPECT_TRUE(uc.port.empty());
  16460. EXPECT_EQ("/path", uc.path);
  16461. }
  16462. {
  16463. detail::UrlComponents uc;
  16464. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16465. EXPECT_EQ("::1", uc.host);
  16466. EXPECT_EQ("8080", uc.port);
  16467. EXPECT_EQ("/path", uc.path);
  16468. }
  16469. {
  16470. detail::UrlComponents uc;
  16471. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16472. }
  16473. {
  16474. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16475. // the path while the connection still targets the bracketed host.
  16476. detail::UrlComponents uc;
  16477. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16478. }
  16479. {
  16480. detail::UrlComponents uc;
  16481. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16482. }
  16483. {
  16484. detail::UrlComponents uc;
  16485. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16486. EXPECT_EQ("::1", uc.host);
  16487. EXPECT_TRUE(uc.port.empty());
  16488. EXPECT_EQ("/path", uc.path);
  16489. }
  16490. {
  16491. detail::UrlComponents uc;
  16492. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16493. EXPECT_TRUE(uc.scheme.empty());
  16494. EXPECT_EQ("example.com", uc.host);
  16495. EXPECT_EQ("/path", uc.path);
  16496. EXPECT_EQ("?q=1", uc.query);
  16497. }
  16498. {
  16499. detail::UrlComponents uc;
  16500. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16501. EXPECT_TRUE(uc.host.empty());
  16502. EXPECT_EQ("/path", uc.path);
  16503. EXPECT_EQ("?q=1", uc.query);
  16504. }
  16505. {
  16506. detail::UrlComponents uc;
  16507. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16508. EXPECT_EQ("example.com", uc.host);
  16509. EXPECT_EQ("8080", uc.port);
  16510. }
  16511. {
  16512. // Unix socket path — must not be parsed as host
  16513. detail::UrlComponents uc;
  16514. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16515. EXPECT_TRUE(uc.host.empty());
  16516. }
  16517. {
  16518. detail::UrlComponents uc;
  16519. ASSERT_TRUE(detail::parse_url("", uc));
  16520. EXPECT_TRUE(uc.host.empty());
  16521. EXPECT_TRUE(uc.path.empty());
  16522. }
  16523. {
  16524. detail::UrlComponents uc;
  16525. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16526. }
  16527. {
  16528. detail::UrlComponents uc;
  16529. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16530. }
  16531. {
  16532. // Accepted by parse_url; callers restrict to http/https
  16533. detail::UrlComponents uc;
  16534. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16535. EXPECT_EQ("ftp", uc.scheme);
  16536. }
  16537. {
  16538. detail::UrlComponents uc;
  16539. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16540. }
  16541. {
  16542. detail::UrlComponents uc;
  16543. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16544. }
  16545. }
  16546. TEST(ParseUrlTest, FragmentHandling) {
  16547. {
  16548. detail::UrlComponents uc;
  16549. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16550. EXPECT_EQ("/path", uc.path);
  16551. EXPECT_TRUE(uc.query.empty());
  16552. }
  16553. {
  16554. detail::UrlComponents uc;
  16555. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16556. EXPECT_TRUE(uc.path.empty());
  16557. EXPECT_TRUE(uc.query.empty());
  16558. }
  16559. }
  16560. TEST(ParseUrlTest, UserinfoHandling) {
  16561. // userinfo is not supported. Parsers that honour it, or take a backslash for
  16562. // '/', would see evil.com where the host used to be the whole authority.
  16563. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  16564. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  16565. for (auto url : urls) {
  16566. detail::UrlComponents uc;
  16567. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  16568. }
  16569. }
  16570. TEST(ParseUrlTest, IPv6EdgeCases) {
  16571. {
  16572. detail::UrlComponents uc;
  16573. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16574. EXPECT_TRUE(uc.scheme.empty());
  16575. EXPECT_EQ("::1", uc.host);
  16576. EXPECT_EQ("8080", uc.port);
  16577. }
  16578. {
  16579. // Zone ID '%25' is not in [a-fA-F0-9:]
  16580. detail::UrlComponents uc;
  16581. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16582. }
  16583. }
  16584. TEST(ParseUrlTest, SchemeEdgeCases) {
  16585. {
  16586. detail::UrlComponents uc;
  16587. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16588. }
  16589. {
  16590. detail::UrlComponents uc;
  16591. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16592. }
  16593. {
  16594. detail::UrlComponents uc;
  16595. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16596. }
  16597. }
  16598. TEST(ParseUrlTest, PortEdgeCases) {
  16599. {
  16600. detail::UrlComponents uc;
  16601. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16602. EXPECT_TRUE(uc.port.empty());
  16603. EXPECT_EQ("/path", uc.path);
  16604. }
  16605. {
  16606. // parse_url accepts any port string; validation is done by parse_port
  16607. detail::UrlComponents uc;
  16608. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16609. EXPECT_EQ("abc", uc.port);
  16610. }
  16611. }
  16612. TEST(ParseUrlTest, WebSocketPatterns) {
  16613. {
  16614. detail::UrlComponents uc;
  16615. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16616. EXPECT_EQ("ws", uc.scheme);
  16617. EXPECT_EQ("echo.example.com", uc.host);
  16618. EXPECT_EQ("8080", uc.port);
  16619. EXPECT_EQ("/ws", uc.path);
  16620. }
  16621. {
  16622. detail::UrlComponents uc;
  16623. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16624. EXPECT_EQ("wss", uc.scheme);
  16625. EXPECT_EQ("echo.example.com", uc.host);
  16626. EXPECT_TRUE(uc.port.empty());
  16627. EXPECT_EQ("/ws", uc.path);
  16628. }
  16629. }
  16630. TEST(ParseUrlTest, QueryOnly) {
  16631. detail::UrlComponents uc;
  16632. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16633. EXPECT_TRUE(uc.host.empty());
  16634. EXPECT_TRUE(uc.path.empty());
  16635. EXPECT_EQ("?q=1&r=2", uc.query);
  16636. }
  16637. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16638. detail::UrlComponents uc;
  16639. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16640. EXPECT_TRUE(uc.scheme.empty());
  16641. EXPECT_EQ("example.com", uc.host);
  16642. EXPECT_EQ("443", uc.port);
  16643. EXPECT_EQ("/path", uc.path);
  16644. }
  16645. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16646. // If ipv6 regex working, regex match codepath is taken.
  16647. // else port will default to 80 in Client impl
  16648. int clientImplMagicPort = 80;
  16649. int port = 4321;
  16650. // above ports must be different to avoid false negative
  16651. EXPECT_NE(clientImplMagicPort, port);
  16652. std::string ipV6TestURL = "http://[ff06::c3]";
  16653. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16654. CLIENT_PRIVATE_KEY_FILE);
  16655. EXPECT_EQ(cli.port(), port);
  16656. }
  16657. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16658. auto file_path = "./www/dir/index.html";
  16659. auto dir_path = "./www/dir";
  16660. detail::FileStat stat_file(file_path);
  16661. EXPECT_TRUE(stat_file.is_file());
  16662. EXPECT_FALSE(stat_file.is_dir());
  16663. detail::FileStat stat_dir(dir_path);
  16664. EXPECT_FALSE(stat_dir.is_file());
  16665. EXPECT_TRUE(stat_dir.is_dir());
  16666. }
  16667. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16668. // IPv4 with default HTTP port (80)
  16669. EXPECT_EQ("example.com",
  16670. detail::make_host_and_port_string("example.com", 80, false));
  16671. // IPv4 with default HTTPS port (443)
  16672. EXPECT_EQ("example.com",
  16673. detail::make_host_and_port_string("example.com", 443, true));
  16674. // IPv4 with non-default HTTP port
  16675. EXPECT_EQ("example.com:8080",
  16676. detail::make_host_and_port_string("example.com", 8080, false));
  16677. // IPv4 with non-default HTTPS port
  16678. EXPECT_EQ("example.com:8443",
  16679. detail::make_host_and_port_string("example.com", 8443, true));
  16680. // IPv6 with default HTTP port (80)
  16681. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16682. // IPv6 with default HTTPS port (443)
  16683. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16684. // IPv6 with non-default HTTP port
  16685. EXPECT_EQ("[::1]:8080",
  16686. detail::make_host_and_port_string("::1", 8080, false));
  16687. // IPv6 with non-default HTTPS port
  16688. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16689. // IPv6 full address with default port
  16690. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16691. detail::make_host_and_port_string(
  16692. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16693. // IPv6 full address with non-default port
  16694. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16695. detail::make_host_and_port_string(
  16696. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16697. // IPv6 localhost with non-default port
  16698. EXPECT_EQ("[::1]:3000",
  16699. detail::make_host_and_port_string("::1", 3000, false));
  16700. // IPv6 with zone ID (link-local address) with default port
  16701. EXPECT_EQ("[fe80::1%eth0]",
  16702. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16703. // IPv6 with zone ID (link-local address) with non-default port
  16704. EXPECT_EQ("[fe80::1%eth0]:8080",
  16705. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16706. // Edge case: Port 443 with is_ssl=false (should add port)
  16707. EXPECT_EQ("example.com:443",
  16708. detail::make_host_and_port_string("example.com", 443, false));
  16709. // Edge case: Port 80 with is_ssl=true (should add port)
  16710. EXPECT_EQ("example.com:80",
  16711. detail::make_host_and_port_string("example.com", 80, true));
  16712. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16713. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16714. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16715. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16716. // Security fix: Already bracketed IPv6 should not get double brackets
  16717. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16718. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16719. EXPECT_EQ("[::1]:8080",
  16720. detail::make_host_and_port_string("[::1]", 8080, false));
  16721. EXPECT_EQ("[2001:db8::1]:8080",
  16722. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16723. EXPECT_EQ("[fe80::1%eth0]",
  16724. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16725. EXPECT_EQ("[fe80::1%eth0]:8080",
  16726. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16727. // Edge case: Empty host (should return as-is)
  16728. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16729. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16730. // This is a known limitation but shouldn't crash
  16731. EXPECT_EQ("[host:name]",
  16732. detail::make_host_and_port_string("host:name", 80, false));
  16733. // Port number edge cases (no validation, but should not crash)
  16734. EXPECT_EQ("example.com:0",
  16735. detail::make_host_and_port_string("example.com", 0, false));
  16736. EXPECT_EQ("example.com:-1",
  16737. detail::make_host_and_port_string("example.com", -1, false));
  16738. EXPECT_EQ("example.com:65535",
  16739. detail::make_host_and_port_string("example.com", 65535, false));
  16740. EXPECT_EQ("example.com:65536",
  16741. detail::make_host_and_port_string("example.com", 65536, false));
  16742. }
  16743. #ifdef CPPHTTPLIB_SSL_ENABLED
  16744. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16745. httplib::SSLClient cli("roblox.com", 443);
  16746. cli.set_follow_location(true);
  16747. auto res = cli.Get("/");
  16748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16749. EXPECT_EQ(StatusCode::OK_200, res->status);
  16750. }
  16751. #endif
  16752. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16753. Server svr;
  16754. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16755. EXPECT_EQ(res.status, 400);
  16756. });
  16757. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16758. auto se = detail::scope_exit([&] {
  16759. svr.stop();
  16760. thread.join();
  16761. ASSERT_FALSE(svr.is_running());
  16762. });
  16763. svr.wait_until_ready();
  16764. Client cli(HOST, PORT);
  16765. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16766. }
  16767. TEST(InvalidHeaderCharsTest, is_field_name) {
  16768. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16769. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16770. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16771. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16772. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16773. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16774. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16775. EXPECT_FALSE(detail::fields::is_field_name(""));
  16776. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16777. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16778. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16779. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16780. }
  16781. TEST(InvalidHeaderCharsTest, is_field_value) {
  16782. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16783. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16784. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16785. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16786. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16787. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16788. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16789. EXPECT_TRUE(detail::fields::is_field_value(""));
  16790. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16791. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16792. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16793. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16794. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16795. }
  16796. TEST(InvalidHeaderCharsTest, OnServer) {
  16797. Server svr;
  16798. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16799. std::string header = "Not Set";
  16800. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16801. res.set_header(header, "value");
  16802. res.set_content("Page Content Page Content", "text/plain");
  16803. });
  16804. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16805. std::string header = "Not Set";
  16806. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16807. res.set_header("X-Test", header);
  16808. res.set_content("Page Content Page Content", "text/plain");
  16809. });
  16810. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16811. auto se = detail::scope_exit([&] {
  16812. svr.stop();
  16813. thread.join();
  16814. ASSERT_FALSE(svr.is_running());
  16815. });
  16816. svr.wait_until_ready();
  16817. Client cli(HOST, PORT);
  16818. {
  16819. auto res = cli.Get(
  16820. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16822. EXPECT_EQ("Page Content Page Content", res->body);
  16823. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16824. }
  16825. {
  16826. auto res = cli.Get(
  16827. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16829. EXPECT_EQ("Page Content Page Content", res->body);
  16830. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16831. }
  16832. }
  16833. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16834. auto handled = false;
  16835. Server svr;
  16836. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16837. thread t = thread([&] { svr.listen(HOST, PORT); });
  16838. auto se = detail::scope_exit([&] {
  16839. svr.stop();
  16840. t.join();
  16841. ASSERT_FALSE(svr.is_running());
  16842. ASSERT_FALSE(handled);
  16843. });
  16844. svr.wait_until_ready();
  16845. auto req = "POST /test HTTP/1.1\r\n"
  16846. "Content-Length: x\r\n"
  16847. "\r\n";
  16848. std::string response;
  16849. ASSERT_TRUE(send_request(1, req, &response));
  16850. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16851. response.substr(0, response.find("\r\n")));
  16852. }
  16853. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16854. // case-insensitive, and a server that receives a 100-continue expectation in
  16855. // an HTTP/1.0 request MUST ignore it.
  16856. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16857. std::string response;
  16858. ASSERT_TRUE(send_request(1, req, &response, port));
  16859. *got_100 = response.find("100 Continue") != std::string::npos;
  16860. }
  16861. class ExpectTokenTest : public ::testing::Test {
  16862. protected:
  16863. void SetUp() override {
  16864. svr_.Post("/p", [](const Request &, Response &res) {
  16865. res.set_content("ok", "text/plain");
  16866. });
  16867. port_ = svr_.bind_to_any_port(HOST);
  16868. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16869. svr_.wait_until_ready();
  16870. }
  16871. void TearDown() override {
  16872. svr_.stop();
  16873. if (thread_.joinable()) { thread_.join(); }
  16874. }
  16875. std::string request(const char *version, const char *expect_value) const {
  16876. return std::string("POST /p ") + version +
  16877. "\r\n"
  16878. "Host: localhost\r\n"
  16879. "Content-Length: 2\r\n"
  16880. "Connection: close\r\n"
  16881. "Expect: " +
  16882. expect_value +
  16883. "\r\n"
  16884. "\r\n"
  16885. "hi";
  16886. }
  16887. Server svr_;
  16888. int port_ = 0;
  16889. thread thread_;
  16890. };
  16891. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16892. bool got_100 = false;
  16893. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16894. EXPECT_TRUE(got_100);
  16895. }
  16896. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16897. bool got_100 = true;
  16898. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16899. EXPECT_FALSE(got_100);
  16900. }
  16901. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16902. bool got_100 = false;
  16903. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16904. EXPECT_TRUE(got_100);
  16905. }
  16906. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16907. bool got_100 = false;
  16908. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16909. EXPECT_TRUE(got_100);
  16910. }
  16911. // `100 Continue` is sent only when the server starts reading the body, so a
  16912. // request rejected before that never invites the client to send it. The
  16913. // requests below carry the expectation but withhold the body, as a client
  16914. // waiting for `100 Continue` would.
  16915. // A POST that expects `100 Continue` and withholds its two-byte body.
  16916. static std::string expect_headers_only(const std::string &path) {
  16917. return "POST " + path +
  16918. " HTTP/1.1\r\n"
  16919. "Host: localhost\r\n"
  16920. "Content-Length: 2\r\n"
  16921. "Expect: 100-continue\r\n"
  16922. "\r\n";
  16923. }
  16924. class ExpectLazyContinueTest : public ::testing::Test {
  16925. protected:
  16926. void SetUp() override {
  16927. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16928. if (req.path == "/pre-routing") {
  16929. res.status = StatusCode::Unauthorized_401;
  16930. return Server::HandlerResponse::Handled;
  16931. }
  16932. return Server::HandlerResponse::Unhandled;
  16933. });
  16934. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16935. if (req.matched_route == "/pre-request") {
  16936. res.status = StatusCode::Forbidden_403;
  16937. return Server::HandlerResponse::Handled;
  16938. }
  16939. return Server::HandlerResponse::Unhandled;
  16940. });
  16941. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16942. res.set_content("ok", "text/plain");
  16943. });
  16944. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16945. res.set_content("ok", "text/plain");
  16946. });
  16947. svr_.Post("/reader-used", [](const Request &, Response &res,
  16948. const ContentReader &content_reader) {
  16949. std::string body;
  16950. content_reader([&](const char *data, size_t len) {
  16951. body.append(data, len);
  16952. return true;
  16953. });
  16954. res.set_content(body, "text/plain");
  16955. });
  16956. svr_.Post("/reader-unused",
  16957. [](const Request &, Response &res, const ContentReader &) {
  16958. res.set_content("ignored", "text/plain");
  16959. });
  16960. port_ = svr_.bind_to_any_port(HOST);
  16961. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16962. svr_.wait_until_ready();
  16963. }
  16964. void TearDown() override {
  16965. svr_.stop();
  16966. if (thread_.joinable()) { thread_.join(); }
  16967. }
  16968. // Sends `req` and reads until the server closes the connection. Returns
  16969. // false if the read had to wait for the client-side timeout instead.
  16970. bool send_until_closed(const std::string &req, std::string *resp) const {
  16971. auto start = std::chrono::steady_clock::now();
  16972. if (!send_request(3, req, resp, port_)) { return false; }
  16973. auto elapsed = std::chrono::steady_clock::now() - start;
  16974. return elapsed < std::chrono::seconds(2);
  16975. }
  16976. // The final response comes without `100 Continue`, and the server closes
  16977. // the connection since the body may or may not follow.
  16978. void expect_final_without_interim(const std::string &path,
  16979. const char *status_line) const {
  16980. std::string resp;
  16981. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16982. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16983. EXPECT_EQ(0u, resp.find(status_line));
  16984. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16985. }
  16986. Server svr_;
  16987. int port_ = 0;
  16988. thread thread_;
  16989. };
  16990. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16991. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16992. }
  16993. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16994. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16995. }
  16996. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16997. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16998. }
  16999. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  17000. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  17001. }
  17002. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  17003. // The body follows once `100 Continue` has had time to arrive.
  17004. auto req = expect_headers_only("/reader-used");
  17005. req.insert(req.size() - 2, "Connection: close\r\n");
  17006. std::string resp;
  17007. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  17008. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  17009. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  17010. EXPECT_NE(std::string::npos, resp.find("hi"));
  17011. }
  17012. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  17013. // Large enough for the client to add `Expect: 100-continue` itself.
  17014. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  17015. std::atomic<bool> body_sent{false};
  17016. Client cli(HOST, port_);
  17017. auto res = cli.Post(
  17018. "/pre-request", length,
  17019. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  17020. body_sent = true;
  17021. std::string chunk(len, 'x');
  17022. sink.write(chunk.data(), chunk.size());
  17023. return true;
  17024. },
  17025. "application/octet-stream");
  17026. ASSERT_TRUE(res);
  17027. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17028. EXPECT_FALSE(body_sent);
  17029. }
  17030. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  17031. Server svr;
  17032. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  17033. return StatusCode::ExpectationFailed_417;
  17034. });
  17035. svr.Post("/p", [](const Request &, Response &res) {
  17036. res.set_content("ok", "text/plain");
  17037. });
  17038. auto port = svr.bind_to_any_port(HOST);
  17039. thread t = thread([&] { svr.listen_after_bind(); });
  17040. auto se = detail::scope_exit([&] {
  17041. svr.stop();
  17042. t.join();
  17043. });
  17044. svr.wait_until_ready();
  17045. std::string resp;
  17046. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  17047. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  17048. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17049. // Exactly one response: the route handler must not run after the 417.
  17050. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  17051. }
  17052. #ifndef _WIN32
  17053. TEST(Expect100ContinueTest, ServerClosesConnection) {
  17054. static constexpr char reject[] = "Unauthorized";
  17055. static constexpr char accept[] = "Upload accepted";
  17056. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17057. Server svr;
  17058. svr.set_expect_100_continue_handler(
  17059. [](const Request & /*req*/, Response &res) {
  17060. res.status = StatusCode::Unauthorized_401;
  17061. res.set_content(reject, "text/plain");
  17062. return res.status;
  17063. });
  17064. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17065. res.set_content(accept, "text/plain");
  17066. });
  17067. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17068. auto se = detail::scope_exit([&] {
  17069. svr.stop();
  17070. thread.join();
  17071. ASSERT_FALSE(svr.is_running());
  17072. });
  17073. svr.wait_until_ready();
  17074. {
  17075. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17076. curl_easy_init(), &curl_easy_cleanup};
  17077. ASSERT_NE(curl, nullptr);
  17078. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17079. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17080. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17081. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17082. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17083. &curl_slist_free_all};
  17084. ASSERT_NE(list, nullptr);
  17085. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17086. struct read_data {
  17087. size_t read_size;
  17088. size_t total_size;
  17089. } data = {0, total_size};
  17090. using read_callback_t =
  17091. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17092. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17093. void *userdata) -> size_t {
  17094. read_data *d = (read_data *)userdata;
  17095. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17096. std::fill_n(ptr, size * nmemb, 'A');
  17097. d->read_size += size * nmemb;
  17098. return size * nmemb;
  17099. };
  17100. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  17101. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17102. std::vector<char> buffer;
  17103. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17104. using write_callback_t =
  17105. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17106. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17107. void *userdata) -> size_t {
  17108. std::vector<char> *buf = (std::vector<char> *)userdata;
  17109. buf->reserve(buf->size() + size * nmemb + 1);
  17110. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17111. return size * nmemb;
  17112. };
  17113. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  17114. {
  17115. const auto res = curl_easy_perform(curl.get());
  17116. ASSERT_EQ(res, CURLE_OK);
  17117. }
  17118. {
  17119. auto response_code = long{};
  17120. const auto res =
  17121. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  17122. ASSERT_EQ(res, CURLE_OK);
  17123. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  17124. }
  17125. {
  17126. auto dl = curl_off_t{};
  17127. const auto res =
  17128. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  17129. ASSERT_EQ(res, CURLE_OK);
  17130. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  17131. }
  17132. {
  17133. buffer.push_back('\0');
  17134. ASSERT_STRCASEEQ(buffer.data(), reject);
  17135. }
  17136. }
  17137. }
  17138. #endif
  17139. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  17140. // Regression test for #2458.
  17141. //
  17142. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  17143. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  17144. // ticket can make the client socket spuriously readable during the
  17145. // 100-continue wait. If the readiness is mistaken for an incoming response,
  17146. // the client withholds the body and then blocks reading a response that never
  17147. // comes, failing with `Failed to read connection`.
  17148. //
  17149. // A correct client (like curl) sends the body once no `100 Continue` arrives
  17150. // within the timeout. This raw OpenSSL server deliberately never sends
  17151. // `100 Continue`; the client must still deliver the body and receive 200.
  17152. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  17153. signal(SIGPIPE, SIG_IGN);
  17154. const auto port = PORT + 4;
  17155. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17156. ASSERT_NE(srv, INVALID_SOCKET);
  17157. int opt = 1;
  17158. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  17159. sockaddr_in addr{};
  17160. addr.sin_family = AF_INET;
  17161. addr.sin_port = htons(static_cast<uint16_t>(port));
  17162. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17163. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17164. ASSERT_EQ(0, ::listen(srv, 1));
  17165. std::atomic<size_t> server_body_bytes{0};
  17166. auto server_thread = std::thread([&] {
  17167. sockaddr_in cli_addr{};
  17168. socklen_t cli_len = sizeof(cli_addr);
  17169. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17170. if (cli == INVALID_SOCKET) { return; }
  17171. // Bound the lifetime of the server side so a buggy client (which never
  17172. // sends the body) cannot make this thread block forever on join.
  17173. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  17174. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  17175. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  17176. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  17177. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  17178. SSL *ssl = SSL_new(ctx);
  17179. SSL_set_fd(ssl, static_cast<int>(cli));
  17180. if (SSL_accept(ssl) > 0) {
  17181. // Read the request headers. Reading here also flushes the TLS 1.3
  17182. // session tickets to the client. Deliberately do NOT send
  17183. // `100 Continue`.
  17184. std::string buf;
  17185. char tmp[1024];
  17186. while (buf.find("\r\n\r\n") == std::string::npos) {
  17187. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17188. if (n <= 0) { break; }
  17189. buf.append(tmp, static_cast<size_t>(n));
  17190. }
  17191. // A correct client sends the body now; count what arrives.
  17192. auto pos = buf.find("\r\n\r\n");
  17193. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  17194. while (body < 4096) {
  17195. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17196. if (n <= 0) { break; }
  17197. body += static_cast<size_t>(n);
  17198. }
  17199. server_body_bytes = body;
  17200. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  17201. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  17202. SSL_shutdown(ssl);
  17203. }
  17204. SSL_free(ssl);
  17205. detail::close_socket(cli);
  17206. SSL_CTX_free(ctx);
  17207. });
  17208. auto se = detail::scope_exit([&] {
  17209. server_thread.join();
  17210. detail::close_socket(srv);
  17211. });
  17212. SSLClient cli("127.0.0.1", port);
  17213. cli.enable_server_certificate_verification(false);
  17214. cli.set_connection_timeout(5, 0);
  17215. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  17216. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  17217. std::string body(4096, 'A');
  17218. auto res = cli.Put("/api/test", body, "application/json");
  17219. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  17220. EXPECT_EQ(StatusCode::OK_200, res->status);
  17221. EXPECT_EQ(body.size(), server_body_bytes.load());
  17222. }
  17223. #endif
  17224. template <typename S, typename C>
  17225. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  17226. svr.Get("/stream", [&](const Request &, Response &res) {
  17227. auto data = new std::string("01234567890123456789");
  17228. res.set_content_provider(
  17229. data->size(), "text/plain",
  17230. [&, data](size_t offset, size_t length, DataSink &sink) {
  17231. const size_t DATA_CHUNK_SIZE = 4;
  17232. const auto &d = *data;
  17233. std::this_thread::sleep_for(std::chrono::seconds(1));
  17234. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  17235. return true;
  17236. },
  17237. [data](bool success) {
  17238. EXPECT_FALSE(success);
  17239. delete data;
  17240. });
  17241. });
  17242. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  17243. auto i = new size_t(0);
  17244. res.set_content_provider(
  17245. "text/plain",
  17246. [i](size_t, DataSink &sink) {
  17247. if (*i < 5) {
  17248. std::this_thread::sleep_for(std::chrono::seconds(1));
  17249. sink.write("abcd", 4);
  17250. (*i)++;
  17251. } else {
  17252. sink.done();
  17253. }
  17254. return true;
  17255. },
  17256. [i](bool success) {
  17257. EXPECT_FALSE(success);
  17258. delete i;
  17259. });
  17260. });
  17261. svr.Get("/chunked", [&](const Request &, Response &res) {
  17262. auto i = new size_t(0);
  17263. res.set_chunked_content_provider(
  17264. "text/plain",
  17265. [i](size_t, DataSink &sink) {
  17266. if (*i < 5) {
  17267. std::this_thread::sleep_for(std::chrono::seconds(1));
  17268. sink.os << "abcd";
  17269. (*i)++;
  17270. } else {
  17271. sink.done();
  17272. }
  17273. return true;
  17274. },
  17275. [i](bool success) {
  17276. EXPECT_FALSE(success);
  17277. delete i;
  17278. });
  17279. });
  17280. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17281. auto se = detail::scope_exit([&] {
  17282. svr.stop();
  17283. listen_thread.join();
  17284. ASSERT_FALSE(svr.is_running());
  17285. });
  17286. svr.wait_until_ready();
  17287. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  17288. {
  17289. auto start = std::chrono::steady_clock::now();
  17290. auto res = cli.Get("/stream");
  17291. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17292. std::chrono::steady_clock::now() - start)
  17293. .count();
  17294. ASSERT_FALSE(res);
  17295. EXPECT_EQ(Error::Read, res.error());
  17296. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17297. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17298. }
  17299. {
  17300. auto start = std::chrono::steady_clock::now();
  17301. auto res = cli.Get("/stream_without_length");
  17302. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17303. std::chrono::steady_clock::now() - start)
  17304. .count();
  17305. ASSERT_FALSE(res);
  17306. EXPECT_EQ(Error::Read, res.error());
  17307. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17308. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17309. }
  17310. {
  17311. auto start = std::chrono::steady_clock::now();
  17312. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  17313. EXPECT_EQ("abcd", string(data, data_length));
  17314. return true;
  17315. });
  17316. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17317. std::chrono::steady_clock::now() - start)
  17318. .count();
  17319. ASSERT_FALSE(res);
  17320. EXPECT_EQ(Error::Read, res.error());
  17321. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17322. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17323. }
  17324. }
  17325. TEST(MaxTimeoutTest, ContentStream) {
  17326. time_t timeout = 2000;
  17327. time_t threshold = 200;
  17328. Server svr;
  17329. Client cli("localhost", PORT);
  17330. max_timeout_test(svr, cli, timeout, threshold);
  17331. }
  17332. #ifdef CPPHTTPLIB_SSL_ENABLED
  17333. TEST(MaxTimeoutTest, ContentStreamSSL) {
  17334. time_t timeout = 2000;
  17335. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  17336. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17337. SSLClient cli("localhost", PORT);
  17338. cli.enable_server_certificate_verification(false);
  17339. max_timeout_test(svr, cli, timeout, threshold);
  17340. }
  17341. #endif
  17342. class EventDispatcher {
  17343. public:
  17344. EventDispatcher() {}
  17345. bool wait_event(DataSink *sink) {
  17346. unique_lock<mutex> lk(m_);
  17347. int id = id_;
  17348. // Wait with timeout to prevent hanging if client disconnects
  17349. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17350. [&] { return cid_ == id; })) {
  17351. return false; // Timeout occurred
  17352. }
  17353. sink->write(message_.data(), message_.size());
  17354. return true;
  17355. }
  17356. void send_event(const string &message) {
  17357. lock_guard<mutex> lk(m_);
  17358. cid_ = id_++;
  17359. message_ = message;
  17360. cv_.notify_all();
  17361. }
  17362. private:
  17363. mutex m_;
  17364. condition_variable cv_;
  17365. atomic_int id_{0};
  17366. atomic_int cid_{-1};
  17367. string message_;
  17368. };
  17369. TEST(ClientInThreadTest, Issue2068) {
  17370. EventDispatcher ed;
  17371. Server svr;
  17372. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17373. res.set_chunked_content_provider("text/event-stream",
  17374. [&](size_t /*offset*/, DataSink &sink) {
  17375. return ed.wait_event(&sink);
  17376. });
  17377. });
  17378. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17379. svr.wait_until_ready();
  17380. thread event_thread([&] {
  17381. int id = 0;
  17382. while (svr.is_running()) {
  17383. this_thread::sleep_for(chrono::milliseconds(500));
  17384. std::stringstream ss;
  17385. ss << "data: " << id << "\n\n";
  17386. ed.send_event(ss.str());
  17387. id++;
  17388. }
  17389. });
  17390. auto se = detail::scope_exit([&] {
  17391. svr.stop();
  17392. listen_thread.join();
  17393. event_thread.join();
  17394. ASSERT_FALSE(svr.is_running());
  17395. });
  17396. {
  17397. auto client = detail::make_unique<Client>(HOST, PORT);
  17398. client->set_read_timeout(std::chrono::minutes(10));
  17399. std::atomic<bool> stop{false};
  17400. std::thread t([&] {
  17401. client->Get("/event1",
  17402. [&](const char *, size_t) -> bool { return !stop; });
  17403. });
  17404. std::this_thread::sleep_for(std::chrono::seconds(2));
  17405. stop = true;
  17406. client->stop();
  17407. t.join();
  17408. // Reset client after thread has finished
  17409. client.reset();
  17410. }
  17411. }
  17412. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17413. auto handled = false;
  17414. Server svr;
  17415. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17416. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17417. auto se = detail::scope_exit([&] {
  17418. svr.stop();
  17419. t.join();
  17420. ASSERT_FALSE(svr.is_running());
  17421. ASSERT_FALSE(handled);
  17422. });
  17423. svr.wait_until_ready();
  17424. // Two Content-Length headers with different values — must be rejected
  17425. auto req = "POST /test HTTP/1.1\r\n"
  17426. "Content-Length: 5\r\n"
  17427. "Content-Length: 10\r\n"
  17428. "\r\n"
  17429. "hello";
  17430. std::string response;
  17431. ASSERT_TRUE(send_request(1, req, &response));
  17432. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17433. response.substr(0, response.find("\r\n")));
  17434. }
  17435. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17436. auto handled = false;
  17437. Server svr;
  17438. svr.Post("/test", [&](const Request &, Response &res) {
  17439. handled = true;
  17440. res.set_content("ok", "text/plain");
  17441. });
  17442. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17443. auto se = detail::scope_exit([&] {
  17444. svr.stop();
  17445. t.join();
  17446. ASSERT_FALSE(svr.is_running());
  17447. ASSERT_TRUE(handled);
  17448. });
  17449. svr.wait_until_ready();
  17450. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17451. auto req = "POST /test HTTP/1.1\r\n"
  17452. "Host: localhost\r\n"
  17453. "Content-Length: 5\r\n"
  17454. "Content-Length: 5\r\n"
  17455. "\r\n"
  17456. "hello";
  17457. std::string response;
  17458. ASSERT_TRUE(send_request(1, req, &response));
  17459. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17460. }
  17461. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17462. Server svr;
  17463. svr.Get("/test", [](const Request &, Response &res) {
  17464. res.set_content("ok", "text/plain");
  17465. });
  17466. auto port = svr.bind_to_any_port(HOST);
  17467. thread t = thread([&] { svr.listen_after_bind(); });
  17468. auto se = detail::scope_exit([&] {
  17469. svr.stop();
  17470. t.join();
  17471. ASSERT_FALSE(svr.is_running());
  17472. });
  17473. svr.wait_until_ready();
  17474. auto status_line = [&](const std::string &host_lines) {
  17475. std::string res;
  17476. send_request(
  17477. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17478. &res, port);
  17479. return res.substr(0, res.find("\r\n"));
  17480. };
  17481. const char *accepted[] = {
  17482. "Host: localhost\r\n",
  17483. "Host: a.example:8080\r\n",
  17484. "Host: my_service\r\n",
  17485. "Host: [::1]:8080\r\n",
  17486. "Host: [fe80::1%25eth0]\r\n",
  17487. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17488. };
  17489. for (auto host_lines : accepted) {
  17490. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17491. }
  17492. const char *rejected[] = {
  17493. "Host: a.example\r\nHost: b.example\r\n",
  17494. "Host: a.example\r\nHost: a.example\r\n",
  17495. "Host: a@b.example\r\n",
  17496. "Host: a.example/b\r\n",
  17497. "Host: a.example\\b\r\n",
  17498. "Host: a.example?b\r\n",
  17499. "Host: a.example#b\r\n",
  17500. "Host: a.example b.example\r\n",
  17501. };
  17502. for (auto host_lines : rejected) {
  17503. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17504. << host_lines;
  17505. }
  17506. }
  17507. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17508. Server svr;
  17509. svr.Get("/", [](const Request &req, Response &res) {
  17510. EXPECT_EQ(2U, req.trailers.size());
  17511. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17512. // Denied
  17513. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17514. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17515. // Accepted
  17516. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17517. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17518. EXPECT_TRUE(req.has_trailer("X-World"));
  17519. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17520. res.set_content("ok", "text/plain");
  17521. });
  17522. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17523. auto se = detail::scope_exit([&] {
  17524. svr.stop();
  17525. t.join();
  17526. ASSERT_FALSE(svr.is_running());
  17527. });
  17528. svr.wait_until_ready();
  17529. const std::string req = "GET / HTTP/1.1\r\n"
  17530. "Transfer-Encoding: chunked\r\n"
  17531. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17532. "\r\n"
  17533. "0\r\n"
  17534. "Content-Length: 10\r\n"
  17535. "Host: internal.local\r\n"
  17536. "Content-Type: malicious/content\r\n"
  17537. "Cookie: any\r\n"
  17538. "Set-Cookie: any\r\n"
  17539. "X-Forwarded-For: attacker.com\r\n"
  17540. "X-Real-Ip: 1.1.1.1\r\n"
  17541. "X-Hello: hello\r\n"
  17542. "X-World: world\r\n"
  17543. "\r\n";
  17544. std::string res;
  17545. ASSERT_TRUE(send_request(1, req, &res));
  17546. }
  17547. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17548. // several field lines, and the combined value is what has to be parsed. A
  17549. // Trailer field split across lines therefore declares every name it lists;
  17550. // reading only the first line silently drops the trailers the later lines
  17551. // declare. The prohibited-trailer filter still applies to every line.
  17552. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17553. Server svr;
  17554. size_t observed_trailer_count = 0;
  17555. std::string observed_hello;
  17556. std::string observed_world;
  17557. bool observed_content_length = true;
  17558. svr.Get("/", [&](const Request &req, Response &res) {
  17559. observed_trailer_count = req.trailers.size();
  17560. observed_hello = req.get_trailer_value("X-Hello");
  17561. observed_world = req.get_trailer_value("X-World");
  17562. observed_content_length = req.has_trailer("Content-Length");
  17563. res.set_content("ok", "text/plain");
  17564. });
  17565. auto port = svr.bind_to_any_port(HOST);
  17566. thread t = thread([&]() { svr.listen_after_bind(); });
  17567. auto se = detail::scope_exit([&] {
  17568. svr.stop();
  17569. t.join();
  17570. ASSERT_FALSE(svr.is_running());
  17571. });
  17572. svr.wait_until_ready();
  17573. const std::string req = "GET / HTTP/1.1\r\n"
  17574. "Host: localhost\r\n"
  17575. "Transfer-Encoding: chunked\r\n"
  17576. "Trailer: X-Hello\r\n"
  17577. "Trailer: X-World, Content-Length\r\n"
  17578. "\r\n"
  17579. "0\r\n"
  17580. "X-Hello: hello\r\n"
  17581. "X-World: world\r\n"
  17582. "Content-Length: 10\r\n"
  17583. "\r\n";
  17584. std::string res;
  17585. ASSERT_TRUE(send_request(1, req, &res, port));
  17586. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17587. // Accepted: both field lines contribute to the declared set
  17588. EXPECT_EQ(2U, observed_trailer_count);
  17589. EXPECT_EQ(observed_hello, "hello");
  17590. EXPECT_EQ(observed_world, "world");
  17591. // Denied: a prohibited name stays prohibited on a later field line
  17592. EXPECT_FALSE(observed_content_length);
  17593. }
  17594. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17595. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17596. // unbounded run of fields that are never declared, because the counter would
  17597. // only advance for declared fields.
  17598. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17599. Server svr;
  17600. bool handler_called = false;
  17601. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17602. handler_called = true;
  17603. res.set_content("ok", "text/plain");
  17604. });
  17605. auto port = svr.bind_to_any_port(HOST);
  17606. thread t = thread([&]() { svr.listen_after_bind(); });
  17607. auto se = detail::scope_exit([&] {
  17608. svr.stop();
  17609. t.join();
  17610. ASSERT_FALSE(svr.is_running());
  17611. });
  17612. svr.wait_until_ready();
  17613. // Declare nothing, then send far more undeclared trailer fields than the
  17614. // header-count limit. Parsing must stop and reject the request rather than
  17615. // read every line.
  17616. std::string req = "GET / HTTP/1.1\r\n"
  17617. "Transfer-Encoding: chunked\r\n"
  17618. "\r\n"
  17619. "0\r\n";
  17620. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17621. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17622. }
  17623. req += "\r\n";
  17624. std::string res;
  17625. ASSERT_TRUE(send_request(1, req, &res, port));
  17626. // The request is rejected before the handler runs.
  17627. EXPECT_FALSE(handler_called);
  17628. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17629. }
  17630. // The set of declared trailer names is capped so a peer cannot grow it without
  17631. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17632. // declared past the cap is not honored, even if the field is actually sent.
  17633. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17634. Server svr;
  17635. // One name inside the cap and one past it, so the test tracks the cap rather
  17636. // than a fixed count.
  17637. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17638. const std::string within_cap_name = "X-T-0";
  17639. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17640. bool observed_within_cap = false;
  17641. bool observed_past_cap = false;
  17642. svr.Get("/", [&](const Request &req, Response &res) {
  17643. observed_within_cap = req.has_trailer(within_cap_name);
  17644. observed_past_cap = req.has_trailer(past_cap_name);
  17645. res.set_content("ok", "text/plain");
  17646. });
  17647. auto port = svr.bind_to_any_port(HOST);
  17648. thread t = thread([&]() { svr.listen_after_bind(); });
  17649. auto se = detail::scope_exit([&] {
  17650. svr.stop();
  17651. t.join();
  17652. ASSERT_FALSE(svr.is_running());
  17653. });
  17654. svr.wait_until_ready();
  17655. // Declare more trailer names than the cap in a single Trailer field, then
  17656. // actually send the first (within the cap) and the last (past it).
  17657. std::string trailer_decl = "Trailer: ";
  17658. for (int i = 0; i < declared_count; i++) {
  17659. if (i != 0) { trailer_decl += ", "; }
  17660. trailer_decl += "X-T-" + std::to_string(i);
  17661. }
  17662. trailer_decl += "\r\n";
  17663. const std::string req = "GET / HTTP/1.1\r\n"
  17664. "Host: localhost\r\n"
  17665. "Transfer-Encoding: chunked\r\n" +
  17666. trailer_decl +
  17667. "\r\n"
  17668. "0\r\n" +
  17669. within_cap_name + ": a\r\n" + past_cap_name +
  17670. ": b\r\n"
  17671. "\r\n";
  17672. std::string res;
  17673. ASSERT_TRUE(send_request(1, req, &res, port));
  17674. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17675. // A name within the cap is honored; one declared past the cap is dropped.
  17676. EXPECT_TRUE(observed_within_cap);
  17677. EXPECT_FALSE(observed_past_cap);
  17678. }
  17679. // A direct client that is not listed in trusted_proxies must not be able to
  17680. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17681. // the peer address on the actual TCP connection determines whether the
  17682. // header is honored.
  17683. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17684. Server svr;
  17685. // Deliberately does NOT include the loopback address the test client
  17686. // actually connects from, so the direct connection is not a trusted proxy.
  17687. svr.set_trusted_proxies({"203.0.113.66"});
  17688. std::string observed_remote_addr;
  17689. svr.Get("/ip", [&](const Request &req, Response &res) {
  17690. observed_remote_addr = req.remote_addr;
  17691. res.set_content("ok", "text/plain");
  17692. });
  17693. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17694. auto se = detail::scope_exit([&] {
  17695. svr.stop();
  17696. t.join();
  17697. ASSERT_FALSE(svr.is_running());
  17698. });
  17699. svr.wait_until_ready();
  17700. Client cli(HOST, PORT);
  17701. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17703. EXPECT_EQ(StatusCode::OK_200, res->status);
  17704. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17705. // ignored entirely and the real connection-level address retained.
  17706. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17707. observed_remote_addr == "127.0.0.1");
  17708. }
  17709. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17710. Server svr;
  17711. std::string observed_remote_addr;
  17712. std::string observed_xff;
  17713. svr.Get("/ip", [&](const Request &req, Response &res) {
  17714. observed_remote_addr = req.remote_addr;
  17715. observed_xff = req.get_header_value("X-Forwarded-For");
  17716. res.set_content("ok", "text/plain");
  17717. });
  17718. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17719. auto se = detail::scope_exit([&] {
  17720. svr.stop();
  17721. t.join();
  17722. ASSERT_FALSE(svr.is_running());
  17723. });
  17724. svr.wait_until_ready();
  17725. Client cli(HOST, PORT);
  17726. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17728. EXPECT_EQ(StatusCode::OK_200, res->status);
  17729. EXPECT_EQ(observed_xff, "203.0.113.66");
  17730. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17731. observed_remote_addr == "127.0.0.1");
  17732. }
  17733. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17734. Server svr;
  17735. svr.set_trusted_proxies({"203.0.113.66"});
  17736. std::string observed_remote_addr;
  17737. std::string observed_xff;
  17738. svr.Get("/ip", [&](const Request &req, Response &res) {
  17739. observed_remote_addr = req.remote_addr;
  17740. observed_xff = req.get_header_value("X-Forwarded-For");
  17741. res.set_content("ok", "text/plain");
  17742. });
  17743. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17744. auto se = detail::scope_exit([&] {
  17745. svr.stop();
  17746. t.join();
  17747. ASSERT_FALSE(svr.is_running());
  17748. });
  17749. svr.wait_until_ready();
  17750. Client cli(HOST, PORT);
  17751. auto res = cli.Get("/ip");
  17752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17753. EXPECT_EQ(StatusCode::OK_200, res->status);
  17754. EXPECT_EQ(observed_xff, "");
  17755. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17756. observed_remote_addr == "127.0.0.1");
  17757. }
  17758. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17759. Server svr;
  17760. // Include the loopback address the test client actually connects from, so
  17761. // the direct connection itself is recognized as the trusted proxy hop.
  17762. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17763. std::string observed_remote_addr;
  17764. std::string observed_xff;
  17765. svr.Get("/ip", [&](const Request &req, Response &res) {
  17766. observed_remote_addr = req.remote_addr;
  17767. observed_xff = req.get_header_value("X-Forwarded-For");
  17768. res.set_content("ok", "text/plain");
  17769. });
  17770. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17771. auto se = detail::scope_exit([&] {
  17772. svr.stop();
  17773. t.join();
  17774. ASSERT_FALSE(svr.is_running());
  17775. });
  17776. svr.wait_until_ready();
  17777. Client cli(HOST, PORT);
  17778. auto res = cli.Get(
  17779. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17781. EXPECT_EQ(StatusCode::OK_200, res->status);
  17782. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17783. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17784. }
  17785. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17786. Server svr;
  17787. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17788. std::string observed_remote_addr;
  17789. std::string observed_xff;
  17790. svr.Get("/ip", [&](const Request &req, Response &res) {
  17791. observed_remote_addr = req.remote_addr;
  17792. observed_xff = req.get_header_value("X-Forwarded-For");
  17793. res.set_content("ok", "text/plain");
  17794. });
  17795. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17796. auto se = detail::scope_exit([&] {
  17797. svr.stop();
  17798. t.join();
  17799. ASSERT_FALSE(svr.is_running());
  17800. });
  17801. svr.wait_until_ready();
  17802. Client cli(HOST, PORT);
  17803. auto res = cli.Get(
  17804. "/ip",
  17805. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17807. EXPECT_EQ(StatusCode::OK_200, res->status);
  17808. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17809. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17810. }
  17811. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17812. Server svr;
  17813. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17814. std::string observed_remote_addr;
  17815. std::string observed_xff;
  17816. svr.Get("/ip", [&](const Request &req, Response &res) {
  17817. observed_remote_addr = req.remote_addr;
  17818. observed_xff = req.get_header_value("X-Forwarded-For");
  17819. res.set_content("ok", "text/plain");
  17820. });
  17821. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17822. auto se = detail::scope_exit([&] {
  17823. svr.stop();
  17824. t.join();
  17825. ASSERT_FALSE(svr.is_running());
  17826. });
  17827. svr.wait_until_ready();
  17828. Client cli(HOST, PORT);
  17829. auto res = cli.Get(
  17830. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17832. EXPECT_EQ(StatusCode::OK_200, res->status);
  17833. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17834. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17835. // and must not be selected.
  17836. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17837. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17838. }
  17839. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17840. Server svr;
  17841. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17842. std::string observed_remote_addr;
  17843. svr.Get("/ip", [&](const Request &req, Response &res) {
  17844. observed_remote_addr = req.remote_addr;
  17845. res.set_content("ok", "text/plain");
  17846. });
  17847. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17848. auto se = detail::scope_exit([&] {
  17849. svr.stop();
  17850. t.join();
  17851. ASSERT_FALSE(svr.is_running());
  17852. });
  17853. svr.wait_until_ready();
  17854. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17855. // a forged address and the trusted proxy's own address; the forged value must
  17856. // not win over the address the trusted proxy actually recorded.
  17857. Client cli(HOST, PORT);
  17858. auto res = cli.Get(
  17859. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17861. EXPECT_EQ(StatusCode::OK_200, res->status);
  17862. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17863. }
  17864. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17865. Server svr;
  17866. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17867. std::string observed_remote_addr;
  17868. std::string observed_xff;
  17869. svr.Get("/ip", [&](const Request &req, Response &res) {
  17870. observed_remote_addr = req.remote_addr;
  17871. observed_xff = req.get_header_value("X-Forwarded-For");
  17872. res.set_content("ok", "text/plain");
  17873. });
  17874. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17875. auto se = detail::scope_exit([&] {
  17876. svr.stop();
  17877. t.join();
  17878. ASSERT_FALSE(svr.is_running());
  17879. });
  17880. svr.wait_until_ready();
  17881. Client cli(HOST, PORT);
  17882. auto res = cli.Get(
  17883. "/ip",
  17884. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17886. EXPECT_EQ(StatusCode::OK_200, res->status);
  17887. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17888. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17889. }
  17890. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17891. Server svr;
  17892. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17893. std::string observed_remote_addr;
  17894. std::string observed_xff;
  17895. svr.Get("/ip", [&](const Request &req, Response &res) {
  17896. observed_remote_addr = req.remote_addr;
  17897. observed_xff = req.get_header_value("X-Forwarded-For");
  17898. res.set_content("ok", "text/plain");
  17899. });
  17900. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17901. auto se = detail::scope_exit([&] {
  17902. svr.stop();
  17903. t.join();
  17904. ASSERT_FALSE(svr.is_running());
  17905. });
  17906. svr.wait_until_ready();
  17907. std::string raw_req =
  17908. "GET /ip HTTP/1.1\r\n"
  17909. "Host: localhost\r\n"
  17910. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17911. "Connection: close\r\n"
  17912. "\r\n";
  17913. std::string out;
  17914. ASSERT_TRUE(send_request(5, raw_req, &out));
  17915. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17916. // Header parser trims surrounding whitespace of the header value
  17917. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17918. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17919. }
  17920. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17921. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17922. // their own X-Forwarded-For as a separate field line rather than extending the
  17923. // one the client sent, so every occurrence has to be taken into account.
  17924. // Reading only the first one hands back the address the client chose.
  17925. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17926. Server svr;
  17927. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17928. std::string observed_remote_addr;
  17929. size_t observed_xff_count = 0;
  17930. svr.Get("/ip", [&](const Request &req, Response &res) {
  17931. observed_remote_addr = req.remote_addr;
  17932. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17933. res.set_content("ok", "text/plain");
  17934. });
  17935. auto port = svr.bind_to_any_port(HOST);
  17936. thread t = thread([&]() { svr.listen_after_bind(); });
  17937. auto se = detail::scope_exit([&] {
  17938. svr.stop();
  17939. t.join();
  17940. ASSERT_FALSE(svr.is_running());
  17941. });
  17942. svr.wait_until_ready();
  17943. // The client supplies the first field line; the trusted proxy appends the
  17944. // address it observed as a second one.
  17945. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17946. "Host: localhost\r\n"
  17947. "X-Forwarded-For: 1.2.3.4\r\n"
  17948. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17949. "Connection: close\r\n"
  17950. "\r\n";
  17951. std::string out;
  17952. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17953. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17954. EXPECT_EQ(observed_xff_count, 2U);
  17955. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17956. // The same chain spread over one field line per hop derives the same client
  17957. // address, i.e. the split and the comma-joined representations agree.
  17958. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17959. "Host: localhost\r\n"
  17960. "X-Forwarded-For: 1.2.3.4\r\n"
  17961. "X-Forwarded-For: 198.51.100.23\r\n"
  17962. "X-Forwarded-For: 192.0.2.45\r\n"
  17963. "Connection: close\r\n"
  17964. "\r\n";
  17965. out.clear();
  17966. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17967. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17968. EXPECT_EQ(observed_xff_count, 3U);
  17969. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17970. }
  17971. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17972. // crash the server (it used to call front() on an empty vector inside
  17973. // get_client_ip). The connection-level remote address must be retained instead.
  17974. static void run_malformed_xff_test(const std::string &xff_value) {
  17975. Server svr;
  17976. svr.set_trusted_proxies({"192.0.2.45"});
  17977. std::string observed_remote_addr;
  17978. svr.Get("/ip", [&](const Request &req, Response &res) {
  17979. observed_remote_addr = req.remote_addr;
  17980. res.set_content("ok", "text/plain");
  17981. });
  17982. int port = 0;
  17983. thread t = thread([&]() {
  17984. port = svr.bind_to_any_port(HOST);
  17985. svr.listen_after_bind();
  17986. });
  17987. auto se = detail::scope_exit([&] {
  17988. svr.stop();
  17989. t.join();
  17990. ASSERT_FALSE(svr.is_running());
  17991. });
  17992. svr.wait_until_ready();
  17993. Client cli(HOST, port);
  17994. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17996. EXPECT_EQ(StatusCode::OK_200, res->status);
  17997. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17998. observed_remote_addr == "127.0.0.1");
  17999. }
  18000. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  18001. run_malformed_xff_test("");
  18002. }
  18003. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  18004. run_malformed_xff_test(",");
  18005. }
  18006. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  18007. run_malformed_xff_test(", , ,");
  18008. }
  18009. // The same rule applies to Accept: a request whose acceptable types are spread
  18010. // over several field lines must be negotiated against all of them.
  18011. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  18012. // case-insensitive connection options. Comparing the whole field value against
  18013. // one option misses a client that sends several of them, and misses every
  18014. // casing but the one written in the comparison.
  18015. //
  18016. // Sends req, reads the response, then reuses the same socket for a second
  18017. // request to find out whether the server kept the connection.
  18018. static void probe_connection_reuse(int port, const std::string &req,
  18019. bool *announced_close, bool *reusable) {
  18020. auto error = Error::Success;
  18021. auto sock = detail::create_client_socket(
  18022. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18023. /*connection_timeout_sec=*/5, 0,
  18024. /*read_timeout_sec=*/1, 0,
  18025. /*write_timeout_sec=*/5, 0, std::string(), error);
  18026. ASSERT_NE(sock, INVALID_SOCKET);
  18027. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  18028. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  18029. "Host: localhost\r\n"
  18030. "Connection: close\r\n"
  18031. "\r\n";
  18032. std::string first_response;
  18033. std::string second_response;
  18034. detail::process_client_socket(
  18035. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  18036. [&](Stream &strm) {
  18037. if (strm.write(req.data(), req.size()) !=
  18038. static_cast<ssize_t>(req.size())) {
  18039. return false;
  18040. }
  18041. char buf[512];
  18042. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  18043. // Headers plus the two-byte body of the handler below
  18044. while (reader.getline()) {
  18045. first_response += reader.ptr();
  18046. if (first_response.find("ok") != std::string::npos) { break; }
  18047. }
  18048. if (strm.write(second.data(), second.size()) !=
  18049. static_cast<ssize_t>(second.size())) {
  18050. return true;
  18051. }
  18052. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  18053. while (reader2.getline()) {
  18054. second_response += reader2.ptr();
  18055. if (second_response.find("ok") != std::string::npos) { break; }
  18056. }
  18057. return true;
  18058. });
  18059. *announced_close =
  18060. first_response.find("Connection: close") != std::string::npos;
  18061. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18062. }
  18063. class ConnectionTokenTest : public ::testing::Test {
  18064. protected:
  18065. void SetUp() override {
  18066. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18067. res.set_content("ok", "text/plain");
  18068. });
  18069. port_ = svr_.bind_to_any_port(HOST);
  18070. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18071. svr_.wait_until_ready();
  18072. }
  18073. void TearDown() override {
  18074. svr_.stop();
  18075. if (thread_.joinable()) { thread_.join(); }
  18076. }
  18077. Server svr_;
  18078. int port_ = 0;
  18079. thread thread_;
  18080. };
  18081. // "close" alongside another option still closes the connection, and the
  18082. // response says so rather than leaving the peer to discover it.
  18083. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18084. bool announced_close = false;
  18085. bool reusable = true;
  18086. probe_connection_reuse(port_,
  18087. "GET /keepalive HTTP/1.1\r\n"
  18088. "Host: localhost\r\n"
  18089. "Connection: keep-alive, close\r\n"
  18090. "\r\n",
  18091. &announced_close, &reusable);
  18092. EXPECT_TRUE(announced_close);
  18093. EXPECT_FALSE(reusable);
  18094. }
  18095. // "close" split over two field lines is the same list, so it is honored too.
  18096. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18097. bool announced_close = false;
  18098. bool reusable = true;
  18099. probe_connection_reuse(port_,
  18100. "GET /keepalive HTTP/1.1\r\n"
  18101. "Host: localhost\r\n"
  18102. "Connection: keep-alive\r\n"
  18103. "Connection: close\r\n"
  18104. "\r\n",
  18105. &announced_close, &reusable);
  18106. EXPECT_TRUE(announced_close);
  18107. EXPECT_FALSE(reusable);
  18108. }
  18109. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18110. // keep-alive in the spelling everyone actually sends keeps its connection.
  18111. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18112. bool announced_close = false;
  18113. bool reusable = false;
  18114. probe_connection_reuse(port_,
  18115. "GET /keepalive HTTP/1.0\r\n"
  18116. "Host: localhost\r\n"
  18117. "Connection: keep-alive\r\n"
  18118. "\r\n",
  18119. &announced_close, &reusable);
  18120. EXPECT_FALSE(announced_close);
  18121. EXPECT_TRUE(reusable);
  18122. }
  18123. // A token the value merely contains is not the token itself.
  18124. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  18125. bool announced_close = false;
  18126. bool reusable = false;
  18127. probe_connection_reuse(port_,
  18128. "GET /keepalive HTTP/1.1\r\n"
  18129. "Host: localhost\r\n"
  18130. "Connection: notclose\r\n"
  18131. "\r\n",
  18132. &announced_close, &reusable);
  18133. EXPECT_FALSE(announced_close);
  18134. EXPECT_TRUE(reusable);
  18135. }
  18136. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  18137. Server svr;
  18138. std::vector<std::string> observed_types;
  18139. svr.Get("/", [&](const Request &req, Response &res) {
  18140. observed_types = req.accept_content_types;
  18141. res.set_content("ok", "text/plain");
  18142. });
  18143. auto port = svr.bind_to_any_port(HOST);
  18144. thread t = thread([&]() { svr.listen_after_bind(); });
  18145. auto se = detail::scope_exit([&] {
  18146. svr.stop();
  18147. t.join();
  18148. ASSERT_FALSE(svr.is_running());
  18149. });
  18150. svr.wait_until_ready();
  18151. Client cli(HOST, port);
  18152. Headers headers;
  18153. headers.emplace("Accept", "text/plain;q=0.5");
  18154. headers.emplace("Accept", "application/json");
  18155. auto res = cli.Get("/", headers);
  18156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18157. EXPECT_EQ(StatusCode::OK_200, res->status);
  18158. // Sorted by q-value, so the second field line's type comes first
  18159. ASSERT_EQ(2U, observed_types.size());
  18160. EXPECT_EQ("application/json", observed_types[0]);
  18161. EXPECT_EQ("text/plain", observed_types[1]);
  18162. }
  18163. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  18164. // empty field line must not contribute a bare comma to the combined value.
  18165. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  18166. Server svr;
  18167. std::vector<std::string> observed_types;
  18168. svr.Get("/", [&](const Request &req, Response &res) {
  18169. observed_types = req.accept_content_types;
  18170. res.set_content("ok", "text/plain");
  18171. });
  18172. auto port = svr.bind_to_any_port(HOST);
  18173. thread t = thread([&]() { svr.listen_after_bind(); });
  18174. auto se = detail::scope_exit([&] {
  18175. svr.stop();
  18176. t.join();
  18177. ASSERT_FALSE(svr.is_running());
  18178. });
  18179. svr.wait_until_ready();
  18180. // Empty first field line, then a real one
  18181. std::string raw_req = "GET / HTTP/1.1\r\n"
  18182. "Host: localhost\r\n"
  18183. "Accept:\r\n"
  18184. "Accept: application/json\r\n"
  18185. "Connection: close\r\n"
  18186. "\r\n";
  18187. std::string out;
  18188. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18189. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18190. ASSERT_EQ(1U, observed_types.size());
  18191. EXPECT_EQ("application/json", observed_types[0]);
  18192. }
  18193. // The skip in get_combined_header_value() is what keeps an empty field line
  18194. // from contributing a bare comma. Only a trailing empty field line exercises
  18195. // it: a leading one is already covered by the "combined is still empty" check,
  18196. // and parse_accept_header() now ignores the empty element either way, so the
  18197. // request-level test above can no longer tell the two apart.
  18198. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  18199. Headers headers;
  18200. headers.emplace("Accept", "text/html");
  18201. headers.emplace("Accept", "");
  18202. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  18203. headers.clear();
  18204. headers.emplace("Accept", "");
  18205. headers.emplace("Accept", "application/json");
  18206. EXPECT_EQ("application/json",
  18207. detail::get_combined_header_value(headers, "Accept"));
  18208. }
  18209. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18210. // An encoding offered on a later Accept-Encoding field line is still offered.
  18211. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  18212. Server svr;
  18213. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18214. res.set_content(std::string(1024, 'x'), "text/plain");
  18215. });
  18216. auto port = svr.bind_to_any_port(HOST);
  18217. thread t = thread([&]() { svr.listen_after_bind(); });
  18218. auto se = detail::scope_exit([&] {
  18219. svr.stop();
  18220. t.join();
  18221. ASSERT_FALSE(svr.is_running());
  18222. });
  18223. svr.wait_until_ready();
  18224. Client cli(HOST, port);
  18225. cli.set_decompress(false);
  18226. Headers headers;
  18227. headers.emplace("Accept-Encoding", "identity");
  18228. headers.emplace("Accept-Encoding", "gzip");
  18229. auto res = cli.Get("/", headers);
  18230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18231. EXPECT_EQ(StatusCode::OK_200, res->status);
  18232. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  18233. }
  18234. #endif
  18235. #ifndef _WIN32
  18236. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  18237. Server svr;
  18238. svr.Post("/post", [&](const Request &req, Response &res) {
  18239. res.set_content(req.body, "text/plain");
  18240. });
  18241. svr.Put("/put", [&](const Request &req, Response &res) {
  18242. res.set_content(req.body, "text/plain");
  18243. });
  18244. svr.Patch("/patch", [&](const Request &req, Response &res) {
  18245. res.set_content(req.body, "text/plain");
  18246. });
  18247. svr.Delete("/delete", [&](const Request &req, Response &res) {
  18248. res.set_content(req.body, "text/plain");
  18249. });
  18250. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18251. auto se = detail::scope_exit([&] {
  18252. svr.stop();
  18253. t.join();
  18254. ASSERT_FALSE(svr.is_running());
  18255. });
  18256. svr.wait_until_ready();
  18257. std::string resp;
  18258. // POST without Content-Length
  18259. ASSERT_TRUE(send_request(5,
  18260. "POST /post HTTP/1.1\r\n"
  18261. "Host: localhost\r\n"
  18262. "Connection: close\r\n"
  18263. "\r\n",
  18264. &resp));
  18265. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18266. // PUT without Content-Length
  18267. resp.clear();
  18268. ASSERT_TRUE(send_request(5,
  18269. "PUT /put HTTP/1.1\r\n"
  18270. "Host: localhost\r\n"
  18271. "Connection: close\r\n"
  18272. "\r\n",
  18273. &resp));
  18274. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18275. // PATCH without Content-Length
  18276. resp.clear();
  18277. ASSERT_TRUE(send_request(5,
  18278. "PATCH /patch HTTP/1.1\r\n"
  18279. "Host: localhost\r\n"
  18280. "Connection: close\r\n"
  18281. "\r\n",
  18282. &resp));
  18283. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18284. // DELETE without Content-Length
  18285. resp.clear();
  18286. ASSERT_TRUE(send_request(5,
  18287. "DELETE /delete HTTP/1.1\r\n"
  18288. "Host: localhost\r\n"
  18289. "Connection: close\r\n"
  18290. "\r\n",
  18291. &resp));
  18292. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18293. }
  18294. #endif
  18295. //==============================================================================
  18296. // open_stream() Tests
  18297. //==============================================================================
  18298. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  18299. std::string result;
  18300. char buf[8192];
  18301. ssize_t n;
  18302. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18303. result.append(buf, static_cast<size_t>(n));
  18304. }
  18305. return result;
  18306. }
  18307. // Mock stream for unit tests
  18308. class MockStream : public Stream {
  18309. public:
  18310. std::string data;
  18311. size_t pos = 0;
  18312. ssize_t error_after = -1; // -1 = no error
  18313. explicit MockStream(const std::string &d, ssize_t err = -1)
  18314. : data(d), error_after(err) {}
  18315. bool is_readable() const override { return true; }
  18316. bool wait_readable() const override { return true; }
  18317. bool wait_writable() const override { return true; }
  18318. ssize_t read(char *ptr, size_t size) override {
  18319. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  18320. if (pos >= data.size()) return 0;
  18321. size_t limit =
  18322. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  18323. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  18324. std::memcpy(ptr, data.data() + pos, to_read);
  18325. pos += to_read;
  18326. return static_cast<ssize_t>(to_read);
  18327. }
  18328. ssize_t write(const char *, size_t) override { return -1; }
  18329. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  18330. ip = "127.0.0.1";
  18331. port = 0;
  18332. }
  18333. void get_local_ip_and_port(std::string &ip, int &port) const override {
  18334. ip = "127.0.0.1";
  18335. port = 0;
  18336. }
  18337. socket_t socket() const override { return INVALID_SOCKET; }
  18338. time_t duration() const override { return 0; }
  18339. };
  18340. TEST(StreamHandleTest, Basic) {
  18341. ClientImpl::StreamHandle handle;
  18342. EXPECT_FALSE(handle.is_valid());
  18343. handle.response = detail::make_unique<Response>();
  18344. handle.error = Error::Connection;
  18345. EXPECT_FALSE(handle.is_valid());
  18346. handle.error = Error::Success;
  18347. EXPECT_TRUE(handle.is_valid());
  18348. }
  18349. TEST(BodyReaderTest, Basic) {
  18350. MockStream stream("Hello, World!");
  18351. detail::BodyReader reader;
  18352. reader.stream = &stream;
  18353. reader.content_length = 13;
  18354. char buf[32];
  18355. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18356. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18357. EXPECT_TRUE(reader.eof);
  18358. }
  18359. TEST(BodyReaderTest, NoStream) {
  18360. detail::BodyReader reader;
  18361. char buf[32];
  18362. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18363. EXPECT_EQ(Error::Connection, reader.last_error);
  18364. }
  18365. TEST(BodyReaderTest, Error) {
  18366. MockStream stream("Hello, World!", 5);
  18367. detail::BodyReader reader;
  18368. reader.stream = &stream;
  18369. reader.content_length = 13;
  18370. char buf[32];
  18371. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18372. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18373. EXPECT_EQ(Error::Read, reader.last_error);
  18374. }
  18375. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18376. // Mock-based StreamHandle tests relying on private internals are removed.
  18377. class OpenStreamTest : public ::testing::Test {
  18378. protected:
  18379. void SetUp() override {
  18380. svr_.Get("/hello", [](const Request &, Response &res) {
  18381. res.set_content("Hello World!", "text/plain");
  18382. });
  18383. svr_.Get("/large", [](const Request &, Response &res) {
  18384. res.set_content(std::string(10000, 'X'), "text/plain");
  18385. });
  18386. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18387. res.set_content("Hello World!", "image/jpeg");
  18388. res.set_header("Content-Encoding", "UTF-8");
  18389. });
  18390. svr_.Get("/chunked", [](const Request &, Response &res) {
  18391. res.set_chunked_content_provider("text/plain",
  18392. [](size_t offset, DataSink &sink) {
  18393. if (offset < 15) {
  18394. sink.write("chunk", 5);
  18395. return true;
  18396. }
  18397. sink.done();
  18398. return true;
  18399. });
  18400. });
  18401. svr_.Get("/compressible", [](const Request &, Response &res) {
  18402. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18403. DataSink &sink) {
  18404. if (offset < 100 * 1024) {
  18405. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18406. sink.write(chunk.data(), chunk.size());
  18407. return true;
  18408. }
  18409. sink.done();
  18410. return true;
  18411. });
  18412. });
  18413. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18414. [](const Request & /*req*/, Response &res) {
  18415. auto i = new int(0);
  18416. res.set_header("Trailer", "Content-Length, X-Allowed");
  18417. res.set_chunked_content_provider(
  18418. "text/plain",
  18419. [i](size_t /*offset*/, DataSink &sink) {
  18420. switch (*i) {
  18421. case 0: sink.os << "123"; break;
  18422. case 1: sink.os << "456"; break;
  18423. case 2: sink.os << "789"; break;
  18424. case 3: {
  18425. sink.done_with_trailer(
  18426. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18427. } break;
  18428. }
  18429. (*i)++;
  18430. return true;
  18431. },
  18432. [i](bool success) {
  18433. EXPECT_TRUE(success);
  18434. delete i;
  18435. });
  18436. });
  18437. // Echo headers endpoint for header-related tests
  18438. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18439. std::string body;
  18440. for (const auto &h : req.headers) {
  18441. body.append(h.first);
  18442. body.push_back(':');
  18443. body.append(h.second);
  18444. body.push_back('\n');
  18445. }
  18446. res.set_content(body, "text/plain");
  18447. });
  18448. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18449. std::string body;
  18450. for (const auto &h : req.headers) {
  18451. body.append(h.first);
  18452. body.push_back(':');
  18453. body.append(h.second);
  18454. body.push_back('\n');
  18455. }
  18456. res.set_content(body, "text/plain");
  18457. });
  18458. port_ = svr_.bind_to_any_port("127.0.0.1");
  18459. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18460. svr_.wait_until_ready();
  18461. }
  18462. void TearDown() override {
  18463. svr_.stop();
  18464. if (thread_.joinable()) thread_.join();
  18465. }
  18466. Server svr_;
  18467. std::thread thread_;
  18468. int port_ = 0;
  18469. };
  18470. TEST_F(OpenStreamTest, Basic) {
  18471. Client cli("127.0.0.1", port_);
  18472. auto handle = cli.open_stream("GET", "/hello");
  18473. EXPECT_TRUE(handle.is_valid());
  18474. EXPECT_EQ("Hello World!", read_all(handle));
  18475. }
  18476. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18477. Client cli("127.0.0.1", port_);
  18478. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18479. ASSERT_TRUE(handle.is_valid());
  18480. EXPECT_EQ("Hello World!", read_all(handle));
  18481. }
  18482. TEST_F(OpenStreamTest, SmallBuffer) {
  18483. Client cli("127.0.0.1", port_);
  18484. auto handle = cli.open_stream("GET", "/hello");
  18485. std::string result;
  18486. char buf[4];
  18487. ssize_t n;
  18488. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18489. result.append(buf, static_cast<size_t>(n));
  18490. EXPECT_EQ("Hello World!", result);
  18491. }
  18492. TEST_F(OpenStreamTest, DefaultHeaders) {
  18493. Client cli("127.0.0.1", port_);
  18494. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18495. {
  18496. auto handle = cli.open_stream("GET", "/echo-headers");
  18497. ASSERT_TRUE(handle.is_valid());
  18498. auto body = read_all(handle);
  18499. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18500. std::string::npos);
  18501. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18502. std::string::npos);
  18503. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18504. }
  18505. // open_stream POST with body and no explicit content_type should NOT add
  18506. // text/plain Content-Type (behavior differs from non-streaming path), but
  18507. // should include Content-Length
  18508. {
  18509. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18510. ASSERT_TRUE(handle.is_valid());
  18511. auto body = read_all(handle);
  18512. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18513. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18514. }
  18515. // open_stream POST with explicit Content-Type should preserve it
  18516. {
  18517. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18518. {{"Content-Type", "application/custom"}},
  18519. "{}", "application/custom");
  18520. ASSERT_TRUE(handle.is_valid());
  18521. auto body = read_all(handle);
  18522. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18523. }
  18524. // User-specified User-Agent must not be overwritten for stream API
  18525. {
  18526. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18527. {{"User-Agent", "MyAgent/1.2"}});
  18528. ASSERT_TRUE(handle.is_valid());
  18529. auto body = read_all(handle);
  18530. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18531. }
  18532. }
  18533. TEST_F(OpenStreamTest, Large) {
  18534. Client cli("127.0.0.1", port_);
  18535. auto handle = cli.open_stream("GET", "/large");
  18536. EXPECT_EQ(10000u, read_all(handle).size());
  18537. }
  18538. TEST_F(OpenStreamTest, ConnectionError) {
  18539. Client cli("127.0.0.1", 9999);
  18540. auto handle = cli.open_stream("GET", "/hello");
  18541. EXPECT_FALSE(handle.is_valid());
  18542. }
  18543. TEST_F(OpenStreamTest, Chunked) {
  18544. Client cli("127.0.0.1", port_);
  18545. auto handle = cli.open_stream("GET", "/chunked");
  18546. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18547. "Transfer-Encoding") == "chunked");
  18548. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18549. }
  18550. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18551. Client cli("127.0.0.1", port_);
  18552. auto handle =
  18553. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18554. ASSERT_TRUE(handle.is_valid());
  18555. // Consume body to allow trailers to be received/parsed
  18556. auto body = read_all(handle);
  18557. // Explicitly parse trailers (ensure trailers are available for assertion)
  18558. handle.parse_trailers_if_needed();
  18559. EXPECT_EQ(std::string("123456789"), body);
  18560. // The response should include a Trailer header declaring both names
  18561. ASSERT_TRUE(handle.response);
  18562. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18563. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18564. handle.response->get_header_value("Trailer"));
  18565. // Prohibited trailer must not be present
  18566. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18567. // Allowed trailer should be present
  18568. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18569. EXPECT_EQ(std::string("yes"),
  18570. handle.response->get_trailer_value("X-Allowed"));
  18571. // Verify trailers are NOT present as regular headers
  18572. EXPECT_EQ(std::string(""),
  18573. handle.response->get_header_value("Content-Length"));
  18574. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18575. }
  18576. static std::thread serve_single_response(std::promise<int> &port_promise,
  18577. const std::string &response) {
  18578. return std::thread([&port_promise, response] {
  18579. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18580. default_socket_options(srv);
  18581. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18582. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18583. sockaddr_in addr{};
  18584. addr.sin_family = AF_INET;
  18585. addr.sin_port = htons(0); // Let OS assign a free port
  18586. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18587. int opt = 1;
  18588. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18589. #ifdef _WIN32
  18590. reinterpret_cast<const char *>(&opt),
  18591. #else
  18592. &opt,
  18593. #endif
  18594. sizeof(opt));
  18595. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18596. ::listen(srv, 1) != 0) {
  18597. port_promise.set_value(-1);
  18598. detail::close_socket(srv);
  18599. return;
  18600. }
  18601. socklen_t addr_len = sizeof(addr);
  18602. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18603. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18604. sockaddr_in cli_addr{};
  18605. socklen_t cli_len = sizeof(cli_addr);
  18606. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18607. if (cli != INVALID_SOCKET) {
  18608. // Read the complete HTTP request (until the blank line that terminates
  18609. // headers) before sending the response. If the server closes the socket
  18610. // while the client's request data is still unread in the kernel receive
  18611. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18612. // connection on both sides: it discards the client's receive buffer
  18613. // (which already holds our response) and causes any in-progress write on
  18614. // the client to fail with ECONNRESET. Reading all request data first
  18615. // ensures close() emits a graceful FIN.
  18616. {
  18617. char rbuf[256];
  18618. std::string req;
  18619. while (req.find("\r\n\r\n") == std::string::npos) {
  18620. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18621. if (n <= 0) { break; }
  18622. req.append(rbuf, static_cast<size_t>(n));
  18623. }
  18624. }
  18625. ::send(cli,
  18626. #ifdef _WIN32
  18627. static_cast<const char *>(response.c_str()),
  18628. static_cast<int>(response.size()),
  18629. #else
  18630. response.c_str(), response.size(),
  18631. #endif
  18632. 0);
  18633. detail::close_socket(cli);
  18634. }
  18635. detail::close_socket(srv);
  18636. });
  18637. }
  18638. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18639. #ifndef _WIN32
  18640. signal(SIGPIPE, SIG_IGN);
  18641. #endif
  18642. std::promise<int> port_promise;
  18643. auto port_future = port_promise.get_future();
  18644. auto server_thread =
  18645. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18646. "Content-Type: text/plain\r\n"
  18647. "Content-Length: not-a-number\r\n"
  18648. "Connection: close\r\n"
  18649. "\r\n"
  18650. "hello");
  18651. auto port = port_future.get();
  18652. ASSERT_GT(port, 0);
  18653. Client cli("127.0.0.1", port);
  18654. auto handle = cli.open_stream("GET", "/");
  18655. EXPECT_FALSE(handle.is_valid());
  18656. server_thread.join();
  18657. }
  18658. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18659. #ifndef _WIN32
  18660. signal(SIGPIPE, SIG_IGN);
  18661. #endif
  18662. std::promise<int> port_promise;
  18663. auto port_future = port_promise.get_future();
  18664. auto server_thread = serve_single_response(
  18665. port_promise, "HTTP/1.1 200 OK\r\n"
  18666. "Content-Type: text/plain\r\n"
  18667. "Content-Length: 99999999999999999999999999\r\n"
  18668. "Connection: close\r\n"
  18669. "\r\n"
  18670. "hello");
  18671. auto port = port_future.get();
  18672. ASSERT_GT(port, 0);
  18673. // Historically std::stoull would throw std::out_of_range here and crash
  18674. // the process, then parsing silently clamped to a bogus framing length and
  18675. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18676. // so the stream fails to open, matching the not-a-number case above. The
  18677. // process still must NOT terminate.
  18678. Client cli("127.0.0.1", port);
  18679. auto handle = cli.open_stream("GET", "/");
  18680. EXPECT_FALSE(handle.is_valid());
  18681. server_thread.join();
  18682. }
  18683. // Serves `response` to the single request `fn` makes with a fresh client.
  18684. template <typename Fn>
  18685. static void with_single_response(const std::string &response, Fn fn) {
  18686. #ifndef _WIN32
  18687. signal(SIGPIPE, SIG_IGN);
  18688. #endif
  18689. std::promise<int> port_promise;
  18690. auto port_future = port_promise.get_future();
  18691. auto server_thread = serve_single_response(port_promise, response);
  18692. auto se = detail::scope_exit([&] { server_thread.join(); });
  18693. auto port = port_future.get();
  18694. ASSERT_GT(port, 0);
  18695. Client cli("127.0.0.1", port);
  18696. fn(cli);
  18697. }
  18698. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18699. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18700. // the chunked coding and drop Content-Length, so a front-end that trusts
  18701. // Content-Length would disagree about where the body ends (response
  18702. // smuggling). The client must reject such a response.
  18703. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18704. for (const char *te : {"chunked", "gzip, chunked"}) {
  18705. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18706. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18707. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18708. "5\r\nhello\r\n0\r\n\r\n";
  18709. with_single_response(response, [&](Client &cli) {
  18710. auto res = cli.Get("/");
  18711. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18712. EXPECT_EQ(Error::Read, res.error()) << te;
  18713. });
  18714. with_single_response(response, [&](Client &cli) {
  18715. auto handle = cli.open_stream("GET", "/");
  18716. EXPECT_FALSE(handle.is_valid()) << te;
  18717. EXPECT_EQ(Error::Read, handle.error) << te;
  18718. });
  18719. }
  18720. }
  18721. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18722. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18723. // closing the connection (unlike a request, which must be rejected).
  18724. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18725. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18726. "Transfer-Encoding: chunked\r\n"
  18727. "Connection: close\r\n"
  18728. "\r\n"
  18729. "5\r\nhello\r\n0\r\n\r\n",
  18730. "HTTP/1.1 200 OK\r\n"
  18731. "Transfer-Encoding: gzip\r\n"
  18732. "Connection: close\r\n"
  18733. "\r\n"
  18734. "hello"}) {
  18735. with_single_response(response, [&](Client &cli) {
  18736. auto res = cli.Get("/");
  18737. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18738. EXPECT_EQ("hello", res->body);
  18739. });
  18740. with_single_response(response, [&](Client &cli) {
  18741. auto handle = cli.open_stream("GET", "/");
  18742. ASSERT_TRUE(handle.is_valid()) << response;
  18743. EXPECT_EQ("hello", read_all(handle));
  18744. });
  18745. }
  18746. }
  18747. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18748. // framing headers describe nothing to read and must not be rejected.
  18749. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18750. const std::string framing = "Content-Length: 5\r\n"
  18751. "Transfer-Encoding: chunked\r\n"
  18752. "Connection: close\r\n"
  18753. "\r\n";
  18754. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18755. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18756. });
  18757. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18758. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18759. });
  18760. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18761. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18762. with_single_response(response, [&](Client &cli) {
  18763. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18764. });
  18765. with_single_response(response, [&](Client &cli) {
  18766. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18767. });
  18768. }
  18769. }
  18770. // A payload max length of 0 means no limit, however the body is framed.
  18771. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18772. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18773. "Transfer-Encoding: chunked\r\n"
  18774. "\r\n"
  18775. "5\r\nhello\r\n0\r\n\r\n",
  18776. "HTTP/1.1 200 OK\r\n"
  18777. "Connection: close\r\n"
  18778. "\r\n"
  18779. "hello"}) {
  18780. with_single_response(response, [&](Client &cli) {
  18781. cli.set_payload_max_length(0);
  18782. auto res = cli.Get("/");
  18783. ASSERT_TRUE(res) << response;
  18784. EXPECT_EQ("hello", res->body) << response;
  18785. });
  18786. }
  18787. }
  18788. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18789. Server svr;
  18790. svr.set_payload_max_length(0);
  18791. svr.Post("/echo", [](const Request &req, Response &res) {
  18792. res.set_content(req.body, "text/plain");
  18793. });
  18794. auto port = svr.bind_to_any_port(HOST);
  18795. thread t = thread([&] { svr.listen_after_bind(); });
  18796. auto se = detail::scope_exit([&] {
  18797. svr.stop();
  18798. t.join();
  18799. ASSERT_FALSE(svr.is_running());
  18800. });
  18801. svr.wait_until_ready();
  18802. Client cli(HOST, port);
  18803. auto res = cli.Post(
  18804. "/echo",
  18805. [](size_t /*offset*/, DataSink &sink) {
  18806. sink.write("hello", 5);
  18807. sink.done();
  18808. return true;
  18809. },
  18810. "text/plain");
  18811. ASSERT_TRUE(res);
  18812. EXPECT_EQ(StatusCode::OK_200, res->status);
  18813. EXPECT_EQ("hello", res->body);
  18814. }
  18815. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18816. TEST_F(OpenStreamTest, Gzip) {
  18817. Client cli("127.0.0.1", port_);
  18818. auto handle = cli.open_stream("GET", "/compressible", {},
  18819. {{"Accept-Encoding", "gzip"}});
  18820. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18821. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18822. }
  18823. #endif
  18824. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18825. TEST_F(OpenStreamTest, Brotli) {
  18826. Client cli("127.0.0.1", port_);
  18827. auto handle =
  18828. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18829. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18830. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18831. }
  18832. #endif
  18833. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18834. TEST_F(OpenStreamTest, Zstd) {
  18835. Client cli("127.0.0.1", port_);
  18836. auto handle = cli.open_stream("GET", "/compressible", {},
  18837. {{"Accept-Encoding", "zstd"}});
  18838. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18839. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18840. }
  18841. #endif
  18842. #ifdef CPPHTTPLIB_SSL_ENABLED
  18843. class SSLOpenStreamTest : public ::testing::Test {
  18844. protected:
  18845. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18846. void SetUp() override {
  18847. svr_.Get("/hello", [](const Request &, Response &res) {
  18848. res.set_content("Hello SSL World!", "text/plain");
  18849. });
  18850. svr_.Get("/chunked", [](const Request &, Response &res) {
  18851. res.set_chunked_content_provider("text/plain",
  18852. [](size_t offset, DataSink &sink) {
  18853. if (offset < 15) {
  18854. sink.write("chunk", 5);
  18855. return true;
  18856. }
  18857. sink.done();
  18858. return true;
  18859. });
  18860. });
  18861. svr_.Post("/echo", [](const Request &req, Response &res) {
  18862. res.set_content(req.body, req.get_header_value("Content-Type"));
  18863. });
  18864. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18865. std::string body = req.body;
  18866. res.set_chunked_content_provider(
  18867. "text/plain", [body](size_t offset, DataSink &sink) {
  18868. if (offset < body.size()) {
  18869. sink.write(body.data() + offset, body.size() - offset);
  18870. }
  18871. sink.done();
  18872. return true;
  18873. });
  18874. });
  18875. port_ = svr_.bind_to_any_port("127.0.0.1");
  18876. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18877. svr_.wait_until_ready();
  18878. }
  18879. void TearDown() override {
  18880. svr_.stop();
  18881. if (thread_.joinable()) thread_.join();
  18882. }
  18883. SSLServer svr_;
  18884. std::thread thread_;
  18885. int port_ = 0;
  18886. };
  18887. TEST_F(SSLOpenStreamTest, Basic) {
  18888. SSLClient cli("127.0.0.1", port_);
  18889. cli.enable_server_certificate_verification(false);
  18890. auto handle = cli.open_stream("GET", "/hello");
  18891. ASSERT_TRUE(handle.is_valid());
  18892. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18893. }
  18894. TEST_F(SSLOpenStreamTest, Chunked) {
  18895. SSLClient cli("127.0.0.1", port_);
  18896. cli.enable_server_certificate_verification(false);
  18897. auto handle = cli.open_stream("GET", "/chunked");
  18898. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18899. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18900. "Transfer-Encoding") == "chunked");
  18901. auto body = read_all(handle);
  18902. EXPECT_EQ("chunkchunkchunk", body);
  18903. }
  18904. TEST_F(SSLOpenStreamTest, Post) {
  18905. SSLClient cli("127.0.0.1", port_);
  18906. cli.enable_server_certificate_verification(false);
  18907. auto handle =
  18908. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  18909. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18910. EXPECT_EQ(200, handle.response->status);
  18911. auto body = read_all(handle);
  18912. EXPECT_EQ("Hello SSL POST", body);
  18913. }
  18914. TEST_F(SSLOpenStreamTest, PostChunked) {
  18915. SSLClient cli("127.0.0.1", port_);
  18916. cli.enable_server_certificate_verification(false);
  18917. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  18918. "Chunked SSL Data", "text/plain");
  18919. ASSERT_TRUE(handle.is_valid());
  18920. EXPECT_EQ(200, handle.response->status);
  18921. auto body = read_all(handle);
  18922. EXPECT_EQ("Chunked SSL Data", body);
  18923. }
  18924. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  18925. // Content-Length is terminated by the server closing the connection. When the
  18926. // SSL peer sends a close_notify after the body, the client must treat it as a
  18927. // clean EOF and return a successful response rather than an error.
  18928. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  18929. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18930. ASSERT_TRUE(svr.is_valid());
  18931. svr.set_keep_alive_max_count(1);
  18932. const std::string expected_body = "Hello from connection-close response!";
  18933. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  18934. res.set_content_provider("text/plain",
  18935. [&](size_t offset, DataSink &sink) -> bool {
  18936. if (offset < expected_body.size()) {
  18937. sink.write(expected_body.data() + offset,
  18938. expected_body.size() - offset);
  18939. }
  18940. sink.done();
  18941. return true;
  18942. });
  18943. });
  18944. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  18945. auto se = detail::scope_exit([&] {
  18946. svr.stop();
  18947. listen_thread.join();
  18948. ASSERT_FALSE(svr.is_running());
  18949. });
  18950. svr.wait_until_ready();
  18951. SSLClient cli(HOST, PORT);
  18952. cli.enable_server_certificate_verification(false);
  18953. auto res = cli.Get("/no-content-length");
  18954. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18955. EXPECT_EQ(StatusCode::OK_200, res->status);
  18956. EXPECT_EQ(expected_body, res->body);
  18957. }
  18958. #endif // CPPHTTPLIB_SSL_ENABLED
  18959. //==============================================================================
  18960. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18961. // results for various scenarios.
  18962. //==============================================================================
  18963. TEST(ParityTest, GetVsOpenStream) {
  18964. Server svr;
  18965. const std::string path = "/parity";
  18966. const std::string content = "Parity test content: hello world";
  18967. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18968. res.set_content(content, "text/plain");
  18969. });
  18970. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18971. auto se = detail::scope_exit([&] {
  18972. svr.stop();
  18973. t.join();
  18974. ASSERT_FALSE(svr.is_running());
  18975. });
  18976. svr.wait_until_ready();
  18977. Client cli(HOST, PORT);
  18978. // Non-stream path
  18979. auto r1 = cli.Get(path);
  18980. ASSERT_TRUE(r1);
  18981. EXPECT_EQ(StatusCode::OK_200, r1->status);
  18982. // Stream path
  18983. auto h = cli.open_stream("GET", path);
  18984. ASSERT_TRUE(h.is_valid());
  18985. EXPECT_EQ(r1->body, read_all(h));
  18986. }
  18987. // Helper to compress data with provided compressor type T
  18988. template <typename Compressor>
  18989. static std::string compress_payload_for_parity(const std::string &in) {
  18990. std::string out;
  18991. Compressor compressor;
  18992. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  18993. [&](const char *data, size_t n) {
  18994. out.append(data, n);
  18995. return true;
  18996. });
  18997. EXPECT_TRUE(ok);
  18998. return out;
  18999. }
  19000. // Helper function for compression parity tests
  19001. template <typename Compressor>
  19002. static void test_compression_parity(const std::string &original,
  19003. const std::string &path,
  19004. const std::string &encoding) {
  19005. const std::string compressed =
  19006. compress_payload_for_parity<Compressor>(original);
  19007. Server svr;
  19008. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19009. res.set_content(compressed, "application/octet-stream");
  19010. res.set_header("Content-Encoding", encoding);
  19011. });
  19012. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  19013. auto se = detail::scope_exit([&] {
  19014. svr.stop();
  19015. t.join();
  19016. ASSERT_FALSE(svr.is_running());
  19017. });
  19018. svr.wait_until_ready();
  19019. Client cli(HOST, PORT);
  19020. // Non-streaming
  19021. {
  19022. auto res = cli.Get(path);
  19023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19024. EXPECT_EQ(StatusCode::OK_200, res->status);
  19025. EXPECT_EQ(original, res->body);
  19026. }
  19027. // Streaming
  19028. {
  19029. auto h = cli.open_stream("GET", path);
  19030. ASSERT_TRUE(h.is_valid());
  19031. EXPECT_EQ(original, read_all(h));
  19032. }
  19033. }
  19034. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19035. TEST(ParityTest, Gzip) {
  19036. test_compression_parity<detail::gzip_compressor>(
  19037. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  19038. }
  19039. #endif
  19040. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19041. TEST(ParityTest, Brotli) {
  19042. test_compression_parity<detail::brotli_compressor>(
  19043. "Hello, brotli parity test payload", "/parity-br", "br");
  19044. }
  19045. #endif
  19046. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19047. TEST(ParityTest, Zstd) {
  19048. test_compression_parity<detail::zstd_compressor>(
  19049. "Zstandard parity test payload", "/parity-zstd", "zstd");
  19050. }
  19051. #endif
  19052. //==============================================================================
  19053. // New Stream API Tests
  19054. //==============================================================================
  19055. inline std::string read_body(httplib::stream::Result &result) {
  19056. std::string body;
  19057. while (result.next()) {
  19058. body.append(result.data(), result.size());
  19059. }
  19060. return body;
  19061. }
  19062. TEST(ClientConnectionTest, Basic) {
  19063. httplib::ClientConnection conn;
  19064. EXPECT_FALSE(conn.is_open());
  19065. conn.sock = 1;
  19066. EXPECT_TRUE(conn.is_open());
  19067. httplib::ClientConnection conn2(std::move(conn));
  19068. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  19069. conn2.sock = INVALID_SOCKET;
  19070. }
  19071. // Unified test server for all stream::* tests
  19072. class StreamApiTest : public ::testing::Test {
  19073. protected:
  19074. void SetUp() override {
  19075. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19076. res.set_content("Hello World!", "text/plain");
  19077. });
  19078. svr_.Get("/echo-params",
  19079. [](const httplib::Request &req, httplib::Response &res) {
  19080. std::string r;
  19081. for (const auto &p : req.params) {
  19082. if (!r.empty()) r += "&";
  19083. r += p.first + "=" + p.second;
  19084. }
  19085. res.set_content(r, "text/plain");
  19086. });
  19087. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19088. res.set_content(req.body, req.get_header_value("Content-Type"));
  19089. });
  19090. svr_.Post("/echo-headers",
  19091. [](const httplib::Request &req, httplib::Response &res) {
  19092. std::string r;
  19093. for (const auto &h : req.headers)
  19094. r += h.first + ": " + h.second + "\n";
  19095. res.set_content(r, "text/plain");
  19096. });
  19097. svr_.Post("/echo-params",
  19098. [](const httplib::Request &req, httplib::Response &res) {
  19099. std::string r = "params:";
  19100. for (const auto &p : req.params)
  19101. r += p.first + "=" + p.second + ";";
  19102. res.set_content(r + " body:" + req.body, "text/plain");
  19103. });
  19104. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  19105. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  19106. });
  19107. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19108. res.set_content("PUT:" + req.body, "text/plain");
  19109. });
  19110. svr_.Patch("/echo",
  19111. [](const httplib::Request &req, httplib::Response &res) {
  19112. res.set_content("PATCH:" + req.body, "text/plain");
  19113. });
  19114. svr_.Delete(
  19115. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  19116. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  19117. "text/plain");
  19118. });
  19119. svr_.Get("/head-test",
  19120. [](const httplib::Request &, httplib::Response &res) {
  19121. res.set_content("body for HEAD", "text/plain");
  19122. });
  19123. svr_.Options("/options",
  19124. [](const httplib::Request &, httplib::Response &res) {
  19125. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  19126. });
  19127. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  19128. svr_.wait_until_ready();
  19129. }
  19130. void TearDown() override {
  19131. svr_.stop();
  19132. if (thread_.joinable()) thread_.join();
  19133. }
  19134. httplib::Server svr_;
  19135. std::thread thread_;
  19136. };
  19137. // stream::Get tests
  19138. TEST_F(StreamApiTest, GetBasic) {
  19139. httplib::Client cli(HOST, PORT);
  19140. auto result = httplib::stream::Get(cli, "/hello");
  19141. ASSERT_TRUE(result.is_valid());
  19142. EXPECT_EQ(200, result.status());
  19143. EXPECT_EQ("Hello World!", read_body(result));
  19144. }
  19145. TEST_F(StreamApiTest, GetWithParams) {
  19146. httplib::Client cli(HOST, PORT);
  19147. httplib::Params params{{"foo", "bar"}};
  19148. auto result = httplib::stream::Get(cli, "/echo-params", params);
  19149. ASSERT_TRUE(result.is_valid());
  19150. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  19151. }
  19152. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19153. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  19154. httplib::Client cli(HOST, PORT);
  19155. cli.set_payload_max_length(0);
  19156. auto result = httplib::stream::Get(cli, "/hello");
  19157. ASSERT_TRUE(result.is_valid());
  19158. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  19159. EXPECT_EQ("Hello World!", read_body(result));
  19160. }
  19161. #endif
  19162. TEST_F(StreamApiTest, GetConnectionError) {
  19163. httplib::Client cli(HOST, 9999);
  19164. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  19165. }
  19166. TEST_F(StreamApiTest, Get404) {
  19167. httplib::Client cli(HOST, PORT);
  19168. auto result = httplib::stream::Get(cli, "/nonexistent");
  19169. EXPECT_TRUE(result.is_valid());
  19170. EXPECT_EQ(404, result.status());
  19171. }
  19172. // stream::Post tests
  19173. TEST_F(StreamApiTest, PostBasic) {
  19174. httplib::Client cli(HOST, PORT);
  19175. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  19176. "application/json");
  19177. ASSERT_TRUE(result.is_valid());
  19178. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  19179. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  19180. }
  19181. TEST_F(StreamApiTest, PostWithHeaders) {
  19182. httplib::Client cli(HOST, PORT);
  19183. httplib::Headers headers{{"X-Custom", "value"}};
  19184. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  19185. "text/plain");
  19186. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  19187. }
  19188. TEST_F(StreamApiTest, PostWithParams) {
  19189. httplib::Client cli(HOST, PORT);
  19190. httplib::Params params{{"k", "v"}};
  19191. auto result =
  19192. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  19193. auto body = read_body(result);
  19194. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  19195. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  19196. }
  19197. TEST_F(StreamApiTest, PostLarge) {
  19198. httplib::Client cli(HOST, PORT);
  19199. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  19200. size_t total = 0;
  19201. while (result.next()) {
  19202. total += result.size();
  19203. }
  19204. EXPECT_EQ(100u * 1024u, total);
  19205. }
  19206. // stream::Put/Patch tests
  19207. TEST_F(StreamApiTest, PutAndPatch) {
  19208. httplib::Client cli(HOST, PORT);
  19209. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  19210. EXPECT_EQ("PUT:test", read_body(put));
  19211. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  19212. EXPECT_EQ("PATCH:test", read_body(patch));
  19213. }
  19214. // stream::Delete tests
  19215. TEST_F(StreamApiTest, Delete) {
  19216. httplib::Client cli(HOST, PORT);
  19217. auto del1 = httplib::stream::Delete(cli, "/resource");
  19218. EXPECT_EQ("Deleted", read_body(del1));
  19219. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  19220. EXPECT_EQ("Deleted:data", read_body(del2));
  19221. }
  19222. // stream::Head/Options tests
  19223. TEST_F(StreamApiTest, HeadAndOptions) {
  19224. httplib::Client cli(HOST, PORT);
  19225. auto head = httplib::stream::Head(cli, "/head-test");
  19226. EXPECT_TRUE(head.is_valid());
  19227. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  19228. auto opts = httplib::stream::Options(cli, "/options");
  19229. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  19230. }
  19231. // SSL stream::* tests
  19232. #ifdef CPPHTTPLIB_SSL_ENABLED
  19233. class SSLStreamApiTest : public ::testing::Test {
  19234. protected:
  19235. void SetUp() override {
  19236. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19237. res.set_content("Hello SSL!", "text/plain");
  19238. });
  19239. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19240. res.set_content(req.body, "text/plain");
  19241. });
  19242. port_ = svr_.bind_to_any_port("127.0.0.1");
  19243. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19244. svr_.wait_until_ready();
  19245. }
  19246. void TearDown() override {
  19247. svr_.stop();
  19248. if (thread_.joinable()) thread_.join();
  19249. }
  19250. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  19251. std::thread thread_;
  19252. int port_ = 0;
  19253. };
  19254. TEST_F(SSLStreamApiTest, GetAndPost) {
  19255. httplib::SSLClient cli("127.0.0.1", port_);
  19256. cli.enable_server_certificate_verification(false);
  19257. auto get = httplib::stream::Get(cli, "/hello");
  19258. EXPECT_EQ("Hello SSL!", read_body(get));
  19259. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  19260. EXPECT_EQ("test", read_body(post));
  19261. }
  19262. #endif
  19263. // Tests for Error::Timeout and Error::ConnectionClosed error types
  19264. // These errors are set in SocketStream/SSLSocketStream and propagated through
  19265. // BodyReader
  19266. TEST(ErrorHandlingTest, StreamReadTimeout) {
  19267. // Test that read timeout during streaming is detected
  19268. // Use a large content-length response where server delays mid-stream
  19269. Server svr;
  19270. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19271. // Send a large response with delay in the middle
  19272. res.set_content_provider(
  19273. 1000, // content_length
  19274. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  19275. if (offset < 100) {
  19276. // Send first 100 bytes immediately
  19277. std::string data(100, 'A');
  19278. sink.write(data.c_str(), data.size());
  19279. return true;
  19280. }
  19281. // Then delay longer than client timeout
  19282. std::this_thread::sleep_for(std::chrono::seconds(3));
  19283. std::string data(900, 'B');
  19284. sink.write(data.c_str(), data.size());
  19285. return true;
  19286. });
  19287. });
  19288. auto port = 8091;
  19289. std::thread t([&]() { svr.listen("localhost", port); });
  19290. svr.wait_until_ready();
  19291. Client cli("localhost", port);
  19292. cli.set_read_timeout(1, 0); // 1 second timeout
  19293. auto handle = cli.open_stream("GET", "/slow-stream");
  19294. ASSERT_TRUE(handle.is_valid());
  19295. char buf[256];
  19296. ssize_t total = 0;
  19297. ssize_t n;
  19298. bool got_error = false;
  19299. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19300. total += n;
  19301. }
  19302. if (n < 0) {
  19303. got_error = true;
  19304. // Should be timeout or read error
  19305. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19306. handle.get_read_error() == Error::Read)
  19307. << "Actual error: " << to_string(handle.get_read_error());
  19308. }
  19309. // Either we got an error, or we got less data than expected
  19310. EXPECT_TRUE(got_error || total < 1000)
  19311. << "Expected timeout but got all " << total << " bytes";
  19312. svr.stop();
  19313. t.join();
  19314. }
  19315. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  19316. // Test connection closed detection via BodyReader
  19317. Server svr;
  19318. std::atomic<bool> close_now{false};
  19319. svr.Get("/will-close", [&](const Request &, Response &res) {
  19320. res.set_content_provider(
  19321. 10000, // Large content_length that we won't fully send
  19322. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19323. if (offset < 100) {
  19324. std::string data(100, 'X');
  19325. sink.write(data.c_str(), data.size());
  19326. return true;
  19327. }
  19328. // Wait for signal then abort
  19329. while (!close_now) {
  19330. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19331. }
  19332. return false; // Abort - server will close connection
  19333. });
  19334. });
  19335. auto port = 8092;
  19336. std::thread t([&]() { svr.listen("localhost", port); });
  19337. svr.wait_until_ready();
  19338. Client cli("localhost", port);
  19339. auto handle = cli.open_stream("GET", "/will-close");
  19340. ASSERT_TRUE(handle.is_valid());
  19341. char buf[256];
  19342. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19343. EXPECT_GT(n, 0) << "First read should succeed";
  19344. // Signal server to close
  19345. close_now = true;
  19346. // Keep reading until error or EOF
  19347. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19348. // Keep reading
  19349. }
  19350. // Should get an error since content_length wasn't satisfied
  19351. if (n < 0) {
  19352. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19353. handle.get_read_error() == Error::Read)
  19354. << "Actual error: " << to_string(handle.get_read_error());
  19355. }
  19356. svr.stop();
  19357. t.join();
  19358. }
  19359. #ifdef CPPHTTPLIB_SSL_ENABLED
  19360. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  19361. // Test that read timeout during SSL streaming is detected
  19362. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19363. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19364. res.set_content_provider(
  19365. 1000, "text/plain",
  19366. [](size_t offset, size_t /*length*/, DataSink &sink) {
  19367. if (offset < 100) {
  19368. std::string data(100, 'A');
  19369. sink.write(data.c_str(), data.size());
  19370. return true;
  19371. }
  19372. std::this_thread::sleep_for(std::chrono::seconds(3));
  19373. std::string data(900, 'B');
  19374. sink.write(data.c_str(), data.size());
  19375. return true;
  19376. });
  19377. });
  19378. auto port = 8093;
  19379. std::thread t([&]() { svr.listen("localhost", port); });
  19380. svr.wait_until_ready();
  19381. SSLClient cli("localhost", port);
  19382. cli.enable_server_certificate_verification(false);
  19383. cli.set_read_timeout(1, 0); // 1 second timeout
  19384. auto handle = cli.open_stream("GET", "/slow-stream");
  19385. ASSERT_TRUE(handle.is_valid());
  19386. char buf[256];
  19387. ssize_t total = 0;
  19388. ssize_t n;
  19389. bool got_error = false;
  19390. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19391. total += n;
  19392. }
  19393. if (n < 0) {
  19394. got_error = true;
  19395. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19396. handle.get_read_error() == Error::Read)
  19397. << "Actual error: " << to_string(handle.get_read_error());
  19398. }
  19399. EXPECT_TRUE(got_error || total < 1000)
  19400. << "Expected timeout but got all " << total << " bytes";
  19401. svr.stop();
  19402. t.join();
  19403. }
  19404. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  19405. // Test SSL connection closed detection
  19406. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19407. std::atomic<bool> close_now{false};
  19408. svr.Get("/will-close", [&](const Request &, Response &res) {
  19409. res.set_content_provider(
  19410. 10000, "text/plain",
  19411. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19412. if (offset < 100) {
  19413. std::string data(100, 'X');
  19414. sink.write(data.c_str(), data.size());
  19415. return true;
  19416. }
  19417. while (!close_now) {
  19418. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19419. }
  19420. return false;
  19421. });
  19422. });
  19423. auto port = 8094;
  19424. std::thread t([&]() { svr.listen("localhost", port); });
  19425. svr.wait_until_ready();
  19426. SSLClient cli("localhost", port);
  19427. cli.enable_server_certificate_verification(false);
  19428. auto handle = cli.open_stream("GET", "/will-close");
  19429. ASSERT_TRUE(handle.is_valid());
  19430. char buf[256];
  19431. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19432. EXPECT_GT(n, 0);
  19433. // Signal server to close
  19434. close_now = true;
  19435. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19436. // Keep reading
  19437. }
  19438. if (n < 0) {
  19439. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19440. handle.get_read_error() == Error::Read)
  19441. << "Actual error: " << to_string(handle.get_read_error());
  19442. }
  19443. svr.stop();
  19444. t.join();
  19445. }
  19446. #endif
  19447. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19448. using namespace httplib;
  19449. // Create a test file
  19450. const char *fname = "etag_testfile.txt";
  19451. const char *content = "etag-content";
  19452. {
  19453. std::ofstream ofs(fname);
  19454. ofs << content;
  19455. ASSERT_TRUE(ofs.good());
  19456. }
  19457. Server svr;
  19458. svr.set_mount_point("/static", ".");
  19459. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19460. svr.wait_until_ready();
  19461. Client cli(HOST, PORT);
  19462. // First request: should get 200 with ETag header
  19463. auto res1 = cli.Get("/static/etag_testfile.txt");
  19464. ASSERT_TRUE(res1);
  19465. ASSERT_EQ(200, res1->status);
  19466. ASSERT_TRUE(res1->has_header("ETag"));
  19467. std::string etag = res1->get_header_value("ETag");
  19468. EXPECT_FALSE(etag.empty());
  19469. // Verify ETag format: W/"hex-hex"
  19470. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19471. EXPECT_EQ('W', etag[0]);
  19472. EXPECT_EQ('/', etag[1]);
  19473. EXPECT_EQ('"', etag[2]);
  19474. EXPECT_EQ('"', etag.back());
  19475. // Exact match: expect 304 Not Modified
  19476. Headers h2 = {{"If-None-Match", etag}};
  19477. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19478. ASSERT_TRUE(res2);
  19479. EXPECT_EQ(304, res2->status);
  19480. // Wildcard match: expect 304 Not Modified
  19481. Headers h3 = {{"If-None-Match", "*"}};
  19482. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19483. ASSERT_TRUE(res3);
  19484. EXPECT_EQ(304, res3->status);
  19485. // Non-matching ETag: expect 200
  19486. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19487. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19488. ASSERT_TRUE(res4);
  19489. EXPECT_EQ(200, res4->status);
  19490. // Multiple ETags with one matching: expect 304
  19491. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19492. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19493. ASSERT_TRUE(res5);
  19494. EXPECT_EQ(304, res5->status);
  19495. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19496. // that equivalent to the single comma-separated list above, so the match on
  19497. // the second line must still be found.
  19498. Headers h6;
  19499. h6.emplace("If-None-Match", "W/\"other\"");
  19500. h6.emplace("If-None-Match", etag);
  19501. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19502. ASSERT_TRUE(res6);
  19503. EXPECT_EQ(304, res6->status);
  19504. svr.stop();
  19505. t.join();
  19506. std::remove(fname);
  19507. }
  19508. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19509. using namespace httplib;
  19510. Server svr;
  19511. svr.set_mount_point("/static", ".");
  19512. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19513. svr.wait_until_ready();
  19514. Client cli(HOST, PORT);
  19515. // Send If-None-Match: * to a non-existent file
  19516. Headers h = {{"If-None-Match", "*"}};
  19517. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19519. EXPECT_EQ(404, res->status);
  19520. svr.stop();
  19521. t.join();
  19522. }
  19523. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  19524. using namespace httplib;
  19525. // Create a test file
  19526. const char *fname = "etag_boundary_testfile.txt";
  19527. const char *content = "boundary-test";
  19528. {
  19529. std::ofstream ofs(fname);
  19530. ofs << content;
  19531. ASSERT_TRUE(ofs.good());
  19532. }
  19533. Server svr;
  19534. svr.set_mount_point("/static", ".");
  19535. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19536. svr.wait_until_ready();
  19537. Client cli(HOST, PORT);
  19538. // Get the actual ETag
  19539. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  19540. ASSERT_TRUE(res1);
  19541. ASSERT_EQ(200, res1->status);
  19542. ASSERT_TRUE(res1->has_header("ETag"));
  19543. std::string etag = res1->get_header_value("ETag");
  19544. // Test 1: Very long ETag value (longer than actual ETag)
  19545. // Should NOT match and return 200 (not trigger out-of-bounds read)
  19546. Headers h1 = {{"If-None-Match", "W/"
  19547. "\"very-long-etag-value-that-is-much-longer-"
  19548. "than-the-actual-etag-value\""}};
  19549. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  19550. ASSERT_TRUE(res2);
  19551. EXPECT_EQ(200, res2->status); // Should not match
  19552. // Test 2: Long string followed by wildcard
  19553. // Should match on "*" and return 304 (without out-of-bounds read on the long
  19554. // string)
  19555. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19556. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19557. ASSERT_TRUE(res3);
  19558. EXPECT_EQ(304, res3->status); // Should match on "*"
  19559. // Test 3: Wildcard followed by long string
  19560. // Should match on "*" immediately and return 304
  19561. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  19562. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  19563. ASSERT_TRUE(res4);
  19564. EXPECT_EQ(304, res4->status); // Should match on "*"
  19565. // Test 4: Multiple long non-matching values
  19566. // Should NOT match and return 200 (test that all comparisons are safe)
  19567. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  19568. "W/\"second-long-non-matching-value\", "
  19569. "W/\"third-long-non-matching-value\""}};
  19570. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  19571. ASSERT_TRUE(res5);
  19572. EXPECT_EQ(200, res5->status); // Should not match
  19573. // Test 5: Single character that is not "*" (edge case)
  19574. Headers h5 = {{"If-None-Match", "X"}};
  19575. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  19576. ASSERT_TRUE(res6);
  19577. EXPECT_EQ(200, res6->status); // Should not match
  19578. svr.stop();
  19579. t.join();
  19580. std::remove(fname);
  19581. }
  19582. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  19583. using namespace httplib;
  19584. // Create a test file
  19585. const char *fname = "ims_testfile.txt";
  19586. const char *content = "if-modified-since-test";
  19587. {
  19588. std::ofstream ofs(fname);
  19589. ofs << content;
  19590. ASSERT_TRUE(ofs.good());
  19591. }
  19592. Server svr;
  19593. svr.set_mount_point("/static", ".");
  19594. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19595. svr.wait_until_ready();
  19596. Client cli(HOST, PORT);
  19597. // First request: should get 200 with Last-Modified header
  19598. auto res1 = cli.Get("/static/ims_testfile.txt");
  19599. ASSERT_TRUE(res1);
  19600. ASSERT_EQ(200, res1->status);
  19601. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19602. std::string last_modified = res1->get_header_value("Last-Modified");
  19603. EXPECT_FALSE(last_modified.empty());
  19604. // If-Modified-Since with same time: expect 304
  19605. Headers h2 = {{"If-Modified-Since", last_modified}};
  19606. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  19607. ASSERT_TRUE(res2);
  19608. EXPECT_EQ(304, res2->status);
  19609. // If-Modified-Since with future time: expect 304
  19610. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19611. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  19612. ASSERT_TRUE(res3);
  19613. EXPECT_EQ(304, res3->status);
  19614. // If-Modified-Since with past time: expect 200
  19615. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19616. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  19617. ASSERT_TRUE(res4);
  19618. EXPECT_EQ(200, res4->status);
  19619. // If-None-Match takes precedence over If-Modified-Since
  19620. // (send matching ETag with old If-Modified-Since -> should still be 304)
  19621. ASSERT_TRUE(res1->has_header("ETag"));
  19622. std::string etag = res1->get_header_value("ETag");
  19623. Headers h5 = {{"If-None-Match", etag},
  19624. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19625. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  19626. ASSERT_TRUE(res5);
  19627. EXPECT_EQ(304, res5->status);
  19628. svr.stop();
  19629. t.join();
  19630. std::remove(fname);
  19631. }
  19632. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  19633. using namespace httplib;
  19634. Server svr;
  19635. // Endpoint that returns compressible content
  19636. svr.Get("/compressible", [](const Request &, Response &res) {
  19637. // Return a large enough body to trigger compression
  19638. std::string body(1000, 'a');
  19639. res.set_content(body, "text/plain");
  19640. });
  19641. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19642. svr.wait_until_ready();
  19643. Client cli(HOST, PORT);
  19644. // Request with gzip support: should get Vary header when compressed
  19645. cli.set_compress(true);
  19646. auto res1 = cli.Get("/compressible");
  19647. ASSERT_TRUE(res1);
  19648. EXPECT_EQ(200, res1->status);
  19649. // If Content-Encoding is set, Vary should also be set
  19650. if (res1->has_header("Content-Encoding")) {
  19651. EXPECT_TRUE(res1->has_header("Vary"));
  19652. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  19653. }
  19654. // Request without Accept-Encoding header: should not have compression
  19655. Headers h_no_compress;
  19656. auto res2 = cli.Get("/compressible", h_no_compress);
  19657. ASSERT_TRUE(res2);
  19658. EXPECT_EQ(200, res2->status);
  19659. // Verify Vary header is present when compression is applied
  19660. // (the exact behavior depends on server configuration)
  19661. svr.stop();
  19662. t.join();
  19663. }
  19664. TEST(ETagTest, IfRangeWithETag) {
  19665. using namespace httplib;
  19666. // Create a test file with known content
  19667. const char *fname = "if_range_testfile.txt";
  19668. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  19669. {
  19670. std::ofstream ofs(fname);
  19671. ofs << content;
  19672. ASSERT_TRUE(ofs.good());
  19673. }
  19674. Server svr;
  19675. svr.set_mount_point("/static", ".");
  19676. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19677. svr.wait_until_ready();
  19678. Client cli(HOST, PORT);
  19679. // First request: get ETag
  19680. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19681. ASSERT_TRUE(res1);
  19682. ASSERT_EQ(200, res1->status);
  19683. ASSERT_TRUE(res1->has_header("ETag"));
  19684. std::string etag = res1->get_header_value("ETag");
  19685. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  19686. // Since our server generates weak ETags (W/"..."), If-Range with our
  19687. // ETag should NOT result in partial content - it should return full content.
  19688. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  19689. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  19690. ASSERT_TRUE(res2);
  19691. // Weak ETag in If-Range -> full content (200), not partial (206)
  19692. EXPECT_EQ(200, res2->status);
  19693. EXPECT_EQ(content, res2->body);
  19694. EXPECT_FALSE(res2->has_header("Content-Range"));
  19695. // Range request with non-matching If-Range (ETag): should get 200 (full
  19696. // content)
  19697. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  19698. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  19699. ASSERT_TRUE(res3);
  19700. EXPECT_EQ(200, res3->status);
  19701. EXPECT_EQ(content, res3->body);
  19702. EXPECT_FALSE(res3->has_header("Content-Range"));
  19703. // Range request with strong ETag (hypothetical - our server doesn't generate
  19704. // strong ETags, but if client sends a strong ETag that doesn't match, it
  19705. // should return full content)
  19706. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19707. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19708. ASSERT_TRUE(res4);
  19709. EXPECT_EQ(200, res4->status);
  19710. EXPECT_EQ(content, res4->body);
  19711. EXPECT_FALSE(res4->has_header("Content-Range"));
  19712. svr.stop();
  19713. t.join();
  19714. std::remove(fname);
  19715. }
  19716. TEST(ETagTest, IfRangeWithDate) {
  19717. using namespace httplib;
  19718. // Create a test file
  19719. const char *fname = "if_range_date_testfile.txt";
  19720. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  19721. {
  19722. std::ofstream ofs(fname);
  19723. ofs << content;
  19724. ASSERT_TRUE(ofs.good());
  19725. }
  19726. Server svr;
  19727. svr.set_mount_point("/static", ".");
  19728. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19729. svr.wait_until_ready();
  19730. Client cli(HOST, PORT);
  19731. // First request: get Last-Modified
  19732. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  19733. ASSERT_TRUE(res1);
  19734. ASSERT_EQ(200, res1->status);
  19735. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19736. std::string last_modified = res1->get_header_value("Last-Modified");
  19737. // Range request with matching If-Range (date): should get 206
  19738. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19739. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19740. ASSERT_TRUE(res2);
  19741. EXPECT_EQ(206, res2->status);
  19742. EXPECT_EQ("FGHIJ", res2->body);
  19743. // Range request with old If-Range date: should get 200 (full content)
  19744. Headers h3 = {{"Range", "bytes=5-9"},
  19745. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19746. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19747. ASSERT_TRUE(res3);
  19748. EXPECT_EQ(200, res3->status);
  19749. EXPECT_EQ(content, res3->body);
  19750. // Range request with future If-Range date: should get 206
  19751. Headers h4 = {{"Range", "bytes=0-4"},
  19752. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19753. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19754. ASSERT_TRUE(res4);
  19755. EXPECT_EQ(206, res4->status);
  19756. EXPECT_EQ("ABCDE", res4->body);
  19757. svr.stop();
  19758. t.join();
  19759. std::remove(fname);
  19760. }
  19761. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19762. using namespace httplib;
  19763. const char *fname = "etag_malformed.txt";
  19764. const char *content = "malformed-etag";
  19765. {
  19766. std::ofstream ofs(fname);
  19767. ofs << content;
  19768. ASSERT_TRUE(ofs.good());
  19769. }
  19770. Server svr;
  19771. svr.set_mount_point("/static", ".");
  19772. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19773. svr.wait_until_ready();
  19774. Client cli(HOST, PORT);
  19775. // baseline: should get 200 and an ETag
  19776. auto res1 = cli.Get("/static/etag_malformed.txt");
  19777. ASSERT_TRUE(res1);
  19778. ASSERT_EQ(200, res1->status);
  19779. ASSERT_TRUE(res1->has_header("ETag"));
  19780. // Malformed ETag value (missing quotes) should be treated as non-matching
  19781. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19782. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19783. ASSERT_TRUE(res_bad);
  19784. EXPECT_EQ(200, res_bad->status);
  19785. // Whitespace-only header value should be considered invalid / non-matching
  19786. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19787. "Host: localhost\r\n"
  19788. "If-None-Match: \r\n"
  19789. "Connection: close\r\n"
  19790. "\r\n";
  19791. std::string out;
  19792. ASSERT_TRUE(send_request(5, raw_req, &out));
  19793. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19794. svr.stop();
  19795. t.join();
  19796. std::remove(fname);
  19797. }
  19798. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19799. using namespace httplib;
  19800. const char *fname = "ims_invalid_format.txt";
  19801. const char *content = "ims-bad-format";
  19802. {
  19803. std::ofstream ofs(fname);
  19804. ofs << content;
  19805. ASSERT_TRUE(ofs.good());
  19806. }
  19807. Server svr;
  19808. svr.set_mount_point("/static", ".");
  19809. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19810. svr.wait_until_ready();
  19811. Client cli(HOST, PORT);
  19812. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19813. ASSERT_TRUE(res1);
  19814. ASSERT_EQ(200, res1->status);
  19815. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19816. // If-Modified-Since with invalid format should not result in 304
  19817. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19818. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19819. ASSERT_TRUE(res_bad);
  19820. EXPECT_EQ(200, res_bad->status);
  19821. // If-Range with invalid date format should be treated as mismatch -> full
  19822. // content (200)
  19823. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19824. {"If-Range", "invalid-date"}};
  19825. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19826. ASSERT_TRUE(res_ifrange);
  19827. EXPECT_EQ(200, res_ifrange->status);
  19828. svr.stop();
  19829. t.join();
  19830. std::remove(fname);
  19831. }
  19832. TEST(ETagTest, IfRangeWithMalformedETag) {
  19833. using namespace httplib;
  19834. const char *fname = "ifrange_malformed.txt";
  19835. const std::string content = "0123456789";
  19836. {
  19837. std::ofstream ofs(fname);
  19838. ofs << content;
  19839. ASSERT_TRUE(ofs.good());
  19840. }
  19841. Server svr;
  19842. svr.set_mount_point("/static", ".");
  19843. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19844. svr.wait_until_ready();
  19845. Client cli(HOST, PORT);
  19846. // First request: get ETag
  19847. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19848. ASSERT_TRUE(res1);
  19849. ASSERT_EQ(200, res1->status);
  19850. ASSERT_TRUE(res1->has_header("ETag"));
  19851. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19852. // full content (200)
  19853. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19854. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19855. ASSERT_TRUE(res2);
  19856. EXPECT_EQ(200, res2->status);
  19857. EXPECT_EQ(content, res2->body);
  19858. svr.stop();
  19859. t.join();
  19860. std::remove(fname);
  19861. }
  19862. TEST(ETagTest, ExtremeLargeDateValues) {
  19863. using namespace httplib;
  19864. const char *fname = "ims_extreme_date.txt";
  19865. const char *content = "ims-extreme-date";
  19866. {
  19867. std::ofstream ofs(fname);
  19868. ofs << content;
  19869. ASSERT_TRUE(ofs.good());
  19870. }
  19871. Server svr;
  19872. svr.set_mount_point("/static", ".");
  19873. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19874. svr.wait_until_ready();
  19875. Client cli(HOST, PORT);
  19876. auto res1 = cli.Get(std::string("/static/") + fname);
  19877. ASSERT_TRUE(res1);
  19878. ASSERT_EQ(200, res1->status);
  19879. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19880. // Extremely large year that may overflow date parsing routines.
  19881. Headers h_large_date = {
  19882. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19883. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19884. ASSERT_TRUE(res_bad);
  19885. // Expect server to treat this as invalid/mismatch and return full content
  19886. EXPECT_EQ(200, res_bad->status);
  19887. // If-Range with extremely large date should be treated as mismatch -> full
  19888. // content (200)
  19889. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19890. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19891. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19892. ASSERT_TRUE(res_ifrange);
  19893. EXPECT_EQ(200, res_ifrange->status);
  19894. svr.stop();
  19895. t.join();
  19896. std::remove(fname);
  19897. }
  19898. TEST(ETagTest, NegativeFileModificationTime) {
  19899. using namespace httplib;
  19900. const char *fname = "ims_negative_mtime.txt";
  19901. const std::string content = "negative-mtime";
  19902. {
  19903. std::ofstream ofs(fname);
  19904. ofs << content;
  19905. ASSERT_TRUE(ofs.good());
  19906. }
  19907. // Try to set file mtime to a negative value. This may fail on some
  19908. // platforms/filesystems; if it fails, the test will still verify server
  19909. // behaves safely by performing a regular conditional request.
  19910. #if defined(__APPLE__) || defined(__linux__)
  19911. bool set_negative = false;
  19912. do {
  19913. struct timeval times[2];
  19914. // access time: now
  19915. times[0].tv_sec = time(nullptr);
  19916. times[0].tv_usec = 0;
  19917. // modification time: negative (e.g., -1)
  19918. times[1].tv_sec = -1;
  19919. times[1].tv_usec = 0;
  19920. if (utimes(fname, times) == 0) { set_negative = true; }
  19921. } while (0);
  19922. #else
  19923. bool set_negative = false;
  19924. #endif
  19925. Server svr;
  19926. svr.set_mount_point("/static", ".");
  19927. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19928. svr.wait_until_ready();
  19929. Client cli(HOST, PORT);
  19930. auto res1 = cli.Get(std::string("/static/") + fname);
  19931. ASSERT_TRUE(res1);
  19932. ASSERT_EQ(200, res1->status);
  19933. bool has_last_modified = res1->has_header("Last-Modified");
  19934. std::string last_modified;
  19935. if (has_last_modified) {
  19936. last_modified = res1->get_header_value("Last-Modified");
  19937. }
  19938. if (set_negative) {
  19939. // If we successfully set a negative mtime, ensure server returns a
  19940. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  19941. // with an old date and ensure server handles it without crash.
  19942. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  19943. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  19944. ASSERT_TRUE(res2);
  19945. // Behavior may vary; at minimum ensure server responds (200 or 304).
  19946. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  19947. } else {
  19948. // Could not set negative mtime on this platform; fall back to verifying
  19949. // that normal invalid/malformed dates are treated safely (non-304).
  19950. Headers h_bad_date = {
  19951. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19952. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  19953. ASSERT_TRUE(res_bad);
  19954. EXPECT_EQ(200, res_bad->status);
  19955. }
  19956. svr.stop();
  19957. t.join();
  19958. std::remove(fname);
  19959. }
  19960. //==============================================================================
  19961. // Integration Tests with Server
  19962. //==============================================================================
  19963. class SSEIntegrationTest : public ::testing::Test {
  19964. protected:
  19965. void SetUp() override {
  19966. stop_server_.store(false);
  19967. events_.clear();
  19968. server_ = httplib::detail::make_unique<Server>();
  19969. setup_server();
  19970. start_server();
  19971. }
  19972. void TearDown() override {
  19973. stop_server_.store(true);
  19974. event_cv_.notify_all();
  19975. server_->stop();
  19976. if (server_thread_.joinable()) { server_thread_.join(); }
  19977. }
  19978. void setup_server() {
  19979. // Simple SSE endpoint
  19980. server_->Get("/events", [this](const Request &req, Response &res) {
  19981. auto last_id = req.get_header_value("Last-Event-ID");
  19982. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  19983. res.set_chunked_content_provider(
  19984. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  19985. std::unique_lock<std::mutex> lock(event_mutex_);
  19986. if (event_cv_.wait_for(
  19987. lock, std::chrono::milliseconds(200), [this] {
  19988. return !events_.empty() || stop_server_.load();
  19989. })) {
  19990. if (stop_server_.load()) { return false; }
  19991. if (!events_.empty()) {
  19992. std::string event = events_.front();
  19993. events_.erase(events_.begin());
  19994. sink.write(event.data(), event.size());
  19995. return true;
  19996. }
  19997. }
  19998. return !stop_server_.load();
  19999. });
  20000. });
  20001. // Endpoint that returns error
  20002. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  20003. res.status = 500;
  20004. res.set_content("Internal Server Error", "text/plain");
  20005. });
  20006. // Endpoint for custom event types
  20007. server_->Get("/custom-events", [](const Request &, Response &res) {
  20008. res.set_chunked_content_provider(
  20009. "text/event-stream", [](size_t offset, DataSink &sink) {
  20010. if (offset == 0) {
  20011. std::string event = "event: update\ndata: updated\n\n"
  20012. "event: delete\ndata: deleted\n\n";
  20013. sink.write(event.data(), event.size());
  20014. }
  20015. return false; // End stream after sending
  20016. });
  20017. });
  20018. }
  20019. void start_server() {
  20020. port_ = server_->bind_to_any_port(HOST);
  20021. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20022. // Wait for server to start
  20023. while (!server_->is_running()) {
  20024. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20025. }
  20026. }
  20027. int get_port() const { return port_; }
  20028. void send_event(const std::string &event) {
  20029. std::lock_guard<std::mutex> lock(event_mutex_);
  20030. events_.push_back(event);
  20031. event_cv_.notify_all();
  20032. }
  20033. std::unique_ptr<Server> server_;
  20034. std::thread server_thread_;
  20035. std::mutex event_mutex_;
  20036. std::condition_variable event_cv_;
  20037. std::vector<std::string> events_;
  20038. std::atomic<bool> stop_server_{false};
  20039. std::string last_received_event_id_;
  20040. int port_ = 0;
  20041. };
  20042. //==============================================================================
  20043. // SSE Parsing Tests
  20044. //==============================================================================
  20045. class SSEParsingTest : public SSEIntegrationTest {
  20046. protected:
  20047. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  20048. // A trailing sentinel event tells when the whole stream has been parsed.
  20049. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  20050. auto body = stream + "event: end\ndata: end\n\n";
  20051. server_->Get("/parse", [body](const Request &, Response &res) {
  20052. res.set_content(body, "text/event-stream");
  20053. });
  20054. return collect("/parse");
  20055. }
  20056. // Runs SSEClient against path until an "end" event arrives and returns the
  20057. // messages dispatched before it
  20058. std::vector<sse::SSEMessage> collect(const std::string &path) {
  20059. Client client(HOST, get_port());
  20060. sse::SSEClient sse(client, path);
  20061. std::mutex mutex;
  20062. std::condition_variable cv;
  20063. std::vector<sse::SSEMessage> messages;
  20064. auto done = false;
  20065. sse.on_message([&](const sse::SSEMessage &msg) {
  20066. std::lock_guard<std::mutex> lock(mutex);
  20067. // Ignore a replay from a reconnect that races with stop()
  20068. if (!done) { messages.push_back(msg); }
  20069. });
  20070. sse.on_event("end", [&](const sse::SSEMessage &) {
  20071. std::lock_guard<std::mutex> lock(mutex);
  20072. done = true;
  20073. cv.notify_all();
  20074. });
  20075. sse.set_reconnect_interval(100);
  20076. sse.start_async();
  20077. {
  20078. std::unique_lock<std::mutex> lock(mutex);
  20079. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  20080. }
  20081. sse.stop();
  20082. EXPECT_TRUE(done);
  20083. return messages;
  20084. }
  20085. };
  20086. TEST_F(SSEParsingTest, SingleLineData) {
  20087. auto msgs = parse("data: hello\n\n");
  20088. ASSERT_EQ(msgs.size(), 1u);
  20089. EXPECT_EQ(msgs[0].data, "hello");
  20090. EXPECT_EQ(msgs[0].event, "message");
  20091. }
  20092. TEST_F(SSEParsingTest, MultiLineData) {
  20093. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  20094. ASSERT_EQ(msgs.size(), 1u);
  20095. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  20096. }
  20097. TEST_F(SSEParsingTest, CustomEventType) {
  20098. auto msgs = parse("event: update\ndata: payload\n\n");
  20099. ASSERT_EQ(msgs.size(), 1u);
  20100. EXPECT_EQ(msgs[0].event, "update");
  20101. EXPECT_EQ(msgs[0].data, "payload");
  20102. }
  20103. TEST_F(SSEParsingTest, EventIdHandling) {
  20104. auto msgs = parse("id: 12345\ndata: test\n\n");
  20105. ASSERT_EQ(msgs.size(), 1u);
  20106. EXPECT_EQ(msgs[0].id, "12345");
  20107. }
  20108. TEST_F(SSEParsingTest, EmptyEventId) {
  20109. auto msgs = parse("id:\ndata: test\n\n");
  20110. ASSERT_EQ(msgs.size(), 1u);
  20111. EXPECT_EQ(msgs[0].id, "");
  20112. }
  20113. TEST_F(SSEParsingTest, CommentsIgnored) {
  20114. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  20115. ASSERT_EQ(msgs.size(), 1u);
  20116. EXPECT_EQ(msgs[0].data, "hello");
  20117. EXPECT_EQ(msgs[0].event, "message");
  20118. }
  20119. TEST_F(SSEParsingTest, ColonInValue) {
  20120. auto msgs = parse("data: hello:world:test\n\n");
  20121. ASSERT_EQ(msgs.size(), 1u);
  20122. EXPECT_EQ(msgs[0].data, "hello:world:test");
  20123. }
  20124. TEST_F(SSEParsingTest, FieldNameOnly) {
  20125. // A line without a colon is a field name with an empty value
  20126. auto msgs = parse("data\n\n");
  20127. ASSERT_EQ(msgs.size(), 1u);
  20128. EXPECT_EQ(msgs[0].data, "");
  20129. }
  20130. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  20131. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  20132. ASSERT_EQ(msgs.size(), 1u);
  20133. EXPECT_EQ(msgs[0].event, "update");
  20134. EXPECT_EQ(msgs[0].data, "hello");
  20135. }
  20136. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  20137. auto msgs = parse("data\r\n\r\n");
  20138. ASSERT_EQ(msgs.size(), 1u);
  20139. EXPECT_EQ(msgs[0].data, "");
  20140. }
  20141. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  20142. auto msgs = parse("event: update\rdata: hello\r\r");
  20143. ASSERT_EQ(msgs.size(), 1u);
  20144. EXPECT_EQ(msgs[0].event, "update");
  20145. EXPECT_EQ(msgs[0].data, "hello");
  20146. }
  20147. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  20148. // Chunk boundaries fall inside every \r\n and right before the first one
  20149. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  20150. "\n\r", "\nevent: end\ndata: end\n\n"};
  20151. server_->Get("/split", [chunks](const Request &, Response &res) {
  20152. auto i = std::make_shared<size_t>(0);
  20153. res.set_chunked_content_provider(
  20154. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  20155. if (*i == chunks.size()) {
  20156. sink.done();
  20157. } else {
  20158. sink.write(chunks[*i].data(), chunks[*i].size());
  20159. (*i)++;
  20160. }
  20161. return true;
  20162. });
  20163. });
  20164. auto msgs = collect("/split");
  20165. ASSERT_EQ(msgs.size(), 1u);
  20166. EXPECT_EQ(msgs[0].event, "update");
  20167. EXPECT_EQ(msgs[0].data, "hello");
  20168. }
  20169. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  20170. // Only a BOM at the start of the stream is ignored
  20171. auto msgs = parse("\xEF\xBB\xBF"
  20172. "data: first\n\n"
  20173. "\xEF\xBB\xBF"
  20174. "data: second\n\n");
  20175. ASSERT_EQ(msgs.size(), 1u);
  20176. EXPECT_EQ(msgs[0].data, "first");
  20177. }
  20178. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  20179. auto msgs = parse("unknown: value\ndata: hello\n\n");
  20180. ASSERT_EQ(msgs.size(), 1u);
  20181. EXPECT_EQ(msgs[0].data, "hello");
  20182. EXPECT_EQ(msgs[0].event, "message");
  20183. }
  20184. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  20185. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  20186. ASSERT_EQ(msgs.size(), 2u);
  20187. EXPECT_EQ(msgs[0].data, "hello");
  20188. EXPECT_EQ(msgs[1].data, "hello");
  20189. }
  20190. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  20191. // An event without data is not dispatched, and its type must not leak
  20192. // into the next event
  20193. auto msgs = parse("event: update\n\ndata: hello\n\n");
  20194. ASSERT_EQ(msgs.size(), 1u);
  20195. EXPECT_EQ(msgs[0].event, "message");
  20196. EXPECT_EQ(msgs[0].data, "hello");
  20197. }
  20198. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  20199. // The first connection sends only an id; the second echoes back the
  20200. // Last-Event-ID it was reconnected with
  20201. std::atomic<int> connection_count{0};
  20202. server_->Get("/id-only", [&](const Request &req, Response &res) {
  20203. if (connection_count++ == 0) {
  20204. res.set_content("id: 42\n\n", "text/event-stream");
  20205. } else {
  20206. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20207. "\n\nevent: end\ndata: end\n\n",
  20208. "text/event-stream");
  20209. }
  20210. });
  20211. auto msgs = collect("/id-only");
  20212. ASSERT_EQ(msgs.size(), 1u);
  20213. EXPECT_EQ(msgs[0].data, "42");
  20214. }
  20215. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  20216. // The first connection sets an id and then clears it with an empty one; the
  20217. // second reports whether it was reconnected with a Last-Event-ID
  20218. std::atomic<int> connection_count{0};
  20219. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  20220. if (connection_count++ == 0) {
  20221. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  20222. "text/event-stream");
  20223. } else {
  20224. res.set_content(
  20225. std::string("data: ") +
  20226. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  20227. "\n\nevent: end\ndata: end\n\n",
  20228. "text/event-stream");
  20229. }
  20230. });
  20231. auto msgs = collect("/id-clear");
  20232. ASSERT_EQ(msgs.size(), 3u);
  20233. EXPECT_EQ(msgs[0].id, "1");
  20234. EXPECT_EQ(msgs[1].id, "");
  20235. EXPECT_EQ(msgs[2].data, "not sent");
  20236. }
  20237. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  20238. // The first connection sets an id and then sends ids that cannot be carried
  20239. // in a header; the second echoes back the Last-Event-ID it was reconnected
  20240. // with
  20241. std::atomic<int> connection_count{0};
  20242. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  20243. if (connection_count++ == 0) {
  20244. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  20245. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  20246. "text/event-stream");
  20247. } else {
  20248. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20249. "\n\nevent: end\ndata: end\n\n",
  20250. "text/event-stream");
  20251. }
  20252. });
  20253. auto msgs = collect("/id-unsendable");
  20254. ASSERT_EQ(msgs.size(), 1u);
  20255. EXPECT_EQ(msgs[0].data, "42");
  20256. }
  20257. TEST_F(SSEParsingTest, CompleteEventParsing) {
  20258. auto msgs = parse("event: notification\nid: evt-42\n"
  20259. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  20260. ASSERT_EQ(msgs.size(), 1u);
  20261. EXPECT_EQ(msgs[0].event, "notification");
  20262. EXPECT_EQ(msgs[0].id, "evt-42");
  20263. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  20264. }
  20265. TEST(SSEMessageTest, Clear) {
  20266. sse::SSEMessage msg;
  20267. msg.event = "custom";
  20268. msg.data = "some data";
  20269. msg.id = "123";
  20270. msg.clear();
  20271. EXPECT_EQ(msg.event, "message");
  20272. EXPECT_EQ(msg.data, "");
  20273. EXPECT_EQ(msg.id, "");
  20274. }
  20275. //==============================================================================
  20276. // SSE Integration Tests
  20277. //==============================================================================
  20278. // Test: Successful connection and on_open callback
  20279. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  20280. // Add a simple endpoint that sends one event and closes
  20281. server_->Get("/simple-event", [](const Request &, Response &res) {
  20282. res.set_chunked_content_provider(
  20283. "text/event-stream", [](size_t offset, DataSink &sink) {
  20284. if (offset == 0) {
  20285. std::string event = "data: hello\n\n";
  20286. sink.write(event.data(), event.size());
  20287. }
  20288. return false; // Close stream after sending
  20289. });
  20290. });
  20291. Client client("localhost", get_port());
  20292. sse::SSEClient sse(client, "/simple-event");
  20293. std::atomic<bool> open_called{false};
  20294. std::atomic<bool> message_received{false};
  20295. sse.on_open([&open_called]() { open_called.store(true); });
  20296. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  20297. if (msg.data == "hello") { message_received.store(true); }
  20298. });
  20299. sse.set_reconnect_interval(100);
  20300. sse.set_max_reconnect_attempts(1);
  20301. // Start async
  20302. sse.start_async();
  20303. // Wait for message to be processed
  20304. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20305. sse.stop();
  20306. EXPECT_TRUE(open_called.load());
  20307. EXPECT_TRUE(message_received.load());
  20308. }
  20309. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  20310. // A data line that never ends.
  20311. server_->Get("/endless-line", [](const Request &, Response &res) {
  20312. res.set_chunked_content_provider(
  20313. "text/event-stream", [](size_t offset, DataSink &sink) {
  20314. if (offset == 0) { sink.write("data: ", 6); }
  20315. std::string chunk(64 * 1024, 'A');
  20316. return sink.write(chunk.data(), chunk.size());
  20317. });
  20318. });
  20319. Client client("localhost", get_port());
  20320. // A stream that may run forever, so that only the event is bounded.
  20321. client.set_payload_max_length(0);
  20322. sse::SSEClient sse(client, "/endless-line");
  20323. std::atomic<bool> too_long{false};
  20324. sse.on_error([&](Error err) {
  20325. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  20326. });
  20327. sse.set_max_reconnect_attempts(1);
  20328. sse.start_async();
  20329. for (int i = 0; i < 500 && !too_long; i++) {
  20330. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20331. }
  20332. sse.stop();
  20333. EXPECT_TRUE(too_long);
  20334. }
  20335. // Test: on_message callback
  20336. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  20337. // Endpoint that sends multiple events then closes
  20338. server_->Get("/multi-event", [](const Request &, Response &res) {
  20339. res.set_chunked_content_provider(
  20340. "text/event-stream", [](size_t offset, DataSink &sink) {
  20341. if (offset == 0) {
  20342. std::string events = "data: message1\n\ndata: message2\n\n";
  20343. sink.write(events.data(), events.size());
  20344. }
  20345. return false;
  20346. });
  20347. });
  20348. Client client("localhost", get_port());
  20349. sse::SSEClient sse(client, "/multi-event");
  20350. std::vector<std::string> received_messages;
  20351. std::mutex messages_mutex;
  20352. sse.on_message([&](const sse::SSEMessage &msg) {
  20353. std::lock_guard<std::mutex> lock(messages_mutex);
  20354. received_messages.push_back(msg.data);
  20355. });
  20356. sse.set_reconnect_interval(100);
  20357. sse.set_max_reconnect_attempts(1);
  20358. sse.start_async();
  20359. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20360. sse.stop();
  20361. std::lock_guard<std::mutex> lock(messages_mutex);
  20362. EXPECT_GE(received_messages.size(), 2u);
  20363. if (received_messages.size() >= 2) {
  20364. EXPECT_EQ(received_messages[0], "message1");
  20365. EXPECT_EQ(received_messages[1], "message2");
  20366. }
  20367. }
  20368. // Test: on_event for specific types
  20369. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  20370. Client client("localhost", get_port());
  20371. sse::SSEClient sse(client, "/custom-events");
  20372. std::atomic<bool> update_received{false};
  20373. std::atomic<bool> delete_received{false};
  20374. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  20375. if (msg.data == "updated") { update_received.store(true); }
  20376. });
  20377. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  20378. if (msg.data == "deleted") { delete_received.store(true); }
  20379. });
  20380. sse.set_max_reconnect_attempts(1);
  20381. sse.start_async();
  20382. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  20383. sse.stop();
  20384. EXPECT_TRUE(update_received.load());
  20385. EXPECT_TRUE(delete_received.load());
  20386. }
  20387. // Test: on_error callback on connection failure
  20388. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  20389. // Connect to a non-existent port
  20390. Client client("localhost", 59999);
  20391. sse::SSEClient sse(client, "/events");
  20392. std::atomic<bool> error_called{false};
  20393. Error received_error = Error::Success;
  20394. sse.on_error([&](Error err) {
  20395. error_called.store(true);
  20396. received_error = err;
  20397. });
  20398. sse.set_reconnect_interval(50);
  20399. sse.set_max_reconnect_attempts(1);
  20400. sse.start_async();
  20401. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20402. sse.stop();
  20403. EXPECT_TRUE(error_called.load());
  20404. EXPECT_NE(received_error, Error::Success);
  20405. }
  20406. // Test: Last-Event-ID header sent on reconnect
  20407. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  20408. // Endpoint that sends event with ID
  20409. server_->Get("/event-with-id", [](const Request &, Response &res) {
  20410. res.set_chunked_content_provider(
  20411. "text/event-stream", [](size_t offset, DataSink &sink) {
  20412. if (offset == 0) {
  20413. std::string event = "id: evt-123\ndata: test\n\n";
  20414. sink.write(event.data(), event.size());
  20415. }
  20416. return false;
  20417. });
  20418. });
  20419. Client client("localhost", get_port());
  20420. sse::SSEClient sse(client, "/event-with-id");
  20421. std::atomic<bool> id_received{false};
  20422. sse.on_message([&](const sse::SSEMessage &msg) {
  20423. if (!msg.id.empty()) { id_received.store(true); }
  20424. });
  20425. sse.set_reconnect_interval(100);
  20426. sse.set_max_reconnect_attempts(1);
  20427. sse.start_async();
  20428. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20429. sse.stop();
  20430. EXPECT_TRUE(id_received.load());
  20431. EXPECT_EQ(sse.last_event_id(), "evt-123");
  20432. }
  20433. // Test: Manual stop
  20434. TEST_F(SSEIntegrationTest, ManualStop) {
  20435. // Endpoint that sends one event and stays open briefly
  20436. std::atomic<bool> handler_running{true};
  20437. server_->Get("/stay-open", [&handler_running](const Request &,
  20438. Response &res) {
  20439. res.set_chunked_content_provider(
  20440. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  20441. if (offset == 0) {
  20442. std::string event = "data: connected\n\n";
  20443. sink.write(event.data(), event.size());
  20444. }
  20445. // Keep connection open while handler_running is true
  20446. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  20447. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20448. }
  20449. return false;
  20450. });
  20451. });
  20452. Client client("localhost", get_port());
  20453. sse::SSEClient sse(client, "/stay-open");
  20454. std::atomic<bool> connected{false};
  20455. sse.on_open([&connected]() { connected.store(true); });
  20456. sse.set_reconnect_interval(100);
  20457. sse.set_max_reconnect_attempts(1);
  20458. sse.start_async();
  20459. // Wait for connection to establish
  20460. for (int i = 0; i < 20 && !connected.load(); ++i) {
  20461. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20462. }
  20463. EXPECT_TRUE(connected.load());
  20464. EXPECT_TRUE(sse.is_connected());
  20465. // Signal handler to stop
  20466. handler_running.store(false);
  20467. // Stop SSE client
  20468. sse.stop();
  20469. EXPECT_FALSE(sse.is_connected());
  20470. }
  20471. // Test: SSEClient with custom headers
  20472. TEST_F(SSEIntegrationTest, CustomHeaders) {
  20473. // Setup a server endpoint that checks for custom header
  20474. std::atomic<bool> header_received{false};
  20475. server_->Get("/header-check", [&](const Request &req, Response &res) {
  20476. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  20477. header_received.store(true);
  20478. }
  20479. res.set_chunked_content_provider("text/event-stream",
  20480. [](size_t, DataSink &) { return false; });
  20481. });
  20482. Client client("localhost", get_port());
  20483. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20484. sse::SSEClient sse(client, "/header-check", headers);
  20485. sse.set_max_reconnect_attempts(1);
  20486. sse.start_async();
  20487. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20488. sse.stop();
  20489. EXPECT_TRUE(header_received.load());
  20490. }
  20491. // Test: Reconnect interval configuration
  20492. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  20493. Client client("localhost", get_port());
  20494. sse::SSEClient sse(client, "/events");
  20495. auto &result = sse.set_reconnect_interval(500);
  20496. // Builder pattern should return reference to self
  20497. EXPECT_EQ(&result, &sse);
  20498. }
  20499. // Test: Max reconnect attempts
  20500. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  20501. // Connect to non-existent port to force reconnects
  20502. Client client("localhost", 59998);
  20503. sse::SSEClient sse(client, "/events");
  20504. std::atomic<int> error_count{0};
  20505. sse.on_error([&](Error) { error_count.fetch_add(1); });
  20506. sse.set_reconnect_interval(50);
  20507. sse.set_max_reconnect_attempts(2);
  20508. auto start = std::chrono::steady_clock::now();
  20509. sse.start(); // Blocking call
  20510. auto end = std::chrono::steady_clock::now();
  20511. // Should have stopped after 2 failed attempts
  20512. EXPECT_GE(error_count.load(), 2);
  20513. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  20514. auto duration =
  20515. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  20516. #ifdef _WIN32
  20517. // Windows is much slower for socket connection failures
  20518. EXPECT_LT(duration.count(), 7000);
  20519. #else
  20520. EXPECT_LT(duration.count(), 1000);
  20521. #endif
  20522. }
  20523. // Test: Multi-line data in integration
  20524. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  20525. // Endpoint with multi-line data
  20526. server_->Get("/multiline-data", [](const Request &, Response &res) {
  20527. res.set_chunked_content_provider(
  20528. "text/event-stream", [](size_t offset, DataSink &sink) {
  20529. if (offset == 0) {
  20530. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  20531. sink.write(event.data(), event.size());
  20532. }
  20533. return false;
  20534. });
  20535. });
  20536. Client client("localhost", get_port());
  20537. sse::SSEClient sse(client, "/multiline-data");
  20538. std::string received_data;
  20539. std::mutex data_mutex;
  20540. sse.on_message([&](const sse::SSEMessage &msg) {
  20541. std::lock_guard<std::mutex> lock(data_mutex);
  20542. received_data = msg.data;
  20543. });
  20544. sse.set_reconnect_interval(100);
  20545. sse.set_max_reconnect_attempts(1);
  20546. sse.start_async();
  20547. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20548. sse.stop();
  20549. std::lock_guard<std::mutex> lock(data_mutex);
  20550. EXPECT_EQ(received_data, "line1\nline2\nline3");
  20551. }
  20552. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  20553. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  20554. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  20555. DataSink &sink) {
  20556. if (offset == 0) {
  20557. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  20558. sink.write(events.data(), events.size());
  20559. }
  20560. return false;
  20561. });
  20562. });
  20563. Client client("localhost", get_port());
  20564. sse::SSEClient sse(client, "/empty-data-lines");
  20565. std::mutex mutex;
  20566. std::condition_variable cv;
  20567. std::vector<std::string> received;
  20568. sse.on_message([&](const sse::SSEMessage &msg) {
  20569. std::lock_guard<std::mutex> lock(mutex);
  20570. received.push_back(msg.data);
  20571. cv.notify_all();
  20572. });
  20573. sse.set_max_reconnect_attempts(1);
  20574. sse.start_async();
  20575. {
  20576. std::unique_lock<std::mutex> lock(mutex);
  20577. cv.wait_for(lock, std::chrono::seconds(2),
  20578. [&] { return received.size() >= 3; });
  20579. }
  20580. sse.stop();
  20581. ASSERT_GE(received.size(), 3u);
  20582. EXPECT_EQ(received[0], "");
  20583. EXPECT_EQ(received[1], "\nhello");
  20584. EXPECT_EQ(received[2], "");
  20585. }
  20586. // Test: Auto-reconnect after server disconnection
  20587. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  20588. std::atomic<int> connection_count{0};
  20589. std::atomic<int> message_count{0};
  20590. // Endpoint that sends one event and closes, forcing reconnect
  20591. server_->Get("/reconnect-test",
  20592. [&connection_count](const Request &, Response &res) {
  20593. connection_count.fetch_add(1);
  20594. res.set_chunked_content_provider(
  20595. "text/event-stream", [](size_t offset, DataSink &sink) {
  20596. if (offset == 0) {
  20597. std::string event = "data: hello\n\n";
  20598. sink.write(event.data(), event.size());
  20599. }
  20600. return false; // Close connection after sending
  20601. });
  20602. });
  20603. Client client("localhost", get_port());
  20604. sse::SSEClient sse(client, "/reconnect-test");
  20605. sse.on_message([&message_count](const sse::SSEMessage &) {
  20606. message_count.fetch_add(1);
  20607. });
  20608. sse.set_reconnect_interval(100);
  20609. sse.set_max_reconnect_attempts(3);
  20610. sse.start_async();
  20611. // Wait long enough for multiple reconnects
  20612. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20613. sse.stop();
  20614. // Should have connected multiple times (initial + reconnects)
  20615. EXPECT_GE(connection_count.load(), 2);
  20616. // Should have received messages from multiple connections
  20617. EXPECT_GE(message_count.load(), 2);
  20618. }
  20619. // Test: A retry field that is not all ASCII digits is ignored
  20620. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  20621. std::atomic<int> connection_count{0};
  20622. server_->Get("/bad-retry",
  20623. [&connection_count](const Request &, Response &res) {
  20624. connection_count.fetch_add(1);
  20625. res.set_chunked_content_provider(
  20626. "text/event-stream", [](size_t offset, DataSink &sink) {
  20627. if (offset == 0) {
  20628. std::string event = "retry: -1\ndata: hello\n\n";
  20629. sink.write(event.data(), event.size());
  20630. }
  20631. return false;
  20632. });
  20633. });
  20634. Client client("localhost", get_port());
  20635. sse::SSEClient sse(client, "/bad-retry");
  20636. sse.set_reconnect_interval(10000);
  20637. sse.start_async();
  20638. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20639. sse.stop();
  20640. EXPECT_EQ(connection_count.load(), 1);
  20641. }
  20642. // Test: A retry field of all ASCII digits sets the reconnection time
  20643. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  20644. std::mutex mutex;
  20645. std::condition_variable cv;
  20646. std::vector<std::chrono::steady_clock::time_point> connected_at;
  20647. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  20648. {
  20649. std::lock_guard<std::mutex> lock(mutex);
  20650. connected_at.push_back(std::chrono::steady_clock::now());
  20651. cv.notify_all();
  20652. }
  20653. res.set_chunked_content_provider(
  20654. "text/event-stream", [](size_t offset, DataSink &sink) {
  20655. if (offset == 0) {
  20656. std::string event = "retry: 0\ndata: hello\n\n";
  20657. sink.write(event.data(), event.size());
  20658. }
  20659. return false;
  20660. });
  20661. });
  20662. Client client("localhost", get_port());
  20663. sse::SSEClient sse(client, "/zero-retry");
  20664. sse.set_reconnect_interval(10000);
  20665. sse.start_async();
  20666. {
  20667. std::unique_lock<std::mutex> lock(mutex);
  20668. cv.wait_for(lock, std::chrono::seconds(5),
  20669. [&] { return connected_at.size() >= 2; });
  20670. }
  20671. sse.stop();
  20672. // The server-supplied interval is applied, but never below 100ms, so
  20673. // "retry: 0" does not cause a busy reconnect loop
  20674. std::lock_guard<std::mutex> lock(mutex);
  20675. ASSERT_GE(connected_at.size(), 2u);
  20676. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  20677. connected_at[1] - connected_at[0])
  20678. .count();
  20679. EXPECT_GE(interval_ms, 100);
  20680. }
  20681. // Test: Last-Event-ID sent on reconnect
  20682. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  20683. std::atomic<int> connection_count{0};
  20684. std::vector<std::string> received_last_event_ids;
  20685. std::mutex id_mutex;
  20686. // Endpoint that checks Last-Event-ID header and sends event with ID
  20687. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  20688. int conn = connection_count.fetch_add(1);
  20689. // Capture the Last-Event-ID header from each connection
  20690. {
  20691. std::lock_guard<std::mutex> lock(id_mutex);
  20692. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  20693. }
  20694. res.set_chunked_content_provider(
  20695. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  20696. if (offset == 0) {
  20697. std::string event =
  20698. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  20699. sink.write(event.data(), event.size());
  20700. }
  20701. return false;
  20702. });
  20703. });
  20704. Client client("localhost", get_port());
  20705. sse::SSEClient sse(client, "/reconnect-with-id");
  20706. sse.set_reconnect_interval(100);
  20707. sse.set_max_reconnect_attempts(3);
  20708. sse.start_async();
  20709. // Wait for at least 2 connections
  20710. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20711. sse.stop();
  20712. // Verify behavior
  20713. std::lock_guard<std::mutex> lock(id_mutex);
  20714. EXPECT_GE(received_last_event_ids.size(), 2u);
  20715. // First connection should have no Last-Event-ID
  20716. if (!received_last_event_ids.empty()) {
  20717. EXPECT_EQ(received_last_event_ids[0], "");
  20718. }
  20719. // Second connection should have Last-Event-ID from first connection
  20720. if (received_last_event_ids.size() >= 2) {
  20721. EXPECT_EQ(received_last_event_ids[1], "event-0");
  20722. }
  20723. }
  20724. // Test: set_headers updates headers used on reconnect
  20725. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  20726. std::vector<std::string> received_tokens;
  20727. std::mutex token_mutex;
  20728. // Endpoint that captures Authorization header
  20729. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  20730. {
  20731. std::lock_guard<std::mutex> lock(token_mutex);
  20732. received_tokens.push_back(req.get_header_value("Authorization"));
  20733. }
  20734. res.set_chunked_content_provider(
  20735. "text/event-stream", [](size_t offset, DataSink &sink) {
  20736. if (offset == 0) {
  20737. std::string event = "data: hello\n\n";
  20738. sink.write(event.data(), event.size());
  20739. }
  20740. return false; // Close connection to trigger reconnect
  20741. });
  20742. });
  20743. Client client("localhost", get_port());
  20744. Headers headers = {{"Authorization", "Bearer old-token"}};
  20745. sse::SSEClient sse(client, "/auth-check", headers);
  20746. // Update headers on each successful connection
  20747. sse.on_open(
  20748. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  20749. sse.set_reconnect_interval(100);
  20750. sse.set_max_reconnect_attempts(3);
  20751. sse.start_async();
  20752. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20753. sse.stop();
  20754. std::lock_guard<std::mutex> lock(token_mutex);
  20755. ASSERT_GE(received_tokens.size(), 2u);
  20756. // First connection uses original header
  20757. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  20758. // Second connection uses updated header from set_headers
  20759. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20760. }
  20761. // Test: 401 allows reconnection (so on_error can refresh headers)
  20762. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20763. std::atomic<int> connection_count{0};
  20764. // Endpoint: returns 401 on first attempt, 200 on second
  20765. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20766. int conn = connection_count.fetch_add(1);
  20767. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20768. res.status = StatusCode::Unauthorized_401;
  20769. res.set_content("Unauthorized", "text/plain");
  20770. return;
  20771. }
  20772. res.set_chunked_content_provider(
  20773. "text/event-stream", [](size_t offset, DataSink &sink) {
  20774. if (offset == 0) {
  20775. std::string event = "data: authenticated\n\n";
  20776. sink.write(event.data(), event.size());
  20777. }
  20778. return false;
  20779. });
  20780. });
  20781. Client client("localhost", get_port());
  20782. Headers headers = {{"Authorization", "Bearer expired"}};
  20783. sse::SSEClient sse(client, "/auth-retry", headers);
  20784. std::atomic<bool> message_received{false};
  20785. // Refresh token on error
  20786. sse.on_error(
  20787. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20788. sse.on_message([&](const sse::SSEMessage &msg) {
  20789. if (msg.data == "authenticated") { message_received.store(true); }
  20790. });
  20791. sse.set_reconnect_interval(100);
  20792. sse.set_max_reconnect_attempts(3);
  20793. sse.start_async();
  20794. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20795. sse.stop();
  20796. // Should have reconnected after 401 and succeeded with new token
  20797. EXPECT_GE(connection_count.load(), 2);
  20798. EXPECT_TRUE(message_received.load());
  20799. }
  20800. TEST(Issue2318Test, EmptyHostString) {
  20801. {
  20802. httplib::Client cli_empty("", PORT);
  20803. auto res = cli_empty.Get("/");
  20804. ASSERT_FALSE(res);
  20805. EXPECT_EQ(httplib::Error::Connection, res.error());
  20806. }
  20807. {
  20808. httplib::Client cli(" ", PORT);
  20809. auto res = cli.Get("/");
  20810. ASSERT_FALSE(res);
  20811. EXPECT_EQ(httplib::Error::Connection, res.error());
  20812. }
  20813. }
  20814. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20815. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20816. Server svr;
  20817. // Set a small payload limit (1KB)
  20818. svr.set_payload_max_length(1024);
  20819. svr.Post("/test", [&](const Request &req, Response &res) {
  20820. res.set_content("Body size: " + std::to_string(req.body.size()),
  20821. "text/plain");
  20822. });
  20823. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20824. auto se = detail::scope_exit([&] {
  20825. svr.stop();
  20826. listen_thread.join();
  20827. });
  20828. svr.wait_until_ready();
  20829. // Create data that compresses well but exceeds limit when decompressed
  20830. // 8KB of repeated null bytes compresses to a very small size
  20831. std::string original_data(8 * 1024, '\0');
  20832. // Compress the data using gzip
  20833. std::string compressed_data;
  20834. detail::gzip_compressor compressor;
  20835. compressor.compress(original_data.data(), original_data.size(), true,
  20836. [&](const char *data, size_t size) {
  20837. compressed_data.append(data, size);
  20838. return true;
  20839. });
  20840. // Verify compression worked (compressed should be much smaller)
  20841. ASSERT_LT(compressed_data.size(), original_data.size());
  20842. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20843. // Send compressed data with Content-Encoding: gzip
  20844. Client cli(HOST, PORT);
  20845. Headers headers = {{"Content-Encoding", "gzip"}};
  20846. auto res =
  20847. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20848. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20850. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20851. }
  20852. #endif
  20853. // ============================================================================
  20854. // OpenSSL-Specific Tests
  20855. // ============================================================================
  20856. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20857. X509 *readCertificate(const std::string &strFileName) {
  20858. std::ifstream inStream(strFileName);
  20859. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20860. std::istreambuf_iterator<char>());
  20861. if (strCertPEM.empty()) return (nullptr);
  20862. BIO *pbCert = BIO_new(BIO_s_mem());
  20863. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20864. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20865. BIO_free(pbCert);
  20866. return (pCert);
  20867. }
  20868. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20869. std::ifstream inStream(strFileName);
  20870. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20871. std::istreambuf_iterator<char>());
  20872. if (strPrivateKeyPEM.empty()) return (nullptr);
  20873. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20874. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20875. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20876. BIO_free(pbPrivKey);
  20877. return (pPrivateKey);
  20878. }
  20879. TEST(BindServerTest, UpdateCerts) {
  20880. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20881. int port = svr.bind_to_any_port("0.0.0.0");
  20882. ASSERT_TRUE(svr.is_valid());
  20883. ASSERT_TRUE(port > 0);
  20884. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20885. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20886. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20887. ASSERT_TRUE(cert != nullptr);
  20888. ASSERT_TRUE(ca_cert != nullptr);
  20889. ASSERT_TRUE(key != nullptr);
  20890. X509_STORE *cert_store = X509_STORE_new();
  20891. X509_STORE_add_cert(cert_store, ca_cert);
  20892. // svr.update_certs(cert, key, cert_store); // deprecated
  20893. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20894. CLIENT_CA_CERT_FILE);
  20895. ASSERT_TRUE(svr.is_valid());
  20896. svr.stop();
  20897. X509_STORE_free(cert_store);
  20898. X509_free(cert);
  20899. X509_free(ca_cert);
  20900. EVP_PKEY_free(key);
  20901. }
  20902. // Test that update_certs() updates client CA list correctly
  20903. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  20904. // Start with file-based constructor
  20905. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20906. ASSERT_TRUE(svr.is_valid());
  20907. // Initially no client CA list should be set
  20908. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20909. ASSERT_TRUE(ssl_ctx != nullptr);
  20910. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  20911. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  20912. EXPECT_EQ(0, count_before);
  20913. // Now update with client CA (PEM string)
  20914. std::string cert_pem, key_pem, ca_pem;
  20915. read_file(SERVER_CERT_FILE, cert_pem);
  20916. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  20917. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  20918. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  20919. ASSERT_TRUE(svr.is_valid());
  20920. // Now client CA list should be set
  20921. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  20922. ASSERT_TRUE(ca_list_after != nullptr);
  20923. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  20924. }
  20925. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  20926. // Test that the file-path SSLServer constructor properly sets the client CA
  20927. // list that is sent to clients during the TLS handshake (CertificateRequest)
  20928. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20929. ASSERT_TRUE(svr.is_valid());
  20930. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20931. ASSERT_TRUE(ssl_ctx != nullptr);
  20932. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  20933. ASSERT_TRUE(ca_list != nullptr);
  20934. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  20935. }
  20936. #endif
  20937. // ============================================================================
  20938. // MbedTLS-Specific Tests
  20939. // ============================================================================
  20940. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  20941. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  20942. using namespace httplib::tls;
  20943. // Track if callback was invoked
  20944. bool callback_invoked = false;
  20945. // The callback receives void* ctx which is actually MbedTlsContext*
  20946. // We can access the mbedtls_ssl_config via the context
  20947. auto setup_callback = [&callback_invoked](void *ctx) {
  20948. callback_invoked = true;
  20949. // Cast to MbedTlsContext* to access the ssl config
  20950. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  20951. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  20952. // Use static variables to hold certificate data (simplified for test)
  20953. static mbedtls_x509_crt own_cert;
  20954. static mbedtls_pk_context own_key;
  20955. static mbedtls_x509_crt ca_chain;
  20956. static bool initialized = false;
  20957. if (!initialized) {
  20958. mbedtls_x509_crt_init(&own_cert);
  20959. mbedtls_pk_init(&own_key);
  20960. mbedtls_x509_crt_init(&ca_chain);
  20961. // Load server certificate
  20962. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  20963. return false;
  20964. }
  20965. // Load server private key.
  20966. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  20967. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  20968. #if MBEDTLS_VERSION_MAJOR == 3
  20969. ,
  20970. mbedtls_ctr_drbg_random, nullptr
  20971. #endif
  20972. ) != 0) {
  20973. return false;
  20974. }
  20975. // Load CA chain for client verification
  20976. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  20977. return false;
  20978. }
  20979. initialized = true;
  20980. }
  20981. // Configure the SSL config
  20982. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  20983. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  20984. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  20985. // Set minimum TLS version using mbedTLS native API
  20986. #if MBEDTLS_VERSION_MAJOR >= 3
  20987. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  20988. #else
  20989. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  20990. MBEDTLS_SSL_MINOR_VERSION_3);
  20991. #endif
  20992. return true;
  20993. };
  20994. SSLServer svr(setup_callback);
  20995. ASSERT_TRUE(svr.is_valid());
  20996. ASSERT_TRUE(callback_invoked);
  20997. svr.Get("/test", [&](const Request &req, Response &res) {
  20998. res.set_content("test", "text/plain");
  20999. auto cert = req.peer_cert();
  21000. ASSERT_TRUE(static_cast<bool>(cert));
  21001. auto common_name = cert.subject_cn();
  21002. EXPECT_EQ("Common Name", common_name);
  21003. });
  21004. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21005. auto se = detail::scope_exit([&] {
  21006. svr.stop();
  21007. t.join();
  21008. ASSERT_FALSE(svr.is_running());
  21009. });
  21010. svr.wait_until_ready();
  21011. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  21012. cli.enable_server_certificate_verification(false);
  21013. cli.set_connection_timeout(30);
  21014. auto res = cli.Get("/test");
  21015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21016. ASSERT_EQ(StatusCode::OK_200, res->status);
  21017. }
  21018. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  21019. // context (owning mbedtls_ssl_config) before shutting down a still-open
  21020. // keep-alive SSL session, which reads through that config in
  21021. // mbedtls_ssl_close_notify.
  21022. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  21023. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21024. ASSERT_TRUE(svr.is_valid());
  21025. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  21026. res.set_content("test", "text/plain");
  21027. });
  21028. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21029. auto se = detail::scope_exit([&] {
  21030. svr.stop();
  21031. t.join();
  21032. ASSERT_FALSE(svr.is_running());
  21033. });
  21034. svr.wait_until_ready();
  21035. {
  21036. SSLClient cli(HOST, PORT);
  21037. cli.enable_server_certificate_verification(false);
  21038. cli.set_keep_alive(true);
  21039. auto res = cli.Get("/test");
  21040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21041. ASSERT_EQ(StatusCode::OK_200, res->status);
  21042. // cli is destructed here with the keep-alive SSL session still open.
  21043. }
  21044. }
  21045. #endif
  21046. // WebSocket Tests
  21047. TEST(WebSocketTest, RSVBitsMustBeZero) {
  21048. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  21049. // defining the meaning of these bits has been negotiated.
  21050. auto make_frame = [](uint8_t first_byte) {
  21051. std::string frame;
  21052. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  21053. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  21054. frame += "Hello";
  21055. return frame;
  21056. };
  21057. // RSV1 set (0x40)
  21058. {
  21059. detail::BufferStream strm;
  21060. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  21061. ws::Opcode opcode;
  21062. std::string payload;
  21063. bool fin;
  21064. EXPECT_EQ(
  21065. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21066. ws::impl::FrameRead::Fail);
  21067. }
  21068. // RSV2 set (0x20)
  21069. {
  21070. detail::BufferStream strm;
  21071. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  21072. ws::Opcode opcode;
  21073. std::string payload;
  21074. bool fin;
  21075. EXPECT_EQ(
  21076. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21077. ws::impl::FrameRead::Fail);
  21078. }
  21079. // RSV3 set (0x10)
  21080. {
  21081. detail::BufferStream strm;
  21082. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  21083. ws::Opcode opcode;
  21084. std::string payload;
  21085. bool fin;
  21086. EXPECT_EQ(
  21087. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21088. ws::impl::FrameRead::Fail);
  21089. }
  21090. // No RSV bits set - should succeed
  21091. {
  21092. detail::BufferStream strm;
  21093. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  21094. ws::Opcode opcode;
  21095. std::string payload;
  21096. bool fin;
  21097. EXPECT_EQ(
  21098. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21099. ws::impl::FrameRead::Ok);
  21100. EXPECT_EQ(ws::Opcode::Text, opcode);
  21101. EXPECT_EQ("Hello", payload);
  21102. EXPECT_TRUE(fin);
  21103. }
  21104. }
  21105. TEST(WebSocketTest, ControlFrameValidation) {
  21106. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  21107. // payload length <= 125.
  21108. // Ping with FIN=0 - must be rejected
  21109. {
  21110. detail::BufferStream strm;
  21111. std::string frame;
  21112. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  21113. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21114. strm.write(frame.data(), frame.size());
  21115. ws::Opcode opcode;
  21116. std::string payload;
  21117. bool fin;
  21118. EXPECT_EQ(
  21119. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21120. ws::impl::FrameRead::Fail);
  21121. }
  21122. // Close with FIN=0 - must be rejected
  21123. {
  21124. detail::BufferStream strm;
  21125. std::string frame;
  21126. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  21127. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21128. strm.write(frame.data(), frame.size());
  21129. ws::Opcode opcode;
  21130. std::string payload;
  21131. bool fin;
  21132. EXPECT_EQ(
  21133. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21134. ws::impl::FrameRead::Fail);
  21135. }
  21136. // Ping with payload_len=126 (extended length) - must be rejected
  21137. {
  21138. detail::BufferStream strm;
  21139. std::string frame;
  21140. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21141. frame += static_cast<char>(126); // payload_len=126 (>125)
  21142. frame += static_cast<char>(0x00); // extended length high byte
  21143. frame += static_cast<char>(126); // extended length low byte
  21144. frame += std::string(126, 'x');
  21145. strm.write(frame.data(), frame.size());
  21146. ws::Opcode opcode;
  21147. std::string payload;
  21148. bool fin;
  21149. EXPECT_EQ(
  21150. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21151. ws::impl::FrameRead::Fail);
  21152. }
  21153. // Ping with FIN=1 and payload_len=125 - should succeed
  21154. {
  21155. detail::BufferStream strm;
  21156. std::string frame;
  21157. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21158. frame += static_cast<char>(125); // payload_len=125
  21159. frame += std::string(125, 'x');
  21160. strm.write(frame.data(), frame.size());
  21161. ws::Opcode opcode;
  21162. std::string payload;
  21163. bool fin;
  21164. EXPECT_EQ(
  21165. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21166. ws::impl::FrameRead::Ok);
  21167. EXPECT_EQ(ws::Opcode::Ping, opcode);
  21168. EXPECT_EQ(125u, payload.size());
  21169. EXPECT_TRUE(fin);
  21170. }
  21171. }
  21172. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  21173. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  21174. // length MUST be 0.
  21175. // MSB set - must be rejected
  21176. {
  21177. detail::BufferStream strm;
  21178. std::string frame;
  21179. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21180. frame += static_cast<char>(127); // 64-bit extended length
  21181. frame += static_cast<char>(0x80); // MSB set (invalid)
  21182. frame += std::string(7, '\0'); // remaining 7 bytes of length
  21183. strm.write(frame.data(), frame.size());
  21184. ws::Opcode opcode;
  21185. std::string payload;
  21186. bool fin;
  21187. EXPECT_EQ(
  21188. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21189. ws::impl::FrameRead::Fail);
  21190. }
  21191. // MSB clear - should pass length parsing (will be rejected by max_len,
  21192. // but that's a different check; use a small length to verify)
  21193. {
  21194. detail::BufferStream strm;
  21195. std::string frame;
  21196. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21197. frame += static_cast<char>(127); // 64-bit extended length
  21198. frame += std::string(7, '\0'); // high bytes = 0
  21199. frame += static_cast<char>(0x03); // length = 3
  21200. frame += "abc";
  21201. strm.write(frame.data(), frame.size());
  21202. ws::Opcode opcode;
  21203. std::string payload;
  21204. bool fin;
  21205. EXPECT_EQ(
  21206. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21207. ws::impl::FrameRead::Ok);
  21208. EXPECT_EQ(ws::Opcode::Text, opcode);
  21209. EXPECT_EQ("abc", payload);
  21210. }
  21211. }
  21212. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  21213. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  21214. // Valid UTF-8
  21215. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  21216. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  21217. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  21218. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  21219. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  21220. // Invalid UTF-8
  21221. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  21222. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  21223. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  21224. EXPECT_FALSE(
  21225. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  21226. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  21227. }
  21228. TEST(WebSocketTest, ConnectAndDisconnect) {
  21229. Server svr;
  21230. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21231. std::string msg;
  21232. while (ws.read(msg)) {}
  21233. });
  21234. auto port = svr.bind_to_any_port(HOST);
  21235. std::thread t([&]() { svr.listen_after_bind(); });
  21236. svr.wait_until_ready();
  21237. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21238. auto res = client.connect();
  21239. ASSERT_TRUE(res);
  21240. EXPECT_EQ(Error::Success, res.error());
  21241. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  21242. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  21243. EXPECT_TRUE(client.is_open());
  21244. client.close();
  21245. EXPECT_FALSE(client.is_open());
  21246. svr.stop();
  21247. t.join();
  21248. }
  21249. TEST(WebSocketTest, ValidURL) {
  21250. ws::WebSocketClient ws1("ws://localhost:8080/path");
  21251. EXPECT_TRUE(ws1.is_valid());
  21252. ws::WebSocketClient ws2("ws://example.com/path");
  21253. EXPECT_TRUE(ws2.is_valid());
  21254. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  21255. EXPECT_TRUE(ws3.is_valid());
  21256. #ifdef CPPHTTPLIB_SSL_ENABLED
  21257. ws::WebSocketClient wss1("wss://example.com/path");
  21258. EXPECT_TRUE(wss1.is_valid());
  21259. ws::WebSocketClient wss2("wss://example.com:443/path");
  21260. EXPECT_TRUE(wss2.is_valid());
  21261. #endif
  21262. }
  21263. TEST(WebSocketTest, InvalidURL) {
  21264. // No scheme
  21265. ws::WebSocketClient ws1("localhost:8080/path");
  21266. EXPECT_FALSE(ws1.is_valid());
  21267. // No path
  21268. ws::WebSocketClient ws2("ws://localhost:8080");
  21269. EXPECT_FALSE(ws2.is_valid());
  21270. // Empty string
  21271. ws::WebSocketClient ws3("");
  21272. EXPECT_FALSE(ws3.is_valid());
  21273. // Missing host
  21274. ws::WebSocketClient ws4("ws://:8080/path");
  21275. EXPECT_FALSE(ws4.is_valid());
  21276. // Port number overflow — should not crash
  21277. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  21278. EXPECT_FALSE(ws5.is_valid());
  21279. // Port out of range
  21280. ws::WebSocketClient ws6("ws://localhost:99999/path");
  21281. EXPECT_FALSE(ws6.is_valid());
  21282. }
  21283. TEST(WebSocketTest, UnsupportedScheme) {
  21284. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  21285. ws::WebSocketClient ws1("http://localhost:8080/path");
  21286. EXPECT_FALSE(ws1.is_valid());
  21287. ws::WebSocketClient ws2("https://localhost:8080/path");
  21288. EXPECT_FALSE(ws2.is_valid());
  21289. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  21290. EXPECT_FALSE(ws3.is_valid());
  21291. #else
  21292. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  21293. std::invalid_argument);
  21294. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  21295. std::invalid_argument);
  21296. #endif
  21297. }
  21298. TEST(WebSocketTest, ConnectWhenInvalid) {
  21299. ws::WebSocketClient ws("not a valid url");
  21300. EXPECT_FALSE(ws.is_valid());
  21301. auto res = ws.connect();
  21302. EXPECT_FALSE(res);
  21303. EXPECT_EQ(Error::Connection, res.error());
  21304. EXPECT_EQ(-1, res.status());
  21305. }
  21306. TEST(WebSocketTest, ConnectRefusedReportsError) {
  21307. // Grab a port that is free, then close it again so nothing listens there
  21308. Server svr;
  21309. auto port = svr.bind_to_any_port(HOST);
  21310. svr.stop();
  21311. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21312. auto res = client.connect();
  21313. ASSERT_FALSE(res);
  21314. EXPECT_EQ(Error::Connection, res.error());
  21315. EXPECT_EQ(-1, res.status());
  21316. }
  21317. TEST(WebSocketTest, DefaultPort) {
  21318. ws::WebSocketClient ws1("ws://example.com/path");
  21319. EXPECT_TRUE(ws1.is_valid());
  21320. // ws:// defaults to port 80 (verified by successful parse)
  21321. #ifdef CPPHTTPLIB_SSL_ENABLED
  21322. ws::WebSocketClient ws2("wss://example.com/path");
  21323. EXPECT_TRUE(ws2.is_valid());
  21324. // wss:// defaults to port 443 (verified by successful parse)
  21325. #endif
  21326. }
  21327. TEST(WebSocketTest, IPv6LiteralAddress) {
  21328. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  21329. EXPECT_TRUE(ws1.is_valid());
  21330. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  21331. EXPECT_TRUE(ws2.is_valid());
  21332. }
  21333. TEST(WebSocketTest, ComplexPath) {
  21334. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  21335. EXPECT_TRUE(ws1.is_valid());
  21336. ws::WebSocketClient ws2("ws://localhost:8080/");
  21337. EXPECT_TRUE(ws2.is_valid());
  21338. }
  21339. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  21340. Server svr;
  21341. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21342. std::string msg;
  21343. while (ws.read(msg)) {}
  21344. });
  21345. auto port = svr.bind_to_any_port(HOST);
  21346. std::thread t([&]() { svr.listen_after_bind(); });
  21347. svr.wait_until_ready();
  21348. auto another_host = "example.com";
  21349. auto wrong_ip = "192.0.2.1";
  21350. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21351. client.set_hostname_addr_map({{another_host, wrong_ip}});
  21352. ASSERT_TRUE(client.connect());
  21353. EXPECT_TRUE(client.is_open());
  21354. client.close();
  21355. svr.stop();
  21356. t.join();
  21357. }
  21358. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  21359. Server svr;
  21360. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21361. std::string msg;
  21362. while (ws.read(msg)) {}
  21363. });
  21364. auto port = svr.bind_to_any_port(HOST);
  21365. std::thread t([&]() { svr.listen_after_bind(); });
  21366. svr.wait_until_ready();
  21367. auto wrong_ip = "192.0.2.1";
  21368. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21369. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  21370. client.set_connection_timeout(1);
  21371. client.set_read_timeout(1);
  21372. client.set_write_timeout(1);
  21373. EXPECT_FALSE(client.connect());
  21374. EXPECT_FALSE(client.is_open());
  21375. svr.stop();
  21376. t.join();
  21377. }
  21378. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  21379. // A mapped value that is not an IP literal must be resolved. HOST resolves
  21380. // from the hosts file, so this test needs no external DNS. "target.invalid"
  21381. // (RFC 6761) is only a map key and the Host header value.
  21382. auto host = "target.invalid";
  21383. Server svr;
  21384. std::string received_host;
  21385. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21386. received_host = req.get_header_value("Host");
  21387. std::string msg;
  21388. while (ws.read(msg)) {}
  21389. });
  21390. auto port = svr.bind_to_any_port(HOST);
  21391. std::thread t([&]() { svr.listen_after_bind(); });
  21392. // ASSERT_* below returns from the test body, which would leave t joinable
  21393. // and make ~thread call std::terminate.
  21394. auto se = detail::scope_exit([&] {
  21395. svr.stop();
  21396. if (t.joinable()) { t.join(); }
  21397. });
  21398. svr.wait_until_ready();
  21399. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  21400. std::to_string(port) + "/ws");
  21401. client.set_hostname_addr_map({{host, HOST}});
  21402. ASSERT_TRUE(client.connect());
  21403. EXPECT_TRUE(client.is_open());
  21404. client.close();
  21405. svr.stop();
  21406. t.join();
  21407. // The mapping only redirects the connection; the identity stays host_.
  21408. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  21409. }
  21410. class WebSocketIntegrationTest : public ::testing::Test {
  21411. protected:
  21412. void SetUp() override {
  21413. server_ = httplib::detail::make_unique<Server>();
  21414. setup_server();
  21415. start_server();
  21416. }
  21417. void TearDown() override {
  21418. server_->stop();
  21419. if (server_thread_.joinable()) { server_thread_.join(); }
  21420. }
  21421. void setup_server() {
  21422. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21423. std::string msg;
  21424. ws::ReadResult ret;
  21425. while ((ret = ws.read(msg))) {
  21426. if (ret == ws::Binary) {
  21427. ws.send(msg.data(), msg.size());
  21428. } else {
  21429. ws.send(msg);
  21430. }
  21431. }
  21432. });
  21433. server_->WebSocket("/ws-echo-string",
  21434. [](const Request &, ws::WebSocket &ws) {
  21435. std::string msg;
  21436. while (ws.read(msg)) {
  21437. ws.send("echo: " + msg);
  21438. }
  21439. });
  21440. server_->WebSocket(
  21441. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  21442. // Echo back request metadata
  21443. ws.send("path:" + req.path);
  21444. ws.send("header:" + req.get_header_value("X-Test-Header"));
  21445. std::string msg;
  21446. while (ws.read(msg)) {}
  21447. });
  21448. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  21449. std::string msg;
  21450. ws.read(msg); // wait for a message
  21451. ws.close();
  21452. });
  21453. server_->WebSocket("/ws-close-status",
  21454. [](const Request &, ws::WebSocket &ws) {
  21455. std::string msg;
  21456. ws.read(msg); // wait for a message
  21457. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  21458. });
  21459. server_->WebSocket(
  21460. "/ws-subprotocol",
  21461. [](const Request &, ws::WebSocket &ws) {
  21462. std::string msg;
  21463. while (ws.read(msg)) {
  21464. ws.send(msg);
  21465. }
  21466. },
  21467. [](const std::vector<std::string> &protocols) -> std::string {
  21468. for (const auto &p : protocols) {
  21469. if (p == "graphql-ws") { return p; }
  21470. }
  21471. return "";
  21472. });
  21473. server_->WebSocket(
  21474. "/ws-subprotocol-unoffered",
  21475. [](const Request &, ws::WebSocket &ws) {
  21476. std::string msg;
  21477. while (ws.read(msg)) {
  21478. ws.send(msg);
  21479. }
  21480. },
  21481. [](const std::vector<std::string> &) -> std::string {
  21482. return "admin";
  21483. });
  21484. }
  21485. void start_server() {
  21486. port_ = server_->bind_to_any_port(HOST);
  21487. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21488. server_->wait_until_ready();
  21489. }
  21490. std::unique_ptr<Server> server_;
  21491. std::thread server_thread_;
  21492. int port_ = 0;
  21493. };
  21494. TEST_F(WebSocketIntegrationTest, TextEcho) {
  21495. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21496. "/ws-echo");
  21497. ASSERT_TRUE(client.connect());
  21498. ASSERT_TRUE(client.is_open());
  21499. ASSERT_TRUE(client.send("Hello WebSocket"));
  21500. std::string msg;
  21501. EXPECT_EQ(ws::Text, client.read(msg));
  21502. EXPECT_EQ("Hello WebSocket", msg);
  21503. client.close();
  21504. }
  21505. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  21506. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21507. "/ws-echo");
  21508. ASSERT_TRUE(client.connect());
  21509. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  21510. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  21511. std::string msg;
  21512. EXPECT_EQ(ws::Binary, client.read(msg));
  21513. EXPECT_EQ(binary_data, msg);
  21514. client.close();
  21515. }
  21516. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  21517. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21518. "/ws-echo");
  21519. ASSERT_TRUE(client.connect());
  21520. for (int i = 0; i < 10; i++) {
  21521. auto text = "message " + std::to_string(i);
  21522. ASSERT_TRUE(client.send(text));
  21523. std::string msg;
  21524. ASSERT_TRUE(client.read(msg));
  21525. EXPECT_EQ(text, msg);
  21526. }
  21527. client.close();
  21528. }
  21529. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  21530. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21531. "/ws-close");
  21532. ASSERT_TRUE(client.connect());
  21533. // Send a message to trigger the server to close
  21534. ASSERT_TRUE(client.send("trigger close"));
  21535. // The server will close, so read should return false
  21536. std::string msg;
  21537. EXPECT_FALSE(client.read(msg));
  21538. EXPECT_FALSE(client.is_open());
  21539. }
  21540. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  21541. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21542. "/ws-echo");
  21543. ASSERT_TRUE(client.connect());
  21544. // 128KB message
  21545. std::string large_data(128 * 1024, 'X');
  21546. ASSERT_TRUE(client.send(large_data));
  21547. std::string msg;
  21548. ASSERT_TRUE(client.read(msg));
  21549. EXPECT_EQ(large_data, msg);
  21550. client.close();
  21551. }
  21552. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  21553. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21554. "/ws-echo");
  21555. ASSERT_TRUE(client.connect());
  21556. const int num_threads = 4;
  21557. std::vector<std::thread> threads;
  21558. std::atomic<int> send_count{0};
  21559. for (int t = 0; t < num_threads; t++) {
  21560. threads.emplace_back([&client, &send_count, t]() {
  21561. for (int i = 0; i < 5; i++) {
  21562. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  21563. if (client.send(text)) { send_count++; }
  21564. }
  21565. });
  21566. }
  21567. for (auto &th : threads) {
  21568. th.join();
  21569. }
  21570. int received = 0;
  21571. std::string msg;
  21572. while (received < send_count.load()) {
  21573. if (!client.read(msg)) { break; }
  21574. received++;
  21575. }
  21576. EXPECT_EQ(send_count.load(), received);
  21577. client.close();
  21578. }
  21579. TEST_F(WebSocketIntegrationTest, ReadString) {
  21580. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21581. "/ws-echo-string");
  21582. ASSERT_TRUE(client.connect());
  21583. ASSERT_TRUE(client.send("hello"));
  21584. std::string msg;
  21585. ASSERT_TRUE(client.read(msg));
  21586. EXPECT_EQ("echo: hello", msg);
  21587. ASSERT_TRUE(client.send("world"));
  21588. ASSERT_TRUE(client.read(msg));
  21589. EXPECT_EQ("echo: world", msg);
  21590. client.close();
  21591. }
  21592. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  21593. Headers headers = {{"X-Test-Header", "test-value"}};
  21594. ws::WebSocketClient client(
  21595. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  21596. ASSERT_TRUE(client.connect());
  21597. std::string msg;
  21598. ASSERT_TRUE(client.read(msg));
  21599. EXPECT_EQ("path:/ws-request-info", msg);
  21600. ASSERT_TRUE(client.read(msg));
  21601. EXPECT_EQ("header:test-value", msg);
  21602. client.close();
  21603. }
  21604. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  21605. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21606. "/ws-echo");
  21607. client.set_read_timeout(1, 0); // 1 second
  21608. ASSERT_TRUE(client.connect());
  21609. // Don't send anything — server echo handler waits for a message, so read()
  21610. // should time out. The connection survives it: nothing was consumed.
  21611. std::string msg;
  21612. EXPECT_EQ(client.read(msg), ws::Timeout);
  21613. EXPECT_TRUE(client.is_open());
  21614. // And it is still usable afterwards.
  21615. EXPECT_TRUE(client.send("after timeout"));
  21616. EXPECT_EQ(client.read(msg), ws::Text);
  21617. EXPECT_EQ(msg, "after timeout");
  21618. }
  21619. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  21620. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21621. "/ws-echo");
  21622. client.set_read_timeout(1, 0);
  21623. ASSERT_TRUE(client.connect());
  21624. ASSERT_TRUE(client.send("first"));
  21625. std::string msg;
  21626. ASSERT_EQ(client.read(msg), ws::Text);
  21627. ASSERT_EQ(msg, "first");
  21628. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  21629. // not be used with a read timeout: it would reprocess the previous message.
  21630. EXPECT_EQ(client.read(msg), ws::Timeout);
  21631. EXPECT_EQ(msg, "first");
  21632. }
  21633. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  21634. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21635. "/ws-echo");
  21636. ASSERT_TRUE(client.connect());
  21637. // Setting it once the connection is open reaches the live stream, not just
  21638. // the seed for the next connect().
  21639. client.set_read_timeout(1, 0);
  21640. std::string msg;
  21641. EXPECT_EQ(client.read(msg), ws::Timeout);
  21642. EXPECT_TRUE(client.is_open());
  21643. }
  21644. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  21645. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21646. "/ws-echo");
  21647. client.set_read_timeout(5, 0);
  21648. ASSERT_TRUE(client.connect());
  21649. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21650. // The server should reject it and close the connection.
  21651. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  21652. client.send(oversized);
  21653. // The server's read() should have failed due to payload limit,
  21654. // so our read() should return false (connection closed).
  21655. std::string msg;
  21656. EXPECT_FALSE(client.read(msg));
  21657. }
  21658. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  21659. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21660. "/ws-echo");
  21661. client.set_read_timeout(10, 0);
  21662. ASSERT_TRUE(client.connect());
  21663. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21664. // This should succeed.
  21665. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  21666. ASSERT_TRUE(client.send(at_limit));
  21667. std::string msg;
  21668. ASSERT_TRUE(client.read(msg));
  21669. EXPECT_EQ(at_limit.size(), msg.size());
  21670. client.close();
  21671. }
  21672. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  21673. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21674. "/nonexistent");
  21675. auto res = client.connect();
  21676. EXPECT_FALSE(res);
  21677. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21678. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  21679. EXPECT_FALSE(client.is_open());
  21680. }
  21681. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  21682. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21683. "/ws-echo");
  21684. ASSERT_TRUE(client.connect());
  21685. ASSERT_TRUE(client.send(""));
  21686. std::string msg;
  21687. EXPECT_EQ(ws::Text, client.read(msg));
  21688. EXPECT_EQ("", msg);
  21689. client.close();
  21690. }
  21691. TEST_F(WebSocketIntegrationTest, Reconnect) {
  21692. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21693. "/ws-echo");
  21694. // First connection
  21695. ASSERT_TRUE(client.connect());
  21696. ASSERT_TRUE(client.send("first"));
  21697. std::string msg;
  21698. ASSERT_TRUE(client.read(msg));
  21699. EXPECT_EQ("first", msg);
  21700. client.close();
  21701. EXPECT_FALSE(client.is_open());
  21702. // Reconnect using the same client object
  21703. ASSERT_TRUE(client.connect());
  21704. ASSERT_TRUE(client.is_open());
  21705. ASSERT_TRUE(client.send("second"));
  21706. ASSERT_TRUE(client.read(msg));
  21707. EXPECT_EQ("second", msg);
  21708. client.close();
  21709. }
  21710. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  21711. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21712. "/ws-close-status");
  21713. ASSERT_TRUE(client.connect());
  21714. // Trigger the server to close with GoingAway status
  21715. ASSERT_TRUE(client.send("trigger"));
  21716. // read() should return false after receiving the close frame
  21717. std::string msg;
  21718. EXPECT_FALSE(client.read(msg));
  21719. EXPECT_FALSE(client.is_open());
  21720. }
  21721. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  21722. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21723. "/ws-echo");
  21724. ASSERT_TRUE(client.connect());
  21725. client.close(ws::CloseStatus::GoingAway, "client leaving");
  21726. EXPECT_FALSE(client.is_open());
  21727. }
  21728. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  21729. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  21730. ws::WebSocketClient client(
  21731. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21732. ASSERT_TRUE(client.connect());
  21733. // Server should have selected graphql-ws
  21734. EXPECT_EQ("graphql-ws", client.subprotocol());
  21735. client.close();
  21736. }
  21737. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  21738. Headers headers;
  21739. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  21740. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  21741. ws::WebSocketClient client(
  21742. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21743. ASSERT_TRUE(client.connect());
  21744. // The offer on the second field line counts too, so graphql-ws is selected
  21745. EXPECT_EQ("graphql-ws", client.subprotocol());
  21746. client.close();
  21747. }
  21748. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  21749. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  21750. ws::WebSocketClient client(
  21751. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21752. ASSERT_TRUE(client.connect());
  21753. // Server should not have selected any subprotocol
  21754. EXPECT_TRUE(client.subprotocol().empty());
  21755. client.close();
  21756. }
  21757. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  21758. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21759. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21760. "/ws-subprotocol-unoffered",
  21761. headers);
  21762. ASSERT_TRUE(client.connect());
  21763. EXPECT_TRUE(client.subprotocol().empty());
  21764. client.close();
  21765. }
  21766. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21767. // Connect without requesting any subprotocol
  21768. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21769. "/ws-subprotocol");
  21770. ASSERT_TRUE(client.connect());
  21771. EXPECT_TRUE(client.subprotocol().empty());
  21772. client.close();
  21773. }
  21774. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21775. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21776. "/ws-echo");
  21777. client.set_tcp_nodelay(true);
  21778. client.set_connection_timeout(3, 0);
  21779. bool socket_options_called = false;
  21780. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21781. ASSERT_TRUE(client.connect());
  21782. ASSERT_TRUE(client.is_open());
  21783. EXPECT_TRUE(socket_options_called);
  21784. ASSERT_TRUE(client.send("hello"));
  21785. std::string msg;
  21786. auto result = client.read(msg);
  21787. EXPECT_EQ(result, ws::ReadResult::Text);
  21788. EXPECT_EQ(msg, "hello");
  21789. client.close();
  21790. }
  21791. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21792. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21793. "/ws-echo");
  21794. client.set_connection_timeout(std::chrono::seconds(3));
  21795. client.set_write_timeout(std::chrono::seconds(3));
  21796. // A sub-second remainder exercises the seconds/microseconds split.
  21797. client.set_read_timeout(std::chrono::milliseconds(1500));
  21798. ASSERT_TRUE(client.connect());
  21799. auto start = std::chrono::steady_clock::now();
  21800. std::string msg;
  21801. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21802. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21803. std::chrono::steady_clock::now() - start)
  21804. .count();
  21805. // Above 1s so that dropping the microseconds half of the split fails here.
  21806. // Ignoring the setter altogether would not reach this line at all: a client
  21807. // waits forever by default.
  21808. EXPECT_GE(elapsed, 1400);
  21809. EXPECT_LT(elapsed, 30000);
  21810. }
  21811. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21812. Server svr;
  21813. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21814. if (!req.has_header("Authorization")) {
  21815. res.status = StatusCode::Unauthorized_401;
  21816. res.set_content("Unauthorized", "text/plain");
  21817. return Server::HandlerResponse::Handled;
  21818. }
  21819. return Server::HandlerResponse::Unhandled;
  21820. });
  21821. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21822. std::string msg;
  21823. while (ws.read(msg)) {
  21824. ws.send(msg);
  21825. }
  21826. });
  21827. auto port = svr.bind_to_any_port("localhost");
  21828. std::thread t([&]() { svr.listen_after_bind(); });
  21829. svr.wait_until_ready();
  21830. // Without Authorization header - should be rejected before upgrade
  21831. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21832. EXPECT_FALSE(client1.connect());
  21833. // The rejection is framed like any other HTTP response
  21834. {
  21835. Client cli("localhost", port);
  21836. Headers headers = {{"Upgrade", "websocket"},
  21837. {"Connection", "Upgrade"},
  21838. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21839. {"Sec-WebSocket-Version", "13"}};
  21840. auto res = cli.Get("/ws", headers);
  21841. ASSERT_TRUE(res);
  21842. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21843. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21844. EXPECT_EQ("Unauthorized", res->body);
  21845. }
  21846. // With Authorization header - should succeed
  21847. Headers headers = {{"Authorization", "Bearer token123"}};
  21848. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21849. headers);
  21850. ASSERT_TRUE(client2.connect());
  21851. ASSERT_TRUE(client2.send("hello"));
  21852. std::string msg;
  21853. ASSERT_TRUE(client2.read(msg));
  21854. EXPECT_EQ("hello", msg);
  21855. client2.close();
  21856. svr.stop();
  21857. t.join();
  21858. }
  21859. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21860. Server svr;
  21861. std::atomic<int> pre_request_calls{0};
  21862. std::atomic<bool> route_matched{false};
  21863. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21864. pre_request_calls++;
  21865. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21866. if (req.get_header_value("Authorization") != "Bearer token123") {
  21867. res.status = StatusCode::Unauthorized_401;
  21868. res.set_content("Unauthorized", "text/plain");
  21869. return Server::HandlerResponse::Handled;
  21870. }
  21871. return Server::HandlerResponse::Unhandled;
  21872. });
  21873. std::atomic<bool> handler_called{false};
  21874. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21875. handler_called = true;
  21876. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21877. });
  21878. auto port = svr.bind_to_any_port("localhost");
  21879. std::thread t([&]() { svr.listen_after_bind(); });
  21880. svr.wait_until_ready();
  21881. // Without Authorization header - should be rejected before upgrade
  21882. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21883. "/ws/1");
  21884. EXPECT_FALSE(client1.connect());
  21885. EXPECT_FALSE(handler_called);
  21886. EXPECT_EQ(1, pre_request_calls);
  21887. EXPECT_TRUE(route_matched);
  21888. // The rejection is an ordinary HTTP response, not a protocol switch
  21889. {
  21890. Client cli("localhost", port);
  21891. Headers headers = {{"Upgrade", "websocket"},
  21892. {"Connection", "Upgrade"},
  21893. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21894. {"Sec-WebSocket-Version", "13"}};
  21895. auto res = cli.Get("/ws/1", headers);
  21896. ASSERT_TRUE(res);
  21897. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21898. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21899. EXPECT_EQ("Unauthorized", res->body);
  21900. }
  21901. EXPECT_FALSE(handler_called);
  21902. // With Authorization header - should succeed
  21903. Headers headers = {{"Authorization", "Bearer token123"}};
  21904. ws::WebSocketClient client2(
  21905. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  21906. ASSERT_TRUE(client2.connect());
  21907. std::string msg;
  21908. ASSERT_TRUE(client2.read(msg));
  21909. EXPECT_EQ("/ws/:id 2", msg);
  21910. EXPECT_TRUE(handler_called);
  21911. client2.close();
  21912. svr.stop();
  21913. t.join();
  21914. }
  21915. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  21916. Server svr;
  21917. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21918. // A read timeout is how a handler gets control back. Without it, a handler
  21919. // parked in read() can never write on the connection it is reading.
  21920. ws.set_read_timeout(std::chrono::milliseconds(100));
  21921. std::string msg;
  21922. while (ws.is_open()) {
  21923. auto r = ws.read(msg);
  21924. if (r == httplib::ws::Timeout) {
  21925. ws.send("tick");
  21926. continue;
  21927. }
  21928. if (r == httplib::ws::Fail) { break; }
  21929. ws.send(msg);
  21930. }
  21931. });
  21932. auto port = svr.bind_to_any_port("localhost");
  21933. std::thread t([&]() { svr.listen_after_bind(); });
  21934. svr.wait_until_ready();
  21935. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21936. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  21937. ASSERT_TRUE(client.connect());
  21938. // The client sends nothing, so anything it receives came out of the
  21939. // handler's timeout path.
  21940. std::string msg;
  21941. ASSERT_EQ(client.read(msg), ws::Text);
  21942. EXPECT_EQ("tick", msg);
  21943. client.close();
  21944. svr.stop();
  21945. t.join();
  21946. }
  21947. // Stream::read may return fewer bytes than asked for. This is that contract at
  21948. // its worst -- one byte per call -- which is what a frame header straddling a
  21949. // read buffer's boundary looks like to the frame parser.
  21950. class WsByteAtATimeStream : public Stream {
  21951. public:
  21952. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  21953. bool is_readable() const override { return true; }
  21954. bool wait_readable() const override { return true; }
  21955. bool wait_writable() const override { return true; }
  21956. ssize_t read(char *ptr, size_t size) override {
  21957. if (size == 0 || pos_ >= data_.size()) { return 0; }
  21958. *ptr = data_[pos_++];
  21959. return 1;
  21960. }
  21961. ssize_t write(const char *, size_t size) override {
  21962. return static_cast<ssize_t>(size);
  21963. }
  21964. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  21965. ip = "127.0.0.1";
  21966. port = 0;
  21967. }
  21968. void get_local_ip_and_port(std::string &ip, int &port) const override {
  21969. ip = "127.0.0.1";
  21970. port = 0;
  21971. }
  21972. socket_t socket() const override { return INVALID_SOCKET; }
  21973. time_t duration() const override { return 0; }
  21974. private:
  21975. std::string data_;
  21976. size_t pos_ = 0;
  21977. };
  21978. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  21979. // The payload uses the 16-bit extended length, so the header, the length
  21980. // and the mask key are all multi-byte fields here. Each used to be read
  21981. // with a single read() call, which fails as soon as one is split. The
  21982. // payload is also a little over one read chunk, so it is read in two.
  21983. std::string body;
  21984. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  21985. body += static_cast<char>(i % 251);
  21986. }
  21987. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  21988. std::string frame;
  21989. frame += static_cast<char>(0x81); // FIN + Text
  21990. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  21991. frame += static_cast<char>(body.size() >> 8);
  21992. frame += static_cast<char>(body.size() & 0xff);
  21993. for (size_t i = 0; i < 4; i++) {
  21994. frame += static_cast<char>(mask[i]);
  21995. }
  21996. for (size_t i = 0; i < body.size(); i++) {
  21997. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  21998. }
  21999. WsByteAtATimeStream strm(frame);
  22000. ws::Opcode opcode;
  22001. std::string payload;
  22002. bool fin = false;
  22003. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  22004. /*expect_masked=*/true, body.size()),
  22005. ws::impl::FrameRead::Ok);
  22006. EXPECT_TRUE(fin);
  22007. EXPECT_EQ(opcode, ws::Opcode::Text);
  22008. EXPECT_EQ(payload, body);
  22009. }
  22010. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  22011. std::string body(2000, 'x');
  22012. std::string frame;
  22013. frame += static_cast<char>(0x82); // FIN + Binary
  22014. frame += static_cast<char>(126); // 16-bit length follows
  22015. frame += static_cast<char>(body.size() >> 8);
  22016. frame += static_cast<char>(body.size() & 0xff);
  22017. frame += body;
  22018. detail::BufferStream strm;
  22019. strm.write(frame.data(), frame.size());
  22020. ws::Opcode opcode;
  22021. std::string payload;
  22022. bool fin;
  22023. EXPECT_EQ(
  22024. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  22025. ws::impl::FrameRead::Ok);
  22026. EXPECT_EQ(body, payload);
  22027. }
  22028. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  22029. // The header announces the largest payload allowed, and only 3 bytes of it
  22030. // ever arrive.
  22031. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  22032. std::string frame;
  22033. frame += static_cast<char>(0x82); // FIN + Binary
  22034. frame += static_cast<char>(127); // 64-bit length follows
  22035. for (int shift = 56; shift >= 0; shift -= 8) {
  22036. frame += static_cast<char>((len >> shift) & 0xff);
  22037. }
  22038. frame += "abc";
  22039. detail::BufferStream strm;
  22040. strm.write(frame.data(), frame.size());
  22041. ws::Opcode opcode;
  22042. std::string payload;
  22043. bool fin;
  22044. EXPECT_EQ(
  22045. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  22046. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  22047. ws::impl::FrameRead::Fail);
  22048. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  22049. }
  22050. TEST(WebSocketTest, QueryStringInHandshake) {
  22051. Server svr;
  22052. std::mutex mtx;
  22053. std::string received_target;
  22054. std::string received_token;
  22055. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22056. {
  22057. std::lock_guard<std::mutex> lock(mtx);
  22058. received_target = req.target;
  22059. if (req.has_param("token")) {
  22060. received_token = req.get_param_value("token");
  22061. }
  22062. }
  22063. std::string msg;
  22064. while (ws.read(msg)) {
  22065. ws.send(msg);
  22066. }
  22067. });
  22068. auto port = svr.bind_to_any_port("localhost");
  22069. std::thread t([&]() { svr.listen_after_bind(); });
  22070. svr.wait_until_ready();
  22071. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  22072. "/ws?token=ABC&session=123");
  22073. ASSERT_TRUE(client.connect());
  22074. // Round-trip ensures the handler has run and captured the request.
  22075. ASSERT_TRUE(client.send("hello"));
  22076. std::string msg;
  22077. ASSERT_TRUE(client.read(msg));
  22078. EXPECT_EQ("hello", msg);
  22079. client.close();
  22080. {
  22081. std::lock_guard<std::mutex> lock(mtx);
  22082. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  22083. EXPECT_EQ("ABC", received_token);
  22084. }
  22085. svr.stop();
  22086. t.join();
  22087. }
  22088. // Run a handshake against a throwaway server and hand the request the server
  22089. // received back to the caller, so tests can assert on the headers the client
  22090. // actually put on the wire.
  22091. static void capture_websocket_handshake_request(
  22092. const Headers &client_headers,
  22093. std::function<void(const Request &, int port)> verify) {
  22094. Server svr;
  22095. std::mutex mtx;
  22096. Request received;
  22097. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22098. {
  22099. std::lock_guard<std::mutex> lock(mtx);
  22100. received = req;
  22101. }
  22102. std::string msg;
  22103. while (ws.read(msg)) {
  22104. ws.send(msg);
  22105. }
  22106. });
  22107. auto port = svr.bind_to_any_port("localhost");
  22108. std::thread t([&]() { svr.listen_after_bind(); });
  22109. auto se = detail::scope_exit([&] {
  22110. svr.stop();
  22111. t.join();
  22112. });
  22113. svr.wait_until_ready();
  22114. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  22115. client_headers);
  22116. ASSERT_TRUE(client.connect());
  22117. ASSERT_TRUE(client.send("hello"));
  22118. std::string msg;
  22119. ASSERT_TRUE(client.read(msg));
  22120. client.close();
  22121. {
  22122. std::lock_guard<std::mutex> lock(mtx);
  22123. verify(received, port);
  22124. }
  22125. }
  22126. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  22127. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  22128. // Non-default port must be present in the Host header. Default ports
  22129. // (80/443) are omitted; that logic is covered by
  22130. // MakeHostAndPortStringTest.
  22131. EXPECT_EQ("localhost:" + std::to_string(port),
  22132. req.get_header_value("Host"));
  22133. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  22134. req.get_header_value("User-Agent"));
  22135. EXPECT_FALSE(req.has_header("Accept"));
  22136. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  22137. EXPECT_FALSE(req.has_header("Content-Length"));
  22138. });
  22139. }
  22140. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  22141. capture_websocket_handshake_request(
  22142. {{"Host", "example.com"},
  22143. {"User-Agent", "custom-agent"},
  22144. {"X-Custom", "value"}},
  22145. [](const Request &req, int) {
  22146. EXPECT_EQ("example.com", req.get_header_value("Host"));
  22147. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  22148. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  22149. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  22150. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  22151. });
  22152. }
  22153. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  22154. capture_websocket_handshake_request(
  22155. {{"Upgrade", "bogus"},
  22156. {"Connection", "close"},
  22157. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  22158. {"Sec-WebSocket-Version", "8"}},
  22159. [](const Request &req, int) {
  22160. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  22161. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  22162. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  22163. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  22164. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  22165. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  22166. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  22167. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  22168. req.get_header_value("Sec-WebSocket-Key"));
  22169. });
  22170. }
  22171. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  22172. // A header the client refuses to send must abort the handshake before any
  22173. // part of it reaches the wire; a lone request line would otherwise sit in
  22174. // the peer's buffer as a truncated request.
  22175. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  22176. ASSERT_NE(INVALID_SOCKET, srv);
  22177. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  22178. sockaddr_in addr{};
  22179. addr.sin_family = AF_INET;
  22180. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  22181. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22182. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  22183. ASSERT_EQ(0, ::listen(srv, 1));
  22184. sockaddr_in bound{};
  22185. socklen_t bound_len = sizeof(bound);
  22186. ASSERT_EQ(
  22187. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  22188. auto port = ntohs(bound.sin_port);
  22189. ssize_t received = -1;
  22190. std::thread t([&] {
  22191. // Bound every blocking call so a regression fails the test with a bad
  22192. // value instead of hanging the suite.
  22193. fd_set rfds;
  22194. FD_ZERO(&rfds);
  22195. FD_SET(srv, &rfds);
  22196. timeval tv{5, 0};
  22197. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  22198. 0) {
  22199. return;
  22200. }
  22201. sockaddr_in cli_addr{};
  22202. socklen_t cli_len = sizeof(cli_addr);
  22203. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  22204. if (cli == INVALID_SOCKET) { return; }
  22205. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  22206. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22207. char buf[4096];
  22208. received = ::recv(cli, buf, sizeof(buf), 0);
  22209. });
  22210. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  22211. // connect() has already shut the socket down by the time it returns false,
  22212. // so the peer sees EOF without waiting for the client to be destroyed.
  22213. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  22214. {{"X-Bad", "a\r\nInjected: 1"}});
  22215. EXPECT_FALSE(client.connect());
  22216. t.join();
  22217. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  22218. EXPECT_EQ(0, received);
  22219. }
  22220. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  22221. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  22222. // contains "upgrade" as a substring is a different token and must not
  22223. // start a WebSocket handshake.
  22224. auto make_request = [](const std::vector<std::string> &connection_values) {
  22225. Request req;
  22226. req.method = "GET";
  22227. req.headers.emplace("Upgrade", "websocket");
  22228. for (const auto &value : connection_values) {
  22229. req.headers.emplace("Connection", value);
  22230. }
  22231. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22232. req.headers.emplace("Sec-WebSocket-Version", "13");
  22233. return req;
  22234. };
  22235. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  22236. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  22237. EXPECT_TRUE(
  22238. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  22239. EXPECT_TRUE(
  22240. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  22241. EXPECT_TRUE(
  22242. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  22243. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  22244. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  22245. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  22246. EXPECT_FALSE(
  22247. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  22248. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  22249. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22250. }
  22251. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  22252. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  22253. // asks recipients to match each protocol-name case-insensitively, and RFC
  22254. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  22255. // client naming websocket alongside another protocol, or on a second field
  22256. // line, is offering websocket; a value that merely contains "websocket" as a
  22257. // substring is a different protocol name and is not.
  22258. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  22259. Request req;
  22260. req.method = "GET";
  22261. for (const auto &value : upgrade_values) {
  22262. req.headers.emplace("Upgrade", value);
  22263. }
  22264. req.headers.emplace("Connection", "Upgrade");
  22265. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22266. req.headers.emplace("Sec-WebSocket-Version", "13");
  22267. return req;
  22268. };
  22269. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  22270. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  22271. EXPECT_TRUE(
  22272. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  22273. EXPECT_TRUE(
  22274. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  22275. EXPECT_TRUE(
  22276. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  22277. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  22278. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  22279. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  22280. EXPECT_FALSE(
  22281. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  22282. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  22283. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22284. }
  22285. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  22286. Server svr;
  22287. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  22288. auto port = svr.bind_to_any_port("localhost");
  22289. std::thread t([&]() { svr.listen_after_bind(); });
  22290. auto se = detail::scope_exit([&] {
  22291. svr.stop();
  22292. t.join();
  22293. });
  22294. svr.wait_until_ready();
  22295. Headers headers = {{"Upgrade", "websocket"},
  22296. {"Connection", "notupgrade"},
  22297. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22298. {"Sec-WebSocket-Version", "13"}};
  22299. Client cli("localhost", port);
  22300. auto res = cli.Get("/ws", headers);
  22301. // The route exists only as a WebSocket route, so a request that fails the
  22302. // handshake check falls through to ordinary routing.
  22303. ASSERT_TRUE(res);
  22304. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  22305. }
  22306. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  22307. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  22308. // Connection value is the only thing left for the client to reject.
  22309. Server svr;
  22310. svr.Get("/ws", [](const Request &req, Response &res) {
  22311. res.status = StatusCode::SwitchingProtocol_101;
  22312. res.set_header("Upgrade", "websocket");
  22313. res.set_header("Connection", "notupgrade");
  22314. res.set_header("Sec-WebSocket-Accept",
  22315. detail::websocket_accept_key(
  22316. req.get_header_value("Sec-WebSocket-Key")));
  22317. });
  22318. auto port = svr.bind_to_any_port("localhost");
  22319. std::thread t([&]() { svr.listen_after_bind(); });
  22320. auto se = detail::scope_exit([&] {
  22321. svr.stop();
  22322. t.join();
  22323. });
  22324. svr.wait_until_ready();
  22325. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22326. auto res = client.connect();
  22327. EXPECT_FALSE(res);
  22328. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22329. EXPECT_FALSE(client.is_open());
  22330. }
  22331. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  22332. Server svr;
  22333. svr.Get("/ws", [](const Request &req, Response &res) {
  22334. res.status = StatusCode::SwitchingProtocol_101;
  22335. res.set_header("Upgrade", "websocket");
  22336. res.set_header("Connection", "Upgrade");
  22337. res.set_header("Sec-WebSocket-Accept",
  22338. detail::websocket_accept_key(
  22339. req.get_header_value("Sec-WebSocket-Key")));
  22340. res.set_header("Sec-WebSocket-Protocol", "admin");
  22341. });
  22342. auto port = svr.bind_to_any_port("localhost");
  22343. std::thread t([&]() { svr.listen_after_bind(); });
  22344. auto se = detail::scope_exit([&] {
  22345. svr.stop();
  22346. t.join();
  22347. });
  22348. svr.wait_until_ready();
  22349. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  22350. // Server selects a subprotocol the client never offered
  22351. {
  22352. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22353. ws::WebSocketClient client(url, headers);
  22354. auto res = client.connect();
  22355. EXPECT_FALSE(res);
  22356. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22357. EXPECT_FALSE(client.is_open());
  22358. EXPECT_TRUE(client.subprotocol().empty());
  22359. }
  22360. // Client offered none but the server named one anyway
  22361. {
  22362. ws::WebSocketClient client(url);
  22363. auto res = client.connect();
  22364. EXPECT_FALSE(res);
  22365. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22366. EXPECT_FALSE(client.is_open());
  22367. EXPECT_TRUE(client.subprotocol().empty());
  22368. }
  22369. }
  22370. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  22371. // The socket path doubles as the URL host, so it must not contain '/'.
  22372. const char *shard = getenv("GTEST_SHARD_INDEX");
  22373. const std::string sock_path =
  22374. shard ? std::string("httplib-ws-") + shard + ".sock"
  22375. : std::string("httplib-ws.sock");
  22376. std::remove(sock_path.c_str());
  22377. Server svr;
  22378. std::mutex mtx;
  22379. std::string received_host;
  22380. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22381. {
  22382. std::lock_guard<std::mutex> lock(mtx);
  22383. received_host = req.get_header_value("Host");
  22384. }
  22385. std::string msg;
  22386. while (ws.read(msg)) {
  22387. ws.send(msg);
  22388. }
  22389. });
  22390. svr.set_address_family(AF_UNIX);
  22391. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  22392. auto se = detail::scope_exit([&] {
  22393. svr.stop();
  22394. t.join();
  22395. std::remove(sock_path.c_str());
  22396. });
  22397. svr.wait_until_ready();
  22398. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  22399. client.set_address_family(AF_UNIX);
  22400. ASSERT_TRUE(client.connect());
  22401. ASSERT_TRUE(client.send("hello"));
  22402. std::string msg;
  22403. ASSERT_TRUE(client.read(msg));
  22404. client.close();
  22405. {
  22406. std::lock_guard<std::mutex> lock(mtx);
  22407. // There is no host:port for a Unix socket, so the same "localhost"
  22408. // placeholder the HTTP client uses is expected.
  22409. EXPECT_EQ("localhost", received_host);
  22410. }
  22411. }
  22412. // Two threads must never parse WebSocket frames from the same stream.
  22413. // close() used to read the peer's Close reply with its own frame read, so it
  22414. // raced a reader thread that was in the middle of a payload: the payload loop
  22415. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  22416. // so bytes taken by close() were replaced with bytes from further along the
  22417. // stream. The message kept its length and silently changed content.
  22418. //
  22419. // The raw peer below sends a frame header plus part of the payload, waits for
  22420. // the handler to call close(), and only then sends the rest. Whichever thread
  22421. // would win the race for those bytes, the message must arrive intact, because
  22422. // close() must not touch the stream while read() owns it.
  22423. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  22424. #ifndef _WIN32
  22425. signal(SIGPIPE, SIG_IGN);
  22426. #endif
  22427. const size_t payload_len = 120; // fits the 7-bit length field
  22428. const size_t prefix_len = 8;
  22429. const int attempts = 8;
  22430. std::string expected(payload_len, '\0');
  22431. for (size_t i = 0; i < payload_len; i++) {
  22432. expected[i] = static_cast<char>('a' + i % 26);
  22433. }
  22434. std::atomic<bool> peer_stalled{false};
  22435. std::atomic<bool> handler_done{false};
  22436. std::mutex received_mutex;
  22437. std::vector<std::string> received;
  22438. // Bound every wait, so a regression fails the test instead of hanging the
  22439. // suite.
  22440. auto wait_for = [](const std::atomic<bool> &flag) {
  22441. for (int i = 0; i < 500 && !flag; i++) {
  22442. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22443. }
  22444. };
  22445. Server svr;
  22446. svr.set_websocket_ping_interval(0);
  22447. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22448. std::thread reader([&]() {
  22449. std::string msg;
  22450. while (ws.read(msg)) {
  22451. std::lock_guard<std::mutex> guard(received_mutex);
  22452. received.push_back(msg);
  22453. }
  22454. });
  22455. // Wait until the peer stalls mid-payload, so the reader thread is parked
  22456. // inside read_websocket_frame() when close() runs.
  22457. wait_for(peer_stalled);
  22458. ws.close();
  22459. reader.join();
  22460. handler_done = true;
  22461. });
  22462. auto port = svr.bind_to_any_port("127.0.0.1");
  22463. std::thread t([&]() { svr.listen_after_bind(); });
  22464. auto se = detail::scope_exit([&] {
  22465. svr.stop();
  22466. t.join();
  22467. });
  22468. svr.wait_until_ready();
  22469. auto send_bytes = [](socket_t s, const std::string &data) {
  22470. #ifdef _WIN32
  22471. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  22472. #else
  22473. auto n = ::send(s, data.data(), data.size(), 0);
  22474. #endif
  22475. return n == static_cast<decltype(n)>(data.size());
  22476. };
  22477. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  22478. // Every length used here fits the 7-bit length field.
  22479. auto masked_header = [](uint8_t first_byte, size_t len) {
  22480. std::string h;
  22481. h += static_cast<char>(first_byte);
  22482. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  22483. h.append(4, '\0'); // mask key
  22484. return h;
  22485. };
  22486. for (int attempt = 0; attempt < attempts; attempt++) {
  22487. peer_stalled = false;
  22488. handler_done = false;
  22489. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22490. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  22491. auto se_sock = detail::scope_exit([&] {
  22492. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  22493. });
  22494. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22495. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  22496. sockaddr_in addr{};
  22497. addr.sin_family = AF_INET;
  22498. addr.sin_port = htons(static_cast<uint16_t>(port));
  22499. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22500. ASSERT_EQ(
  22501. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  22502. << "attempt " << attempt;
  22503. ASSERT_TRUE(send_bytes(sock,
  22504. "GET /ws HTTP/1.1\r\n"
  22505. "Host: 127.0.0.1\r\n"
  22506. "Upgrade: websocket\r\n"
  22507. "Connection: Upgrade\r\n"
  22508. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22509. "Sec-WebSocket-Version: 13\r\n"
  22510. "\r\n"))
  22511. << "attempt " << attempt;
  22512. std::string response;
  22513. while (response.find("\r\n\r\n") == std::string::npos) {
  22514. char buf[512];
  22515. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  22516. if (n <= 0) { break; }
  22517. response.append(buf, static_cast<size_t>(n));
  22518. }
  22519. ASSERT_NE(std::string::npos, response.find(" 101 "))
  22520. << "attempt " << attempt;
  22521. // Send the header of a Binary message but only the first prefix_len bytes
  22522. // of its payload, leaving the reader thread stalled inside the payload.
  22523. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  22524. expected.substr(0, prefix_len)))
  22525. << "attempt " << attempt;
  22526. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22527. peer_stalled = true;
  22528. // Let close() send its Close frame and park in its own read before the
  22529. // rest of the payload arrives, so both threads are waiting for it.
  22530. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22531. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  22532. close_frame += static_cast<char>(0x03); // status 1000
  22533. close_frame += static_cast<char>(0xE8);
  22534. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  22535. << "attempt " << attempt;
  22536. // Closing the peer releases the reader thread even on the buggy path,
  22537. // where it waits for bytes another thread already consumed.
  22538. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22539. detail::close_socket(sock);
  22540. sock = INVALID_SOCKET;
  22541. wait_for(handler_done);
  22542. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  22543. }
  22544. std::lock_guard<std::mutex> guard(received_mutex);
  22545. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  22546. << "a message in flight when close() ran was dropped";
  22547. for (size_t i = 0; i < received.size(); i++) {
  22548. EXPECT_EQ(expected, received[i]) << "message " << i;
  22549. }
  22550. }
  22551. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  22552. // returning the socket, or INVALID_SOCKET.
  22553. static socket_t connect_raw_websocket(int port, const std::string &path) {
  22554. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22555. if (sock == INVALID_SOCKET) { return sock; }
  22556. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22557. sockaddr_in addr{};
  22558. addr.sin_family = AF_INET;
  22559. addr.sin_port = htons(static_cast<uint16_t>(port));
  22560. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22561. std::string req = "GET " + path +
  22562. " HTTP/1.1\r\n"
  22563. "Host: 127.0.0.1\r\n"
  22564. "Upgrade: websocket\r\n"
  22565. "Connection: Upgrade\r\n"
  22566. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22567. "Sec-WebSocket-Version: 13\r\n"
  22568. "\r\n";
  22569. std::string res;
  22570. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  22571. ::send(sock, req.data(), static_cast<int>(req.size()), 0) ==
  22572. static_cast<int>(req.size())) {
  22573. char c;
  22574. while (res.find("\r\n\r\n") == std::string::npos &&
  22575. ::recv(sock, &c, 1, 0) == 1) {
  22576. res += c;
  22577. }
  22578. }
  22579. if (res.find(" 101 ") == std::string::npos) {
  22580. detail::close_socket(sock);
  22581. return INVALID_SOCKET;
  22582. }
  22583. return sock;
  22584. }
  22585. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  22586. // The payload must fit the 7-bit length field.
  22587. static std::string masked_frame(uint8_t first_byte,
  22588. const std::string &payload) {
  22589. std::string f;
  22590. f += static_cast<char>(first_byte);
  22591. f += static_cast<char>(0x80 | payload.size());
  22592. f.append(4, '\0');
  22593. return f + payload;
  22594. }
  22595. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  22596. std::atomic<bool> done{false};
  22597. std::string received;
  22598. Server svr;
  22599. svr.set_websocket_ping_interval(0);
  22600. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22601. std::string msg;
  22602. if (ws.read(msg) == ws::Binary) { received = msg; }
  22603. done = true;
  22604. });
  22605. auto port = svr.bind_to_any_port("127.0.0.1");
  22606. std::thread t([&]() { svr.listen_after_bind(); });
  22607. auto se = detail::scope_exit([&] {
  22608. svr.stop();
  22609. t.join();
  22610. });
  22611. svr.wait_until_ready();
  22612. auto sock = connect_raw_websocket(port, "/ws");
  22613. ASSERT_NE(INVALID_SOCKET, sock);
  22614. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  22615. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  22616. masked_frame(0x89, "p") + // FIN + Ping
  22617. masked_frame(0x80, "lo"); // FIN + Continuation
  22618. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  22619. for (int i = 0; i < 500 && !done; i++) {
  22620. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22621. }
  22622. ASSERT_TRUE(done);
  22623. EXPECT_EQ("Hello", received);
  22624. }
  22625. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  22626. Server svr;
  22627. svr.set_websocket_ping_interval(0);
  22628. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22629. std::string msg;
  22630. while (ws.read(msg)) {}
  22631. });
  22632. auto port = svr.bind_to_any_port("127.0.0.1");
  22633. std::thread t([&]() { svr.listen_after_bind(); });
  22634. auto se = detail::scope_exit([&] {
  22635. svr.stop();
  22636. t.join();
  22637. });
  22638. svr.wait_until_ready();
  22639. // The Close each payload is answered with: an echo when it is valid, and
  22640. // 1002 otherwise.
  22641. std::vector<std::pair<std::string, std::string>> cases = {
  22642. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  22643. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  22644. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  22645. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  22646. };
  22647. for (const auto &c : cases) {
  22648. auto sock = connect_raw_websocket(port, "/ws");
  22649. ASSERT_NE(INVALID_SOCKET, sock);
  22650. auto close_frame = masked_frame(0x88, c.first);
  22651. ::send(sock, close_frame.data(), static_cast<int>(close_frame.size()), 0);
  22652. std::string reply;
  22653. char buf[256];
  22654. while (reply.size() < 2 + c.second.size()) {
  22655. auto n = ::recv(sock, buf, sizeof(buf), 0);
  22656. if (n <= 0) { break; }
  22657. reply.append(buf, static_cast<size_t>(n));
  22658. }
  22659. detail::close_socket(sock);
  22660. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  22661. c.second,
  22662. reply);
  22663. }
  22664. }
  22665. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22666. class WebSocketSSLIntegrationTest : public ::testing::Test {
  22667. protected:
  22668. void SetUp() override {
  22669. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  22670. SERVER_PRIVATE_KEY_FILE);
  22671. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22672. std::string msg;
  22673. ws::ReadResult ret;
  22674. while ((ret = ws.read(msg))) {
  22675. if (ret == ws::Binary) {
  22676. ws.send(msg.data(), msg.size());
  22677. } else {
  22678. ws.send(msg);
  22679. }
  22680. }
  22681. });
  22682. port_ = server_->bind_to_any_port(HOST);
  22683. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22684. server_->wait_until_ready();
  22685. }
  22686. void TearDown() override {
  22687. server_->stop();
  22688. if (server_thread_.joinable()) { server_thread_.join(); }
  22689. }
  22690. std::unique_ptr<SSLServer> server_;
  22691. std::thread server_thread_;
  22692. int port_ = 0;
  22693. };
  22694. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  22695. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22696. "/ws-echo");
  22697. client.enable_server_certificate_verification(false);
  22698. ASSERT_TRUE(client.connect());
  22699. ASSERT_TRUE(client.is_open());
  22700. ASSERT_TRUE(client.send("Hello WSS"));
  22701. std::string msg;
  22702. EXPECT_EQ(ws::Text, client.read(msg));
  22703. EXPECT_EQ("Hello WSS", msg);
  22704. client.close();
  22705. }
  22706. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  22707. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  22708. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  22709. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  22710. // client (without calling close() first) is the only path that runs
  22711. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  22712. // bug exactly.
  22713. //
  22714. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  22715. // when linked against an instrumented libssl; run under Valgrind to catch it
  22716. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  22717. // suite (the freed session otherwise stalls on the close handshake) — this test
  22718. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  22719. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  22720. {
  22721. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22722. "/ws-echo");
  22723. client.enable_server_certificate_verification(false);
  22724. client.set_read_timeout(2, 0);
  22725. client.set_write_timeout(2, 0);
  22726. ASSERT_TRUE(client.connect());
  22727. ASSERT_TRUE(client.is_open());
  22728. ASSERT_TRUE(client.send("still open"));
  22729. // Intentionally do NOT call client.close(): leaving scope runs
  22730. // shutdown_and_close() with the WebSocket still open, which must send the
  22731. // close frame while the TLS session is still alive.
  22732. }
  22733. }
  22734. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  22735. // shutdown_and_close() at the start of connect(), reproducing the same
  22736. // use-after-free within the test body rather than at scope exit. The second
  22737. // connect must succeed and echo, proving the close handshake ran over a live
  22738. // session. See the note above about memory-tool requirements.
  22739. TEST_F(WebSocketSSLIntegrationTest,
  22740. ReconnectWhileOpenSendsCloseOverLiveSession) {
  22741. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22742. "/ws-echo");
  22743. client.enable_server_certificate_verification(false);
  22744. client.set_read_timeout(2, 0);
  22745. client.set_write_timeout(2, 0);
  22746. ASSERT_TRUE(client.connect());
  22747. ASSERT_TRUE(client.is_open());
  22748. ASSERT_TRUE(client.send("still open"));
  22749. // Reconnect without closing first: connect() calls shutdown_and_close() on
  22750. // the still-open connection, which must not touch a freed TLS session.
  22751. ASSERT_TRUE(client.connect());
  22752. ASSERT_TRUE(client.is_open());
  22753. ASSERT_TRUE(client.send("after reconnect"));
  22754. std::string msg;
  22755. EXPECT_EQ(ws::Text, client.read(msg));
  22756. EXPECT_EQ("after reconnect", msg);
  22757. client.close();
  22758. }
  22759. #endif
  22760. #ifdef CPPHTTPLIB_SSL_ENABLED
  22761. class WebSocketSSLCATest : public ::testing::Test {
  22762. protected:
  22763. void SetUp() override {
  22764. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  22765. SERVER_PRIVATE_KEY_FILE);
  22766. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22767. std::string msg;
  22768. while (ws.read(msg)) {
  22769. ws.send(msg);
  22770. }
  22771. });
  22772. port_ = server_->bind_to_any_port("127.0.0.1");
  22773. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22774. server_->wait_until_ready();
  22775. }
  22776. void TearDown() override {
  22777. server_->stop();
  22778. if (server_thread_.joinable()) { server_thread_.join(); }
  22779. }
  22780. std::string url() const {
  22781. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  22782. }
  22783. std::unique_ptr<SSLServer> server_;
  22784. std::thread server_thread_;
  22785. int port_ = 0;
  22786. };
  22787. // A custom CA loaded as PEM verifies the server with full certificate
  22788. // verification enabled
  22789. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  22790. ws::WebSocketClient client(url());
  22791. std::string cert;
  22792. read_file(SERVER_CERT2_FILE, cert);
  22793. client.load_ca_cert_store(cert.c_str(), cert.size());
  22794. ASSERT_TRUE(client.connect());
  22795. ASSERT_TRUE(client.send("hello"));
  22796. std::string msg;
  22797. EXPECT_EQ(ws::Text, client.read(msg));
  22798. EXPECT_EQ("hello", msg);
  22799. client.close();
  22800. }
  22801. // A custom CA that does not cover the server must fail verification (the
  22802. // custom CA is exclusive; system certs are not loaded alongside it)
  22803. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  22804. ws::WebSocketClient client(url());
  22805. std::string cert;
  22806. read_file(CLIENT_CA_CERT_FILE, cert);
  22807. client.load_ca_cert_store(cert.c_str(), cert.size());
  22808. auto res = client.connect();
  22809. ASSERT_FALSE(res);
  22810. EXPECT_EQ(Error::SSLServerVerification, res.error());
  22811. EXPECT_EQ(-1, res.status());
  22812. EXPECT_NE(0u, res.ssl_backend_error());
  22813. }
  22814. // The same CA as a file path rather than PEM in memory
  22815. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  22816. ws::WebSocketClient client(url());
  22817. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22818. ASSERT_TRUE(client.connect());
  22819. ASSERT_TRUE(client.send("hello"));
  22820. std::string msg;
  22821. EXPECT_EQ(ws::Text, client.read(msg));
  22822. EXPECT_EQ("hello", msg);
  22823. client.close();
  22824. }
  22825. // ...and a CA file that does not cover the server still fails, so it is the
  22826. // path above that decides the outcome
  22827. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  22828. ws::WebSocketClient client(url());
  22829. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22830. ASSERT_FALSE(client.connect());
  22831. }
  22832. // Regression test: reconnecting with a native custom CA store used to reuse
  22833. // a store handle the previous TLS context had already freed (use-after-free
  22834. // under the OpenSSL backend). The context now lives as long as the client.
  22835. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  22836. ws::WebSocketClient client(url());
  22837. std::string cert;
  22838. read_file(SERVER_CERT2_FILE, cert);
  22839. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  22840. ASSERT_TRUE(client.connect());
  22841. client.close();
  22842. ASSERT_TRUE(client.connect());
  22843. ASSERT_TRUE(client.send("again"));
  22844. std::string msg;
  22845. EXPECT_EQ(ws::Text, client.read(msg));
  22846. EXPECT_EQ("again", msg);
  22847. client.close();
  22848. }
  22849. // Regression test: a certificate with a trusted chain but no identity match
  22850. // for the server IP must be rejected. The Mbed TLS backend used to skip
  22851. // verification entirely for IP hosts, so this connection succeeded there.
  22852. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  22853. // chain verification while the identity check must still fail.
  22854. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  22855. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22856. ASSERT_TRUE(svr.is_valid());
  22857. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22858. std::string msg;
  22859. while (ws.read(msg)) {
  22860. ws.send(msg);
  22861. }
  22862. });
  22863. auto port = svr.bind_to_any_port("127.0.0.1");
  22864. auto t = std::thread([&]() { svr.listen_after_bind(); });
  22865. auto se = detail::scope_exit([&] {
  22866. svr.stop();
  22867. t.join();
  22868. });
  22869. svr.wait_until_ready();
  22870. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  22871. "/echo");
  22872. std::string cert;
  22873. read_file(SERVER_CERT_FILE, cert);
  22874. client.load_ca_cert_store(cert.c_str(), cert.size());
  22875. ASSERT_FALSE(client.connect());
  22876. }
  22877. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  22878. // SNI, so nothing binds the host name to the TLS session. These bind the
  22879. // server to "localhost" instead, the only shape that exercises the SNI and
  22880. // hostname-verification path with certificate verification left enabled.
  22881. class WebSocketSSLDnsHostTest : public ::testing::Test {
  22882. protected:
  22883. void Start(const char *cert_file) {
  22884. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  22885. SERVER_PRIVATE_KEY_FILE);
  22886. ASSERT_TRUE(server_->is_valid());
  22887. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22888. std::string msg;
  22889. while (ws.read(msg)) {
  22890. ws.send(msg);
  22891. }
  22892. });
  22893. port_ = server_->bind_to_any_port("localhost");
  22894. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22895. server_->wait_until_ready();
  22896. }
  22897. void TearDown() override {
  22898. if (server_) { server_->stop(); }
  22899. if (server_thread_.joinable()) { server_thread_.join(); }
  22900. }
  22901. std::string url() const {
  22902. return "wss://localhost:" + std::to_string(port_) + "/echo";
  22903. }
  22904. std::unique_ptr<SSLServer> server_;
  22905. std::thread server_thread_;
  22906. int port_ = 0;
  22907. };
  22908. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  22909. // out and the connection is usable
  22910. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  22911. Start(SERVER_CERT2_FILE);
  22912. ws::WebSocketClient client(url());
  22913. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22914. ASSERT_TRUE(client.connect());
  22915. ASSERT_TRUE(client.send("hello"));
  22916. std::string msg;
  22917. EXPECT_EQ(ws::Text, client.read(msg));
  22918. EXPECT_EQ("hello", msg);
  22919. client.close();
  22920. }
  22921. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  22922. // while the identity check must still reject "localhost"
  22923. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  22924. Start(SERVER_CERT_FILE);
  22925. ws::WebSocketClient client(url());
  22926. client.set_ca_cert_path(SERVER_CERT_FILE);
  22927. auto res = client.connect();
  22928. ASSERT_FALSE(res);
  22929. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  22930. EXPECT_EQ(-1, res.status());
  22931. }
  22932. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  22933. // disabled: the chain is still checked, only the identity check is skipped
  22934. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  22935. Start(SERVER_CERT_FILE);
  22936. ws::WebSocketClient client(url());
  22937. client.set_ca_cert_path(SERVER_CERT_FILE);
  22938. client.enable_server_hostname_verification(false);
  22939. ASSERT_TRUE(client.connect());
  22940. ASSERT_TRUE(client.send("hello"));
  22941. std::string msg;
  22942. EXPECT_EQ(ws::Text, client.read(msg));
  22943. EXPECT_EQ("hello", msg);
  22944. client.close();
  22945. }
  22946. // A CA that did not sign the server certificate fails the chain, even though
  22947. // the name would match
  22948. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  22949. Start(SERVER_CERT2_FILE);
  22950. ws::WebSocketClient client(url());
  22951. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22952. ASSERT_FALSE(client.connect());
  22953. }
  22954. // With verification disabled, neither the chain nor the name is checked
  22955. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  22956. Start(SERVER_CERT_FILE);
  22957. ws::WebSocketClient client(url());
  22958. client.enable_server_certificate_verification(false);
  22959. ASSERT_TRUE(client.connect());
  22960. ASSERT_TRUE(client.send("hello"));
  22961. std::string msg;
  22962. EXPECT_EQ(ws::Text, client.read(msg));
  22963. EXPECT_EQ("hello", msg);
  22964. client.close();
  22965. }
  22966. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  22967. protected:
  22968. void SetUp() override {
  22969. server_ = httplib::detail::make_unique<SSLServer>(
  22970. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22971. ASSERT_TRUE(server_->is_valid());
  22972. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22973. std::string msg;
  22974. while (ws.read(msg)) {
  22975. ws.send(msg);
  22976. }
  22977. });
  22978. port_ = server_->bind_to_any_port("localhost");
  22979. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22980. server_->wait_until_ready();
  22981. }
  22982. void TearDown() override {
  22983. server_->stop();
  22984. if (server_thread_.joinable()) { server_thread_.join(); }
  22985. }
  22986. std::string url() const {
  22987. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22988. }
  22989. void ConnectWithClientCert(const std::string &client_cert_file,
  22990. const std::string &client_private_key_file,
  22991. const char *private_key_password) {
  22992. std::string cert_pem, key_pem;
  22993. read_file(client_cert_file, cert_pem);
  22994. read_file(client_private_key_file, key_pem);
  22995. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  22996. key_pem.c_str(), key_pem.size(),
  22997. private_key_password};
  22998. ws::WebSocketClient client(url(), pem);
  22999. ASSERT_TRUE(client.is_valid());
  23000. client.enable_server_certificate_verification(false);
  23001. ASSERT_TRUE(client.connect());
  23002. ASSERT_TRUE(client.send("hello"));
  23003. std::string msg;
  23004. EXPECT_EQ(ws::Text, client.read(msg));
  23005. EXPECT_EQ("hello", msg);
  23006. client.close();
  23007. }
  23008. std::unique_ptr<SSLServer> server_;
  23009. std::thread server_thread_;
  23010. int port_ = 0;
  23011. };
  23012. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  23013. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  23014. }
  23015. // Control for the tests above: the fixture's server really does require a
  23016. // client certificate, so it is the PEM the constructor installed that decides
  23017. // the outcome.
  23018. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  23019. ws::WebSocketClient client(url());
  23020. ASSERT_TRUE(client.is_valid());
  23021. client.enable_server_certificate_verification(false);
  23022. EXPECT_FALSE(client.connect());
  23023. }
  23024. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  23025. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  23026. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  23027. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  23028. }
  23029. #endif
  23030. #if !defined(_WIN32)
  23031. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  23032. auto secret_dir = std::string("./symlink_test_secret");
  23033. auto served_dir = std::string("./symlink_test_served");
  23034. auto secret_file = secret_dir + "/secret.txt";
  23035. auto symlink_path = served_dir + "/escape";
  23036. // Setup: create directories and files
  23037. mkdir(secret_dir.c_str(), 0755);
  23038. mkdir(served_dir.c_str(), 0755);
  23039. {
  23040. std::ofstream ofs(secret_file);
  23041. ofs << "SECRET_DATA";
  23042. }
  23043. // Create symlink using absolute path so it resolves correctly
  23044. #ifdef PATH_MAX
  23045. char abs_secret[PATH_MAX];
  23046. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  23047. #else
  23048. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  23049. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  23050. ASSERT_NE(nullptr, abs_secret);
  23051. #endif
  23052. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  23053. auto se = detail::scope_exit([&] {
  23054. unlink(symlink_path.c_str());
  23055. unlink(secret_file.c_str());
  23056. rmdir(served_dir.c_str());
  23057. rmdir(secret_dir.c_str());
  23058. });
  23059. Server svr;
  23060. svr.set_mount_point("/", served_dir);
  23061. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  23062. auto se2 = detail::scope_exit([&] {
  23063. svr.stop();
  23064. listen_thread.join();
  23065. });
  23066. svr.wait_until_ready();
  23067. Client cli("localhost", PORT);
  23068. // Symlink pointing outside base dir should be blocked
  23069. auto res = cli.Get("/escape/secret.txt");
  23070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23071. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  23072. }
  23073. #endif
  23074. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  23075. // "GET /smuggled" request), reads the first response, and only then sends the
  23076. // embedded request as the body. Returns how many times /smuggled ran.
  23077. //
  23078. // The body is sent AFTER receiving the first response (as in the original
  23079. // PoC) so that the stream_line_reader cannot buffer it together with the
  23080. // headers of the first request.
  23081. static int count_smuggled_requests(const std::string &outer_head,
  23082. std::string &first_response) {
  23083. Server svr;
  23084. svr.set_mount_point("/", "./www");
  23085. std::atomic<int> smuggled_count(0);
  23086. svr.Get("/smuggled", [&](const Request &, Response &res) {
  23087. smuggled_count++;
  23088. res.set_content("oops", "text/plain");
  23089. });
  23090. svr.Post("/post", [&](const Request &req, Response &res) {
  23091. res.set_content(req.body, "text/plain");
  23092. });
  23093. auto port = svr.bind_to_any_port("localhost");
  23094. thread t = thread([&] { svr.listen_after_bind(); });
  23095. auto se = detail::scope_exit([&] {
  23096. svr.stop();
  23097. t.join();
  23098. });
  23099. svr.wait_until_ready();
  23100. auto error = Error::Success;
  23101. auto sock = detail::create_client_socket(
  23102. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  23103. /*connection_timeout_sec=*/2, 0,
  23104. /*read_timeout_sec=*/2, 0,
  23105. /*write_timeout_sec=*/2, 0, std::string(), error);
  23106. EXPECT_NE(INVALID_SOCKET, sock);
  23107. if (sock == INVALID_SOCKET) { return -1; }
  23108. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23109. // The "smuggled" request will be sent as the body of the outer request
  23110. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  23111. "Host: localhost\r\n"
  23112. "Connection: close\r\n"
  23113. "\r\n";
  23114. auto head = outer_head;
  23115. auto len = std::to_string(smuggled.size());
  23116. for (auto pos = head.find("{len}"); pos != std::string::npos;
  23117. pos = head.find("{len}", pos + len.size())) {
  23118. head.replace(pos, 5, len);
  23119. }
  23120. // Step 1: Send only the outer request headers (no body yet)
  23121. auto sent = send(sock, head.data(), head.size(), 0);
  23122. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  23123. // Step 2: Read the first response
  23124. char buf[4096];
  23125. for (;;) {
  23126. auto n = recv(sock, buf, sizeof(buf), 0);
  23127. if (n <= 0) break;
  23128. first_response.append(buf, static_cast<size_t>(n));
  23129. // Stop once we have a complete response (headers + body)
  23130. auto hdr_end = first_response.find("\r\n\r\n");
  23131. if (hdr_end != std::string::npos) {
  23132. // Check for Content-Length to know when the body is complete
  23133. auto cl_pos = first_response.find("Content-Length:");
  23134. if (cl_pos != std::string::npos) {
  23135. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  23136. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  23137. auto cl = std::stoul(
  23138. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  23139. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  23140. } else {
  23141. break; // No Content-Length, assume headers-only response
  23142. }
  23143. }
  23144. }
  23145. // Step 3: Now send the body, which looks like a new HTTP request. On a
  23146. // vulnerable server the keep-alive loop reads this as a second request. The
  23147. // server may already have closed the connection, so the result is ignored.
  23148. send(sock, smuggled.data(), smuggled.size(), 0);
  23149. // Half-close so that a server which drained the body sees EOF and closes,
  23150. // instead of the read below waiting for the read timeout.
  23151. #ifdef _WIN32
  23152. ::shutdown(sock, SD_SEND);
  23153. #else
  23154. ::shutdown(sock, SHUT_WR);
  23155. #endif
  23156. // Step 4: Read until the server closes the connection
  23157. for (;;) {
  23158. auto n = recv(sock, buf, sizeof(buf), 0);
  23159. if (n <= 0) break;
  23160. }
  23161. return smuggled_count.load();
  23162. }
  23163. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  23164. // A GET request with Content-Length to a static file handler must have its
  23165. // body drained before the keep-alive connection is reused. Otherwise the
  23166. // unread body bytes are interpreted as the next HTTP request.
  23167. std::string first_response;
  23168. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23169. "Host: localhost\r\n"
  23170. "Content-Length: {len}\r\n"
  23171. "\r\n",
  23172. first_response));
  23173. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  23174. }
  23175. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  23176. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  23177. // be answered with 400 and the connection closed. Treating it as "no body"
  23178. // leaves the body to be parsed as the next request.
  23179. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  23180. const char *targets[] = {
  23181. "GET /file", // handler that never reads the body
  23182. "GET /not-found", // no handler matches (404)
  23183. "POST /post", // handler that reads the body
  23184. };
  23185. for (auto target : targets) {
  23186. for (auto value : values) {
  23187. std::string first_response;
  23188. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  23189. " HTTP/1.1\r\n"
  23190. "Host: localhost\r\n"
  23191. "Content-Length: " +
  23192. value + "\r\n\r\n",
  23193. first_response))
  23194. << target << " with Content-Length: " << value;
  23195. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  23196. << target << " with Content-Length: " << value;
  23197. }
  23198. }
  23199. }
  23200. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  23201. // A 400 for an unparseable request line leaves the rest of the message
  23202. // unread, so the connection must be closed rather than reused.
  23203. std::string first_response;
  23204. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  23205. "Host: localhost\r\n"
  23206. "Content-Length: {len}\r\n"
  23207. "\r\n",
  23208. first_response));
  23209. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23210. }
  23211. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  23212. // Same as above for a header block that fails to parse.
  23213. std::string first_response;
  23214. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23215. "Host: localhost\r\n"
  23216. "Bad Header\r\n"
  23217. "Content-Length: {len}\r\n"
  23218. "\r\n",
  23219. first_response));
  23220. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23221. }
  23222. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  23223. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  23224. // server must not read another request on that connection, even when the
  23225. // request had no body to drain.
  23226. std::string first_response;
  23227. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  23228. "Host: localhost\r\n"
  23229. "\r\n",
  23230. first_response));
  23231. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  23232. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  23233. }
  23234. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  23235. // A content reader that stops early leaves the stream inside the body.
  23236. // Draining the whole Content-Length from there, or reading the body again,
  23237. // reads into the next request, and whatever follows is parsed as a request
  23238. // of its own.
  23239. Server svr;
  23240. std::atomic<int> smuggled_count(0);
  23241. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  23242. svr.Post("/upload", [](const Request &req, Response &res,
  23243. const ContentReader &content_reader) {
  23244. // Stop at the last chunk, so the whole body has been read however it
  23245. // arrives.
  23246. auto length = req.get_header_value_u64("Content-Length");
  23247. size_t total = 0;
  23248. auto consumed = content_reader([&](const char *, size_t n) {
  23249. total += n;
  23250. return total < length;
  23251. });
  23252. EXPECT_FALSE(consumed);
  23253. if (req.has_param("retry")) {
  23254. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  23255. }
  23256. // Replace the 400 the aborted read set, which would close the connection.
  23257. res.set_redirect("/done");
  23258. });
  23259. auto port = svr.bind_to_any_port(HOST);
  23260. thread t = thread([&] { svr.listen_after_bind(); });
  23261. auto se = detail::scope_exit([&] {
  23262. svr.stop();
  23263. t.join();
  23264. });
  23265. svr.wait_until_ready();
  23266. // A front end sees the second request as a POST whose body is the GET. The
  23267. // first body is as long as the POST's headers, so draining it again reads
  23268. // exactly those and leaves the GET to be parsed next.
  23269. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  23270. "Host: localhost\r\n"
  23271. "\r\n";
  23272. std::string second_head = "POST /post HTTP/1.1\r\n"
  23273. "Host: localhost\r\n"
  23274. "Content-Length: " +
  23275. std::to_string(inner.size()) +
  23276. "\r\n"
  23277. "\r\n";
  23278. for (auto target : {"/upload", "/upload?retry"}) {
  23279. smuggled_count = 0;
  23280. std::string request = "POST " + std::string(target) +
  23281. " HTTP/1.1\r\n"
  23282. "Host: localhost\r\n"
  23283. "Content-Length: " +
  23284. std::to_string(second_head.size()) +
  23285. "\r\n"
  23286. "\r\n" +
  23287. std::string(second_head.size(), 'A') + second_head +
  23288. inner;
  23289. std::string response;
  23290. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  23291. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  23292. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  23293. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  23294. EXPECT_EQ(0, smuggled_count.load()) << target;
  23295. }
  23296. }
  23297. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  23298. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  23299. // must be rejected with 400 Bad Request.
  23300. Server svr;
  23301. svr.Post("/test", [&](const Request &, Response &res) {
  23302. res.set_content("ok", "text/plain");
  23303. });
  23304. thread t = thread([&] { svr.listen(HOST, PORT); });
  23305. auto se = detail::scope_exit([&] {
  23306. svr.stop();
  23307. t.join();
  23308. ASSERT_FALSE(svr.is_running());
  23309. });
  23310. svr.wait_until_ready();
  23311. // Exact "chunked"
  23312. {
  23313. auto req = "POST /test HTTP/1.1\r\n"
  23314. "Host: localhost\r\n"
  23315. "Content-Length: 5\r\n"
  23316. "Transfer-Encoding: chunked\r\n"
  23317. "Connection: close\r\n"
  23318. "\r\n"
  23319. "hello";
  23320. std::string response;
  23321. ASSERT_TRUE(send_request(1, req, &response));
  23322. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23323. response.substr(0, response.find("\r\n")));
  23324. }
  23325. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  23326. {
  23327. auto req = "POST /test HTTP/1.1\r\n"
  23328. "Host: localhost\r\n"
  23329. "Content-Length: 5\r\n"
  23330. "Transfer-Encoding: gzip, chunked\r\n"
  23331. "Connection: close\r\n"
  23332. "\r\n"
  23333. "hello";
  23334. std::string response;
  23335. ASSERT_TRUE(send_request(1, req, &response));
  23336. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23337. response.substr(0, response.find("\r\n")));
  23338. }
  23339. }
  23340. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  23341. Server svr;
  23342. svr.Post("/test", [&](const Request &, Response &res) {
  23343. res.set_content("ok", "text/plain");
  23344. });
  23345. thread t = thread([&] { svr.listen(HOST, PORT); });
  23346. auto se = detail::scope_exit([&] {
  23347. svr.stop();
  23348. t.join();
  23349. ASSERT_FALSE(svr.is_running());
  23350. });
  23351. svr.wait_until_ready();
  23352. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  23353. // length cannot be determined, so the server must answer 400 and close
  23354. // rather than treat the request as bodyless and leave the body in the
  23355. // socket for the next request to pick up.
  23356. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  23357. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  23358. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  23359. std::string response;
  23360. ASSERT_TRUE(send_request(1, req, &response));
  23361. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23362. response.substr(0, response.find("\r\n")))
  23363. << transfer_encoding;
  23364. }
  23365. // RFC 9110 5.3: the codings may also be split across several
  23366. // Transfer-Encoding lines, which combine in the order they were received.
  23367. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  23368. // just like the single-line "chunked, gzip" above.
  23369. {
  23370. auto req = "POST /test HTTP/1.1\r\n"
  23371. "Host: localhost\r\n"
  23372. "Transfer-Encoding: chunked\r\n"
  23373. "Transfer-Encoding: gzip\r\n"
  23374. "\r\n"
  23375. "0\r\n\r\n";
  23376. std::string response;
  23377. ASSERT_TRUE(send_request(1, req, &response));
  23378. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23379. response.substr(0, response.find("\r\n")));
  23380. }
  23381. // A sequence ending in chunked stays valid.
  23382. auto req = "POST /test HTTP/1.1\r\n"
  23383. "Host: localhost\r\n"
  23384. "Transfer-Encoding: gzip, chunked\r\n"
  23385. "Connection: close\r\n"
  23386. "\r\n"
  23387. "0\r\n\r\n";
  23388. std::string response;
  23389. ASSERT_TRUE(send_request(1, req, &response));
  23390. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  23391. // ...including when it is spread over several lines.
  23392. auto split_req = "POST /test HTTP/1.1\r\n"
  23393. "Host: localhost\r\n"
  23394. "Transfer-Encoding: gzip\r\n"
  23395. "Transfer-Encoding: chunked\r\n"
  23396. "Connection: close\r\n"
  23397. "\r\n"
  23398. "0\r\n\r\n";
  23399. std::string split_response;
  23400. ASSERT_TRUE(send_request(1, split_req, &split_response));
  23401. EXPECT_EQ("HTTP/1.1 200 OK",
  23402. split_response.substr(0, split_response.find("\r\n")));
  23403. }
  23404. // Regression for issue #2450: a DELETE without Content-Length on a
  23405. // keep-alive connection must not let the post-response drain consume the
  23406. // next request's bytes.
  23407. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  23408. Server svr;
  23409. std::atomic<int> delete_count(0);
  23410. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  23411. delete_count++;
  23412. res.status = StatusCode::NoContent_204;
  23413. });
  23414. auto port = svr.bind_to_any_port(HOST);
  23415. thread t = thread([&] { svr.listen_after_bind(); });
  23416. auto se = detail::scope_exit([&] {
  23417. svr.stop();
  23418. t.join();
  23419. });
  23420. svr.wait_until_ready();
  23421. auto error = Error::Success;
  23422. auto sock = detail::create_client_socket(
  23423. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23424. /*connection_timeout_sec=*/2, 0,
  23425. /*read_timeout_sec=*/2, 0,
  23426. /*write_timeout_sec=*/2, 0, std::string(), error);
  23427. ASSERT_NE(INVALID_SOCKET, sock);
  23428. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23429. auto send_request_and_read_response = [&](const std::string &req,
  23430. std::string &out) -> bool {
  23431. auto sent = send(sock, req.data(), req.size(), 0);
  23432. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  23433. char buf[4096];
  23434. for (;;) {
  23435. auto n = recv(sock, buf, sizeof(buf), 0);
  23436. if (n <= 0) { return !out.empty(); }
  23437. out.append(buf, static_cast<size_t>(n));
  23438. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  23439. }
  23440. };
  23441. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  23442. "Host: localhost\r\n"
  23443. "\r\n";
  23444. std::string resp1;
  23445. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  23446. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  23447. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  23448. "Host: localhost\r\n"
  23449. "Connection: close\r\n"
  23450. "\r\n";
  23451. std::string resp2;
  23452. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  23453. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  23454. EXPECT_EQ(2, delete_count.load());
  23455. }
  23456. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  23457. Server svr;
  23458. svr.Post("/ingest", [&](const Request &, Response &res,
  23459. const ContentReader &content_reader) {
  23460. auto consumed = content_reader([](const char *, size_t) { return false; });
  23461. EXPECT_FALSE(consumed);
  23462. res.status = StatusCode::Conflict_409;
  23463. res.set_header("Connection", "close");
  23464. });
  23465. auto port = svr.bind_to_any_port(HOST);
  23466. thread t = thread([&] { svr.listen_after_bind(); });
  23467. auto se = detail::scope_exit([&] {
  23468. svr.stop();
  23469. t.join();
  23470. });
  23471. svr.wait_until_ready();
  23472. auto error = Error::Success;
  23473. auto sock = detail::create_client_socket(
  23474. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23475. /*connection_timeout_sec=*/2, 0,
  23476. /*read_timeout_sec=*/1, 0,
  23477. /*write_timeout_sec=*/2, 0, std::string(), error);
  23478. ASSERT_NE(INVALID_SOCKET, sock);
  23479. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23480. std::string request = "POST /ingest HTTP/1.1\r\n"
  23481. "Host: localhost\r\n"
  23482. "Transfer-Encoding: chunked\r\n"
  23483. "\r\n"
  23484. "4\r\n"
  23485. "data\r\n";
  23486. auto sent = send(sock, request.data(), request.size(), 0);
  23487. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  23488. std::string response;
  23489. ssize_t received = 0;
  23490. do {
  23491. char buf[4096];
  23492. received = recv(sock, buf, sizeof(buf), 0);
  23493. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  23494. } while (received > 0);
  23495. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  23496. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  23497. EXPECT_EQ(0, received);
  23498. }
  23499. namespace no_proxy_test {
  23500. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  23501. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  23502. // calling listen().
  23503. class ScopedServer {
  23504. public:
  23505. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  23506. ~ScopedServer() {
  23507. svr_.stop();
  23508. if (th_.joinable()) { th_.join(); }
  23509. }
  23510. Server &svr() { return svr_; }
  23511. int port() const { return port_; }
  23512. void listen() {
  23513. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23514. svr_.wait_until_ready();
  23515. }
  23516. private:
  23517. Server svr_;
  23518. std::thread th_;
  23519. int port_ = 0;
  23520. };
  23521. class ProxyAndTargetServers {
  23522. public:
  23523. ProxyAndTargetServers() {
  23524. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  23525. proxy_hits_++;
  23526. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23527. res.set_content("via-proxy", "text/plain");
  23528. });
  23529. target_.Get(".*", [this](const Request &req, Response &res) {
  23530. target_hits_++;
  23531. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23532. res.set_content("direct", "text/plain");
  23533. });
  23534. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  23535. target_port_ = target_.bind_to_any_port("127.0.0.1");
  23536. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  23537. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  23538. proxy_mock_.wait_until_ready();
  23539. target_.wait_until_ready();
  23540. }
  23541. ~ProxyAndTargetServers() {
  23542. proxy_mock_.stop();
  23543. target_.stop();
  23544. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  23545. if (target_thread_.joinable()) { target_thread_.join(); }
  23546. }
  23547. Server &proxy_mock() { return proxy_mock_; }
  23548. Server &target() { return target_; }
  23549. int proxy_port() const { return proxy_port_; }
  23550. int target_port() const { return target_port_; }
  23551. int proxy_hits() const { return proxy_hits_.load(); }
  23552. int target_hits() const { return target_hits_.load(); }
  23553. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  23554. void reset_counters() {
  23555. proxy_hits_ = 0;
  23556. target_hits_ = 0;
  23557. last_had_proxy_authz_ = false;
  23558. }
  23559. private:
  23560. Server proxy_mock_;
  23561. Server target_;
  23562. std::thread proxy_thread_;
  23563. std::thread target_thread_;
  23564. int proxy_port_ = 0;
  23565. int target_port_ = 0;
  23566. std::atomic<int> proxy_hits_{0};
  23567. std::atomic<int> target_hits_{0};
  23568. std::atomic<bool> last_had_proxy_authz_{false};
  23569. };
  23570. inline std::unique_ptr<Client> make_client(const std::string &host,
  23571. ProxyAndTargetServers &s) {
  23572. auto cli = detail::make_unique<Client>(host, s.target_port());
  23573. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  23574. cli->set_proxy("127.0.0.1", s.proxy_port());
  23575. return cli;
  23576. }
  23577. } // namespace no_proxy_test
  23578. using no_proxy_test::make_client;
  23579. using no_proxy_test::ProxyAndTargetServers;
  23580. TEST(NoProxyTest, ExactHostnameBypasses) {
  23581. ProxyAndTargetServers s;
  23582. auto cli = make_client("example.com", s);
  23583. cli->set_no_proxy({"example.com"});
  23584. auto res = cli->Get("/");
  23585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23586. EXPECT_EQ(0, s.proxy_hits());
  23587. EXPECT_EQ(1, s.target_hits());
  23588. }
  23589. TEST(NoProxyTest, SubdomainBypasses) {
  23590. ProxyAndTargetServers s;
  23591. auto cli = make_client("foo.example.com", s);
  23592. cli->set_no_proxy({"example.com"});
  23593. auto res = cli->Get("/");
  23594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23595. EXPECT_EQ(0, s.proxy_hits());
  23596. EXPECT_EQ(1, s.target_hits());
  23597. }
  23598. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  23599. // Regression guard: "evilexample.com" must not be considered a subdomain
  23600. // of "example.com". Without the dot-boundary rule, a naive endsWith
  23601. // check would let traffic bypass the proxy and leak credentials direct
  23602. // to the attacker host.
  23603. ProxyAndTargetServers s;
  23604. auto cli = make_client("evilexample.com", s);
  23605. cli->set_no_proxy({"example.com"});
  23606. auto res = cli->Get("/");
  23607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23608. EXPECT_GE(s.proxy_hits(), 1);
  23609. EXPECT_EQ(0, s.target_hits());
  23610. }
  23611. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  23612. ProxyAndTargetServers s;
  23613. auto cli = make_client("example.com.evil.com", s);
  23614. cli->set_no_proxy({"example.com"});
  23615. auto res = cli->Get("/");
  23616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23617. EXPECT_GE(s.proxy_hits(), 1);
  23618. EXPECT_EQ(0, s.target_hits());
  23619. }
  23620. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  23621. ProxyAndTargetServers s;
  23622. auto cli = make_client("example.com", s);
  23623. cli->set_no_proxy({".example.com"});
  23624. auto res = cli->Get("/");
  23625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23626. EXPECT_EQ(0, s.proxy_hits());
  23627. EXPECT_EQ(1, s.target_hits());
  23628. }
  23629. TEST(NoProxyTest, CaseInsensitiveHostname) {
  23630. ProxyAndTargetServers s;
  23631. auto cli = make_client("Example.COM", s);
  23632. cli->set_no_proxy({"EXAMPLE.com"});
  23633. auto res = cli->Get("/");
  23634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23635. EXPECT_EQ(0, s.proxy_hits());
  23636. EXPECT_EQ(1, s.target_hits());
  23637. }
  23638. TEST(NoProxyTest, TrailingDotIsNormalized) {
  23639. ProxyAndTargetServers s;
  23640. auto cli = make_client("example.com.", s);
  23641. cli->set_no_proxy({"example.com"});
  23642. auto res = cli->Get("/");
  23643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23644. EXPECT_EQ(0, s.proxy_hits());
  23645. EXPECT_EQ(1, s.target_hits());
  23646. }
  23647. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  23648. // Trailing dots must be normalized on BOTH sides — host and entry.
  23649. // An implementation that only strips the host-side trailing dot would
  23650. // fail to match host "example.com" against entry "example.com." because
  23651. // a literal substring search would compare 11 chars against 12.
  23652. ProxyAndTargetServers s;
  23653. auto cli = make_client("example.com", s);
  23654. cli->set_no_proxy({"example.com."});
  23655. auto res = cli->Get("/");
  23656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23657. EXPECT_EQ(0, s.proxy_hits());
  23658. EXPECT_EQ(1, s.target_hits());
  23659. }
  23660. TEST(NoProxyTest, WildcardBypassesEverything) {
  23661. ProxyAndTargetServers s;
  23662. auto cli = make_client("anything.invalid.test", s);
  23663. cli->set_no_proxy({"*"});
  23664. auto res = cli->Get("/");
  23665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23666. EXPECT_EQ(0, s.proxy_hits());
  23667. EXPECT_EQ(1, s.target_hits());
  23668. }
  23669. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  23670. ProxyAndTargetServers s;
  23671. Client cli("127.0.0.1", s.target_port());
  23672. cli.set_proxy("127.0.0.1", s.proxy_port());
  23673. cli.set_no_proxy({"127.0.0.1"});
  23674. auto res = cli.Get("/");
  23675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23676. EXPECT_EQ(0, s.proxy_hits());
  23677. EXPECT_EQ(1, s.target_hits());
  23678. }
  23679. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  23680. ProxyAndTargetServers s;
  23681. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  23682. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  23683. cli.set_proxy("127.0.0.1", s.proxy_port());
  23684. cli.set_no_proxy({"::1"});
  23685. auto res = cli.Get("/");
  23686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23687. EXPECT_EQ(0, s.proxy_hits());
  23688. EXPECT_EQ(1, s.target_hits());
  23689. }
  23690. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  23691. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  23692. // must still be recognized as IPv6 for CIDR matching. Implementations
  23693. // that detect IPv6 only when the host begins with '[' would parse the
  23694. // host as a hostname and miss the match.
  23695. ProxyAndTargetServers s;
  23696. Client cli("fe80::1", s.target_port());
  23697. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23698. cli.set_proxy("127.0.0.1", s.proxy_port());
  23699. cli.set_no_proxy({"fe80::/10"});
  23700. auto res = cli.Get("/");
  23701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23702. EXPECT_EQ(0, s.proxy_hits());
  23703. EXPECT_EQ(1, s.target_hits());
  23704. }
  23705. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  23706. ProxyAndTargetServers s;
  23707. Client cli("::1", s.target_port());
  23708. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  23709. cli.set_proxy("127.0.0.1", s.proxy_port());
  23710. cli.set_no_proxy({"[::1]"});
  23711. auto res = cli.Get("/");
  23712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23713. EXPECT_EQ(0, s.proxy_hits());
  23714. EXPECT_EQ(1, s.target_hits());
  23715. }
  23716. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  23717. ProxyAndTargetServers s;
  23718. Client cli("fe80::1", s.target_port());
  23719. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23720. cli.set_proxy("127.0.0.1", s.proxy_port());
  23721. cli.set_no_proxy({"[fe80::]/10"});
  23722. auto res = cli.Get("/");
  23723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23724. EXPECT_EQ(0, s.proxy_hits());
  23725. EXPECT_EQ(1, s.target_hits());
  23726. }
  23727. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  23728. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  23729. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  23730. // tricks via address-family conversion.
  23731. ProxyAndTargetServers s;
  23732. Client cli("::ffff:127.0.0.1", s.target_port());
  23733. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  23734. cli.set_proxy("127.0.0.1", s.proxy_port());
  23735. cli.set_no_proxy({"127.0.0.1"});
  23736. auto res = cli.Get("/");
  23737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23738. EXPECT_GE(s.proxy_hits(), 1);
  23739. EXPECT_EQ(0, s.target_hits());
  23740. }
  23741. TEST(NoProxyTest, IPv4CidrMatch) {
  23742. ProxyAndTargetServers s;
  23743. Client cli("127.0.0.1", s.target_port());
  23744. cli.set_proxy("127.0.0.1", s.proxy_port());
  23745. cli.set_no_proxy({"127.0.0.0/8"});
  23746. auto res = cli.Get("/");
  23747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23748. EXPECT_EQ(0, s.proxy_hits());
  23749. EXPECT_EQ(1, s.target_hits());
  23750. }
  23751. TEST(NoProxyTest, IPv4CidrNonMatch) {
  23752. ProxyAndTargetServers s;
  23753. Client cli("127.0.0.1", s.target_port());
  23754. cli.set_proxy("127.0.0.1", s.proxy_port());
  23755. cli.set_no_proxy({"10.0.0.0/8"});
  23756. auto res = cli.Get("/");
  23757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23758. EXPECT_GE(s.proxy_hits(), 1);
  23759. EXPECT_EQ(0, s.target_hits());
  23760. }
  23761. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  23762. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  23763. // IPv4 target matches.
  23764. ProxyAndTargetServers s;
  23765. Client cli("127.0.0.1", s.target_port());
  23766. cli.set_proxy("127.0.0.1", s.proxy_port());
  23767. cli.set_no_proxy({"0.0.0.0/0"});
  23768. auto res = cli.Get("/");
  23769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23770. EXPECT_EQ(0, s.proxy_hits());
  23771. EXPECT_EQ(1, s.target_hits());
  23772. }
  23773. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  23774. ProxyAndTargetServers s;
  23775. Client cli("127.0.0.1", s.target_port());
  23776. cli.set_proxy("127.0.0.1", s.proxy_port());
  23777. cli.set_no_proxy({"127.0.0.1"});
  23778. auto res = cli.Get("/");
  23779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23780. EXPECT_EQ(0, s.proxy_hits());
  23781. EXPECT_EQ(1, s.target_hits());
  23782. }
  23783. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  23784. ProxyAndTargetServers s;
  23785. Client cli("127.0.0.1", s.target_port());
  23786. cli.set_proxy("127.0.0.1", s.proxy_port());
  23787. cli.set_no_proxy({"127.0.0.0/33"});
  23788. auto res = cli.Get("/");
  23789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23790. EXPECT_GE(s.proxy_hits(), 1);
  23791. EXPECT_EQ(0, s.target_hits());
  23792. }
  23793. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  23794. // Empty prefix after the slash must be rejected, not silently treated as /32.
  23795. ProxyAndTargetServers s;
  23796. Client cli("127.0.0.1", s.target_port());
  23797. cli.set_proxy("127.0.0.1", s.proxy_port());
  23798. cli.set_no_proxy({"127.0.0.1/"});
  23799. auto res = cli.Get("/");
  23800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23801. EXPECT_GE(s.proxy_hits(), 1);
  23802. EXPECT_EQ(0, s.target_hits());
  23803. }
  23804. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  23805. ProxyAndTargetServers s;
  23806. auto cli = make_client("internal.corp", s);
  23807. cli->set_proxy_basic_auth("u", "p");
  23808. cli->set_no_proxy({"internal.corp"});
  23809. auto res = cli->Get("/");
  23810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23811. EXPECT_EQ(1, s.target_hits());
  23812. EXPECT_EQ(0, s.proxy_hits());
  23813. EXPECT_FALSE(s.last_had_proxy_authz())
  23814. << "Proxy-Authorization must not be sent direct to the target";
  23815. }
  23816. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  23817. ProxyAndTargetServers s;
  23818. auto cli = make_client("public.example", s);
  23819. cli->set_proxy_basic_auth("u", "p");
  23820. cli->set_no_proxy({"internal.corp"}); // does not match
  23821. auto res = cli->Get("/");
  23822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23823. EXPECT_GE(s.proxy_hits(), 1);
  23824. EXPECT_TRUE(s.last_had_proxy_authz());
  23825. }
  23826. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  23827. std::atomic<int> hits{0};
  23828. std::atomic<int> hits_with_authz{0};
  23829. no_proxy_test::ScopedServer proxy_mock;
  23830. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23831. hits++;
  23832. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  23833. if (req.target.find("/redir") != std::string::npos) {
  23834. res.set_redirect("http://other.example/landed");
  23835. } else {
  23836. res.set_content("via-proxy", "text/plain");
  23837. }
  23838. });
  23839. proxy_mock.listen();
  23840. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  23841. hits = 0;
  23842. hits_with_authz = 0;
  23843. Client cli("public.example", 80);
  23844. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23845. cli.set_proxy_basic_auth(c.first, c.second);
  23846. cli.set_follow_location(true);
  23847. // The redirect to another host goes through the proxy as well
  23848. auto res = cli.Get("/redir");
  23849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23850. EXPECT_EQ(2, hits.load());
  23851. EXPECT_EQ(2, hits_with_authz.load());
  23852. }
  23853. }
  23854. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  23855. ProxyAndTargetServers s;
  23856. auto cli = make_client("anything.test", s);
  23857. auto res = cli->Get("/");
  23858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23859. EXPECT_GE(s.proxy_hits(), 1);
  23860. EXPECT_EQ(0, s.target_hits());
  23861. }
  23862. TEST(NoProxyTest, PortSpecificEntryRejected) {
  23863. ProxyAndTargetServers s;
  23864. auto cli = make_client("example.com", s);
  23865. cli->set_no_proxy({"example.com:8080"});
  23866. auto res = cli->Get("/");
  23867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23868. EXPECT_GE(s.proxy_hits(), 1);
  23869. EXPECT_EQ(0, s.target_hits());
  23870. }
  23871. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  23872. ProxyAndTargetServers s;
  23873. auto cli = make_client("anything.test", s);
  23874. cli->set_no_proxy({"", " ", "\t"});
  23875. auto res = cli->Get("/");
  23876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23877. EXPECT_GE(s.proxy_hits(), 1);
  23878. EXPECT_EQ(0, s.target_hits());
  23879. }
  23880. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  23881. // An entry with leading/trailing whitespace must still match — env-style
  23882. // values are commonly pasted with stray spaces and an implementation
  23883. // that feeds the raw token directly to inet_pton would fail to match
  23884. // valid CIDRs because of the spaces.
  23885. ProxyAndTargetServers s;
  23886. Client cli("127.0.0.1", s.target_port());
  23887. cli.set_proxy("127.0.0.1", s.proxy_port());
  23888. cli.set_no_proxy({" 127.0.0.0/8 "});
  23889. auto res = cli.Get("/");
  23890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23891. EXPECT_EQ(0, s.proxy_hits());
  23892. EXPECT_EQ(1, s.target_hits());
  23893. }
  23894. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  23895. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  23896. // go direct and must NOT carry Proxy-Authorization.
  23897. std::atomic<int> proxy_hits{0};
  23898. std::atomic<int> target_hits{0};
  23899. std::atomic<bool> target_saw_authz{false};
  23900. no_proxy_test::ScopedServer proxy_mock, target;
  23901. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23902. proxy_hits++;
  23903. res.status = 302;
  23904. res.set_header("Location", "http://127.0.0.1:" +
  23905. std::to_string(target.port()) + "/landed");
  23906. });
  23907. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23908. target_hits++;
  23909. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  23910. res.set_content("direct", "text/plain");
  23911. });
  23912. proxy_mock.listen();
  23913. target.listen();
  23914. Client cli("public.example", target.port());
  23915. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23916. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23917. cli.set_proxy_basic_auth("u", "p");
  23918. cli.set_no_proxy({"127.0.0.1"});
  23919. cli.set_follow_location(true);
  23920. auto res = cli.Get("/redir");
  23921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23922. EXPECT_GE(proxy_hits.load(), 1);
  23923. EXPECT_GE(target_hits.load(), 1);
  23924. EXPECT_FALSE(target_saw_authz.load());
  23925. }
  23926. #ifdef CPPHTTPLIB_SSL_ENABLED
  23927. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  23928. // Direct origin replying 407 must not trigger the digest retry; otherwise
  23929. // proxy creds would be sent to the (possibly hostile) origin.
  23930. std::atomic<int> target_hits{0};
  23931. std::atomic<bool> target_saw_proxy_authz{false};
  23932. no_proxy_test::ScopedServer target;
  23933. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23934. target_hits++;
  23935. if (req.has_header("Proxy-Authorization")) {
  23936. target_saw_proxy_authz = true;
  23937. }
  23938. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23939. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  23940. "nonce=\"abc\", algorithm=MD5");
  23941. });
  23942. target.listen();
  23943. // The proxy address is set to the target's port: the bypass MUST kick in;
  23944. // if it doesn't, the test still routes "via proxy" to the same server and
  23945. // the Proxy-Authorization assertion below catches the leak.
  23946. Client cli("evil.example", target.port());
  23947. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  23948. cli.set_proxy("127.0.0.1", target.port());
  23949. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23950. cli.set_no_proxy({"evil.example"});
  23951. auto res = cli.Get("/x");
  23952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23953. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23954. EXPECT_EQ(1, target_hits.load());
  23955. EXPECT_FALSE(target_saw_proxy_authz.load());
  23956. }
  23957. #endif
  23958. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  23959. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  23960. std::atomic<int> proxy_hits{0};
  23961. std::atomic<int> bypass_hits{0};
  23962. std::atomic<bool> proxy_saw_c_url{false};
  23963. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  23964. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23965. proxy_hits++;
  23966. if (req.path.find("/start") != std::string::npos) {
  23967. res.status = 302;
  23968. res.set_header("Location", "http://127.0.0.1:" +
  23969. std::to_string(bypass_server.port()) +
  23970. "/middle");
  23971. return;
  23972. }
  23973. if (req.path.find("/end") != std::string::npos) {
  23974. proxy_saw_c_url = true;
  23975. res.set_content("c-via-proxy", "text/plain");
  23976. return;
  23977. }
  23978. res.set_content("unexpected", "text/plain");
  23979. });
  23980. // public.example's "advertised" port is arbitrary (the request never lands
  23981. // there — it goes through the proxy), but use a dynamic value to stay
  23982. // friendly with sharded parallel runs.
  23983. int public_port = bypass_server.port();
  23984. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  23985. bypass_hits++;
  23986. res.status = 302;
  23987. res.set_header("Location", "http://public.example:" +
  23988. std::to_string(public_port) + "/end");
  23989. });
  23990. proxy_mock.listen();
  23991. bypass_server.listen();
  23992. Client cli("public.example", public_port);
  23993. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23994. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23995. cli.set_no_proxy({"127.0.0.1"});
  23996. cli.set_follow_location(true);
  23997. auto res = cli.Get("/start");
  23998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23999. EXPECT_EQ(StatusCode::OK_200, res->status);
  24000. EXPECT_EQ("c-via-proxy", res->body);
  24001. EXPECT_GE(proxy_hits.load(), 2);
  24002. EXPECT_GE(bypass_hits.load(), 1);
  24003. EXPECT_TRUE(proxy_saw_c_url.load());
  24004. }
  24005. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  24006. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  24007. // request reconnects to the correct endpoint.
  24008. std::atomic<int> proxy_hits{0};
  24009. std::atomic<int> target_hits{0};
  24010. no_proxy_test::ScopedServer proxy_mock, target;
  24011. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24012. proxy_hits++;
  24013. res.set_content("via-proxy", "text/plain");
  24014. });
  24015. target.svr().Get(".*", [&](const Request &, Response &res) {
  24016. target_hits++;
  24017. res.set_content("direct", "text/plain");
  24018. });
  24019. proxy_mock.listen();
  24020. target.listen();
  24021. Client cli("public.example", target.port());
  24022. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24023. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24024. cli.set_keep_alive(true);
  24025. auto res1 = cli.Get("/a");
  24026. ASSERT_TRUE(res1);
  24027. EXPECT_EQ("via-proxy", res1->body);
  24028. EXPECT_EQ(1, proxy_hits.load());
  24029. EXPECT_EQ(0, target_hits.load());
  24030. cli.set_no_proxy({"public.example"});
  24031. auto res2 = cli.Get("/b");
  24032. ASSERT_TRUE(res2);
  24033. EXPECT_EQ("direct", res2->body);
  24034. EXPECT_EQ(1, proxy_hits.load());
  24035. EXPECT_EQ(1, target_hits.load());
  24036. }
  24037. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  24038. namespace proxy_tunnel_test {
  24039. // SSLServer counterpart to no_proxy_test::ScopedServer.
  24040. class ScopedSSLServer {
  24041. public:
  24042. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  24043. port_ = svr_.bind_to_any_port("127.0.0.1");
  24044. }
  24045. ~ScopedSSLServer() {
  24046. svr_.stop();
  24047. if (th_.joinable()) { th_.join(); }
  24048. }
  24049. SSLServer &svr() { return svr_; }
  24050. int port() const { return port_; }
  24051. void listen() {
  24052. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24053. svr_.wait_until_ready();
  24054. }
  24055. private:
  24056. SSLServer svr_;
  24057. std::thread th_;
  24058. int port_ = 0;
  24059. };
  24060. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  24061. class ScopedConnectProxy {
  24062. public:
  24063. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  24064. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  24065. if (listen_fd_ < 0) { return; }
  24066. int yes = 1;
  24067. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  24068. sockaddr_in a{};
  24069. a.sin_family = AF_INET;
  24070. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24071. a.sin_port = 0;
  24072. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  24073. return;
  24074. }
  24075. socklen_t alen = sizeof(a);
  24076. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  24077. 0) {
  24078. return;
  24079. }
  24080. port_ = ntohs(a.sin_port);
  24081. if (::listen(listen_fd_, 1) != 0) { return; }
  24082. th_ = std::thread([this] { run(); });
  24083. }
  24084. ~ScopedConnectProxy() {
  24085. stop_ = true;
  24086. if (listen_fd_ >= 0) {
  24087. ::shutdown(listen_fd_, SHUT_RDWR);
  24088. ::close(listen_fd_);
  24089. }
  24090. if (th_.joinable()) { th_.join(); }
  24091. }
  24092. int port() const { return port_; }
  24093. int connect_hits() const { return connect_hits_.load(); }
  24094. // Head of the last CONNECT request, as the proxy saw it on the wire.
  24095. std::string connect_request() const {
  24096. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24097. return connect_request_;
  24098. }
  24099. private:
  24100. void run() {
  24101. while (!stop_.load()) {
  24102. fd_set rfds;
  24103. FD_ZERO(&rfds);
  24104. FD_SET(listen_fd_, &rfds);
  24105. timeval tv{0, 100 * 1000};
  24106. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  24107. if (sel <= 0) { continue; }
  24108. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  24109. if (client_fd < 0) { continue; }
  24110. std::string req;
  24111. char buf[2048];
  24112. while (req.find("\r\n\r\n") == std::string::npos) {
  24113. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  24114. if (n <= 0) { break; }
  24115. req.append(buf, static_cast<size_t>(n));
  24116. }
  24117. if (req.compare(0, 7, "CONNECT") != 0) {
  24118. ::close(client_fd);
  24119. continue;
  24120. }
  24121. connect_hits_++;
  24122. {
  24123. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24124. connect_request_ = req;
  24125. }
  24126. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  24127. ::send(client_fd, ok, std::strlen(ok), 0);
  24128. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  24129. sockaddr_in o{};
  24130. o.sin_family = AF_INET;
  24131. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24132. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  24133. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  24134. 0) {
  24135. ::close(client_fd);
  24136. ::close(origin_fd);
  24137. continue;
  24138. }
  24139. auto forward = [](int from, int to) {
  24140. char b[8192];
  24141. for (;;) {
  24142. ssize_t n = ::recv(from, b, sizeof(b), 0);
  24143. if (n <= 0) { break; }
  24144. ssize_t off = 0;
  24145. while (off < n) {
  24146. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  24147. if (s <= 0) {
  24148. off = n;
  24149. break;
  24150. }
  24151. off += s;
  24152. }
  24153. }
  24154. ::shutdown(to, SHUT_WR);
  24155. };
  24156. std::thread t1([&] { forward(client_fd, origin_fd); });
  24157. std::thread t2([&] { forward(origin_fd, client_fd); });
  24158. t1.join();
  24159. t2.join();
  24160. ::close(client_fd);
  24161. ::close(origin_fd);
  24162. }
  24163. }
  24164. int forward_port_ = -1;
  24165. int listen_fd_ = -1;
  24166. int port_ = 0;
  24167. std::thread th_;
  24168. std::atomic<bool> stop_{false};
  24169. std::atomic<int> connect_hits_{0};
  24170. mutable std::mutex connect_request_mutex_;
  24171. std::string connect_request_;
  24172. };
  24173. // Sends one request through the CONNECT proxy to the TLS origin with a
  24174. // credential configured for each hop, and checks that each credential reaches
  24175. // only the hop it was configured for: the proxy's on the CONNECT request, the
  24176. // origin's (every header in origin_headers) on the tunnelled request.
  24177. void CredentialsStayWithTheirHop(
  24178. const std::function<void(SSLClient &)> &set_credentials,
  24179. const std::string &scheme,
  24180. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  24181. std::atomic<int> origin_hits{0};
  24182. std::atomic<bool> origin_saw_proxy_authz{false};
  24183. std::atomic<bool> origin_saw_headers{false};
  24184. ScopedSSLServer origin;
  24185. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24186. origin_hits++;
  24187. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  24188. origin_saw_headers =
  24189. std::all_of(origin_headers.begin(), origin_headers.end(),
  24190. [&](const std::string &h) { return req.has_header(h); });
  24191. res.set_content("ok", "text/plain");
  24192. });
  24193. origin.listen();
  24194. ScopedConnectProxy proxy(origin.port());
  24195. ASSERT_NE(0, proxy.port());
  24196. // Pinned to 127.0.0.1 for the same reason as the test below.
  24197. SSLClient cli("127.0.0.1", origin.port());
  24198. cli.enable_server_certificate_verification(false);
  24199. cli.set_proxy("127.0.0.1", proxy.port());
  24200. set_credentials(cli);
  24201. auto res = cli.Get("/x");
  24202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24203. EXPECT_EQ(StatusCode::OK_200, res->status);
  24204. EXPECT_EQ(1, origin_hits.load());
  24205. EXPECT_EQ(1, proxy.connect_hits());
  24206. EXPECT_TRUE(origin_saw_headers.load());
  24207. EXPECT_FALSE(origin_saw_proxy_authz.load())
  24208. << "Proxy-Authorization must not be sent inside the tunnel";
  24209. auto connect_req = proxy.connect_request();
  24210. EXPECT_NE(std::string::npos,
  24211. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  24212. for (const auto &h : origin_headers) {
  24213. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  24214. << h << " must not be sent to the proxy on CONNECT";
  24215. }
  24216. }
  24217. } // namespace proxy_tunnel_test
  24218. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  24219. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24220. [](SSLClient &cli) {
  24221. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24222. cli.set_basic_auth("origin-user", "origin-pass");
  24223. },
  24224. "Basic");
  24225. }
  24226. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  24227. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24228. [](SSLClient &cli) {
  24229. cli.set_proxy_bearer_token_auth("proxy-token");
  24230. cli.set_bearer_token_auth("origin-token");
  24231. },
  24232. "Bearer");
  24233. }
  24234. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  24235. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24236. [](SSLClient &cli) {
  24237. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24238. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  24239. {"Cookie", "sid=origin-session"},
  24240. {"X-Api-Key", "origin-key"}});
  24241. },
  24242. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  24243. }
  24244. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  24245. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  24246. // retry; otherwise proxy creds would be sent to the origin.
  24247. std::atomic<int> origin_hits{0};
  24248. std::atomic<bool> origin_saw_proxy_authz{false};
  24249. proxy_tunnel_test::ScopedSSLServer origin;
  24250. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24251. origin_hits++;
  24252. if (req.has_header("Proxy-Authorization")) {
  24253. origin_saw_proxy_authz = true;
  24254. }
  24255. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24256. res.set_header("Proxy-Authenticate",
  24257. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  24258. "algorithm=MD5");
  24259. });
  24260. origin.listen();
  24261. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  24262. ASSERT_NE(0, proxy.port());
  24263. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  24264. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  24265. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  24266. // and answer with its own status, making this test flaky.
  24267. SSLClient cli("127.0.0.1", origin.port());
  24268. cli.enable_server_certificate_verification(false);
  24269. cli.set_proxy("127.0.0.1", proxy.port());
  24270. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24271. auto res = cli.Get("/x");
  24272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24273. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24274. EXPECT_EQ(1, origin_hits.load());
  24275. EXPECT_FALSE(origin_saw_proxy_authz.load());
  24276. EXPECT_EQ(1, proxy.connect_hits());
  24277. }
  24278. #endif