test.cc 979 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172
  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 definitions are linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  68. } // namespace tls
  69. } // namespace httplib
  70. #endif
  71. using namespace std;
  72. using namespace httplib;
  73. const char *HOST = "localhost";
  74. static int get_base_port() {
  75. const char *shard = getenv("GTEST_SHARD_INDEX");
  76. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  77. }
  78. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  79. // New standalone tests MUST use svr.bind_to_any_port() instead.
  80. const int PORT = get_base_port();
  81. const string LONG_QUERY_VALUE = string(25000, '@');
  82. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  83. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  84. const string TOO_LONG_QUERY_URL =
  85. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  86. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  87. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  88. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  89. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  90. return file.name == key;
  91. });
  92. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  93. return *it;
  94. #else
  95. if (it != items.end()) { return *it; }
  96. throw std::runtime_error("invalid multipart form data name error");
  97. #endif
  98. }
  99. static void read_file(const std::string &path, std::string &out) {
  100. std::ifstream fs(path, std::ios_base::binary);
  101. if (!fs) {
  102. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  103. return;
  104. #else
  105. throw std::runtime_error("File not found: " + path);
  106. #endif
  107. }
  108. fs.seekg(0, std::ios_base::end);
  109. auto size = fs.tellg();
  110. fs.seekg(0);
  111. out.resize(static_cast<size_t>(size));
  112. fs.read(&out[0], static_cast<std::streamsize>(size));
  113. }
  114. class UnixSocketTest : public ::testing::Test {
  115. protected:
  116. void TearDown() override { std::remove(pathname_.c_str()); }
  117. void client_GET(const std::string &addr) {
  118. httplib::Client cli{addr};
  119. cli.set_address_family(AF_UNIX);
  120. ASSERT_TRUE(cli.is_valid());
  121. const auto &result = cli.Get(pattern_);
  122. ASSERT_TRUE(result) << "error: " << result.error();
  123. const auto &resp = result.value();
  124. EXPECT_EQ(resp.status, StatusCode::OK_200);
  125. EXPECT_EQ(resp.body, content_);
  126. }
  127. static std::string make_sock_path() {
  128. const char *shard = getenv("GTEST_SHARD_INDEX");
  129. return shard ? std::string("./httplib-server-") + shard + ".sock"
  130. : "./httplib-server.sock";
  131. }
  132. const std::string pathname_{make_sock_path()};
  133. const std::string pattern_{"/hi"};
  134. const std::string content_{"Hello World!"};
  135. };
  136. TEST_F(UnixSocketTest, pathname) {
  137. httplib::Server svr;
  138. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  139. res.set_content(content_, "text/plain");
  140. });
  141. std::thread t{[&] {
  142. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  143. }};
  144. auto se = detail::scope_exit([&] {
  145. svr.stop();
  146. t.join();
  147. ASSERT_FALSE(svr.is_running());
  148. });
  149. svr.wait_until_ready();
  150. ASSERT_TRUE(svr.is_running());
  151. client_GET(pathname_);
  152. // ".//x.sock", which is not taken for a URL
  153. client_GET("./" + pathname_.substr(1));
  154. }
  155. #if defined(__linux__) || \
  156. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  157. TEST_F(UnixSocketTest, PeerPid) {
  158. httplib::Server svr;
  159. std::string remote_port_val;
  160. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  161. res.set_content(content_, "text/plain");
  162. remote_port_val = std::to_string(req.remote_port);
  163. });
  164. std::thread t{[&] {
  165. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  166. }};
  167. auto se = detail::scope_exit([&] {
  168. svr.stop();
  169. t.join();
  170. ASSERT_FALSE(svr.is_running());
  171. });
  172. svr.wait_until_ready();
  173. ASSERT_TRUE(svr.is_running());
  174. client_GET(pathname_);
  175. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  176. }
  177. #endif
  178. #ifdef __linux__
  179. TEST_F(UnixSocketTest, abstract) {
  180. constexpr char svr_path[]{"\x00httplib-server.sock"};
  181. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  182. httplib::Server svr;
  183. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  184. res.set_content(content_, "text/plain");
  185. });
  186. std::thread t{[&] {
  187. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  188. }};
  189. auto se = detail::scope_exit([&] {
  190. svr.stop();
  191. t.join();
  192. ASSERT_FALSE(svr.is_running());
  193. });
  194. svr.wait_until_ready();
  195. ASSERT_TRUE(svr.is_running());
  196. client_GET(abstract_addr);
  197. }
  198. #endif
  199. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  200. httplib::Server svr;
  201. std::string received_host_header;
  202. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  203. // Capture the Host header sent by the client
  204. auto host_iter = req.headers.find("Host");
  205. if (host_iter != req.headers.end()) {
  206. received_host_header = host_iter->second;
  207. }
  208. res.set_content(content_, "text/plain");
  209. });
  210. std::thread t{[&] {
  211. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  212. }};
  213. auto se = detail::scope_exit([&] {
  214. svr.stop();
  215. t.join();
  216. ASSERT_FALSE(svr.is_running());
  217. });
  218. svr.wait_until_ready();
  219. ASSERT_TRUE(svr.is_running());
  220. // Test that Host header is automatically set to "localhost" for Unix socket
  221. // connections
  222. httplib::Client cli{pathname_};
  223. cli.set_address_family(AF_UNIX);
  224. ASSERT_TRUE(cli.is_valid());
  225. const auto &result = cli.Get(pattern_);
  226. ASSERT_TRUE(result) << "error: " << result.error();
  227. const auto &resp = result.value();
  228. EXPECT_EQ(resp.status, StatusCode::OK_200);
  229. EXPECT_EQ(resp.body, content_);
  230. // Verify that Host header was automatically set to "localhost"
  231. EXPECT_EQ(received_host_header, "localhost");
  232. }
  233. #ifndef _WIN32
  234. TEST(SocketStream, wait_writable_UNIX) {
  235. int fds[2];
  236. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  237. const auto asSocketStream = [&](socket_t fd,
  238. std::function<bool(Stream &)> func) {
  239. return detail::process_client_socket(
  240. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  241. };
  242. asSocketStream(fds[0], [&](Stream &s0) {
  243. EXPECT_EQ(s0.socket(), fds[0]);
  244. EXPECT_TRUE(s0.wait_writable());
  245. EXPECT_TRUE(s0.is_peer_alive());
  246. EXPECT_EQ(0, close(fds[1]));
  247. EXPECT_FALSE(s0.is_peer_alive());
  248. return true;
  249. });
  250. EXPECT_EQ(0, close(fds[0]));
  251. }
  252. TEST(SocketStream, wait_writable_INET) {
  253. sockaddr_in addr;
  254. memset(&addr, 0, sizeof(addr));
  255. addr.sin_family = AF_INET;
  256. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  257. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  258. int disconnected_svr_sock = -1;
  259. std::thread svr{[&] {
  260. const int s = socket(AF_INET, SOCK_STREAM, 0);
  261. ASSERT_LE(0, s);
  262. // PORT + 1 is shared with the SSL redirect tests and with
  263. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  264. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  265. // because that happens on a worker thread the ASSERT does not stop the
  266. // test: it runs on and fails at the disconnected_svr_sock check instead.
  267. default_socket_options(s);
  268. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  269. ASSERT_EQ(0, listen(s, 1));
  270. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  271. ASSERT_EQ(0, close(s));
  272. }};
  273. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  274. std::thread cli{[&] {
  275. const int s = socket(AF_INET, SOCK_STREAM, 0);
  276. ASSERT_LE(0, s);
  277. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  278. ASSERT_EQ(0, close(s));
  279. }};
  280. cli.join();
  281. svr.join();
  282. ASSERT_NE(disconnected_svr_sock, -1);
  283. const auto asSocketStream = [&](socket_t fd,
  284. std::function<bool(Stream &)> func) {
  285. return detail::process_client_socket(
  286. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  287. };
  288. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  289. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  290. // wait_writable() returns true because select_write() only checks if the
  291. // send buffer has space. Peer disconnection is detected later by send().
  292. EXPECT_TRUE(ss.wait_writable());
  293. return true;
  294. });
  295. ASSERT_EQ(0, close(disconnected_svr_sock));
  296. }
  297. #endif // #ifndef _WIN32
  298. TEST(SetSocketOptTest, TcpNoDelay) {
  299. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  300. ASSERT_NE(sock, INVALID_SOCKET);
  301. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  302. int val = 0;
  303. socklen_t len = sizeof(val);
  304. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  305. reinterpret_cast<char *>(&val), &len));
  306. EXPECT_NE(val, 0);
  307. detail::close_socket(sock);
  308. }
  309. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  310. // accept() reports failures through WSAGetLastError() on Windows and through
  311. // errno everywhere else. Asking the wrong one is what made the accept loop
  312. // treat every recoverable failure as fatal on Windows.
  313. struct Classification {
  314. bool resource;
  315. bool transient;
  316. };
  317. auto classify = [](int err) {
  318. #ifdef _WIN32
  319. WSASetLastError(err);
  320. #else
  321. errno = err;
  322. #endif
  323. // Read both before asserting: an assertion may clobber the error slot.
  324. Classification c;
  325. c.resource = detail::is_accept_resource_error();
  326. c.transient = detail::is_accept_transient_error();
  327. return c;
  328. };
  329. #ifdef _WIN32
  330. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  331. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  332. WSAECONNRESET, WSAECONNABORTED};
  333. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  334. #else
  335. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  336. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  337. ECONNABORTED};
  338. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  339. #endif
  340. for (auto err : resource_errors) {
  341. const auto c = classify(err);
  342. EXPECT_TRUE(c.resource) << "error " << err;
  343. EXPECT_FALSE(c.transient) << "error " << err;
  344. }
  345. for (auto err : transient_errors) {
  346. const auto c = classify(err);
  347. EXPECT_TRUE(c.transient) << "error " << err;
  348. EXPECT_FALSE(c.resource) << "error " << err;
  349. }
  350. for (auto err : fatal_errors) {
  351. const auto c = classify(err);
  352. EXPECT_FALSE(c.resource) << "error " << err;
  353. EXPECT_FALSE(c.transient) << "error " << err;
  354. }
  355. #ifdef _WIN32
  356. WSASetLastError(0);
  357. #else
  358. errno = 0;
  359. #endif
  360. }
  361. TEST(ClientTest, MoveConstructible) {
  362. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  363. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  364. }
  365. TEST(ClientTest, MoveAssignable) {
  366. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  367. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  368. }
  369. #ifdef _WIN32
  370. TEST(StartupTest, WSAStartup) {
  371. WSADATA wsaData;
  372. int ret = WSAStartup(0x0002, &wsaData);
  373. ASSERT_EQ(0, ret);
  374. }
  375. #endif
  376. TEST(DecodePathTest, PercentCharacter) {
  377. EXPECT_EQ(
  378. decode_path_component(
  379. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  380. U8("descrip=Gastos áéíóúñÑ 6"));
  381. }
  382. TEST(DecodePathTest, PercentCharacterNUL) {
  383. string expected;
  384. expected.push_back('x');
  385. expected.push_back('\0');
  386. expected.push_back('x');
  387. EXPECT_EQ(decode_path_component("x%00x"), expected);
  388. }
  389. TEST(DecodePathTest, UnicodeEncoding) {
  390. // %u0041 = 'A' (1-byte UTF-8)
  391. EXPECT_EQ("A", decode_path_component("%u0041"));
  392. // %u00E9 = 'é' (2-byte UTF-8)
  393. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  394. // %u3042 = 'あ' (3-byte UTF-8)
  395. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  396. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  397. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  398. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  399. // neighbours)
  400. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  401. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  402. }
  403. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  404. // A sign or whitespace inside the two-character escape window must not be
  405. // accepted as a valid percent-encoding; the sequence is passed through
  406. // literally, matching decode_uri_component / decode_path_component.
  407. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  408. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  409. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  410. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  411. // Well-formed escapes still decode.
  412. EXPECT_EQ("-", decode_query_component("%2D", false));
  413. EXPECT_EQ("A", decode_query_component("%41", false));
  414. }
  415. TEST(SanitizeFilenameTest, VariousPatterns) {
  416. // Path traversal
  417. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  418. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  419. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  420. // Normal and edge cases
  421. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  422. EXPECT_EQ("filename.txt",
  423. httplib::sanitize_filename("/path/to/filename.txt"));
  424. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  425. EXPECT_EQ("", httplib::sanitize_filename(".."));
  426. EXPECT_EQ("", httplib::sanitize_filename(""));
  427. // Null bytes stripped
  428. EXPECT_EQ("safe.txt",
  429. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  430. // Whitespace-only rejected
  431. EXPECT_EQ("", httplib::sanitize_filename(" "));
  432. }
  433. // Forward declaration (see the base64_encode note below): split builds move the
  434. // definition into httplib.cc, so re-declaring it here lets the test link.
  435. namespace httplib {
  436. namespace detail {
  437. bool is_chunked_transfer_encoding(const Headers &headers);
  438. } // namespace detail
  439. } // namespace httplib
  440. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  441. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  442. auto make = [](std::initializer_list<const char *> lines) {
  443. Headers h;
  444. for (auto te : lines) {
  445. if (te) { h.emplace("Transfer-Encoding", te); }
  446. }
  447. return h;
  448. };
  449. // Sole coding, matched case-insensitively.
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  453. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  454. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  455. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  456. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  457. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  458. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  459. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  462. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  463. // were received, into one list. Headers preserves that order, so the answer
  464. // is decided by the last coding of the last line and the order the lines
  465. // arrived in is significant.
  466. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  467. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  468. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  469. // The split can fall anywhere in the list.
  470. EXPECT_TRUE(
  471. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  472. EXPECT_FALSE(
  473. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  474. // A trailing line naming no coding leaves the list ending in nothing, so it
  475. // must not inherit the chunked from the line before it.
  476. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  477. }
  478. // Forward declarations (see the base64_encode note below).
  479. namespace httplib {
  480. namespace detail {
  481. bool parse_status_line(const char *line, std::string &version, int &status,
  482. std::string &reason);
  483. std::string file_extension(const std::string &path);
  484. std::string
  485. find_content_type(const std::string &path,
  486. const std::map<std::string, std::string> &user_data,
  487. const std::string &default_content_type);
  488. bool can_compress_content_type(const std::string &content_type);
  489. bool is_prohibited_header_name(const std::string &name);
  490. #ifdef CPPHTTPLIB_SSL_ENABLED
  491. bool match_hostname(const std::string &pattern, const std::string &hostname);
  492. #endif
  493. } // namespace detail
  494. } // namespace httplib
  495. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  496. struct {
  497. const char *line;
  498. const char *version;
  499. int status;
  500. const char *reason;
  501. } cases[] = {
  502. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  503. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  504. // The reason phrase may be empty, or left out along with its space.
  505. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  506. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  507. };
  508. for (const auto &c : cases) {
  509. std::string version;
  510. int status = 0;
  511. std::string reason = "unset";
  512. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  513. << c.line;
  514. EXPECT_EQ(c.version, version);
  515. EXPECT_EQ(c.status, status);
  516. EXPECT_EQ(c.reason, reason);
  517. }
  518. }
  519. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  520. const char *lines[] = {
  521. "HTTP/2 200 OK\r\n",
  522. "HTTP/1.2 200 OK\r\n",
  523. "HTTP/1.1 20 OK\r\n",
  524. "HTTP/1.1 2000 OK\r\n",
  525. "HTTP/1.1 2x0 OK\r\n",
  526. "HTTP/1.1 200 OK\r\n",
  527. "HTTP/1.1 200OK\r\n",
  528. "HTTP/1.1 200 O\rK\r\n",
  529. "HTTP/1.1 200 OK",
  530. "HTTP/1.1 200 OK\r\nX",
  531. "",
  532. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  533. "HTTP/1.1 200 OK\n",
  534. #endif
  535. };
  536. for (auto line : lines) {
  537. std::string version;
  538. int status = 0;
  539. std::string reason;
  540. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  541. << line;
  542. }
  543. }
  544. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  545. // Long enough to overflow the stack when matched with std::regex.
  546. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  547. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  548. std::string version;
  549. int status = 0;
  550. std::string reason;
  551. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  552. EXPECT_EQ(200, status);
  553. EXPECT_EQ(long_reason, reason);
  554. }
  555. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  556. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  557. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  558. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  559. EXPECT_EQ("", detail::file_extension("noext"));
  560. EXPECT_EQ("", detail::file_extension("a."));
  561. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  562. EXPECT_EQ("", detail::file_extension("a.b-c"));
  563. // Long enough to overflow the stack when matched with std::regex.
  564. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  565. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  566. }
  567. #ifdef CPPHTTPLIB_SSL_ENABLED
  568. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  569. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  570. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  571. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  572. // A wildcard needs two labels after it, in the leftmost label only
  573. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  574. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  575. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  576. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  577. EXPECT_FALSE(
  578. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  579. // No name may have an empty label
  580. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  581. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  582. }
  583. #endif
  584. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  585. detail::case_ignore::hash hash;
  586. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  587. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  588. // Long enough to overflow the stack if hashed one call per character.
  589. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  590. }
  591. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  592. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  593. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  594. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  595. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  596. // Same 26-bit hash as html, svg and js.
  597. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  598. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  599. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  600. }
  601. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  602. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  603. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  604. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  605. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  606. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  607. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  608. // Same 26-bit hash as application/json.
  609. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  610. }
  611. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  612. Request req;
  613. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  614. EXPECT_TRUE(req.is_multipart_form_data());
  615. std::string boundary;
  616. EXPECT_TRUE(detail::parse_multipart_boundary(
  617. req.get_header_value("Content-Type"), boundary));
  618. EXPECT_EQ("x", boundary);
  619. }
  620. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  621. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  622. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  623. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  624. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  625. // Same 26-bit hash as REMOTE_ADDR.
  626. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  627. }
  628. // Forward declaration: in split builds split.py strips `inline` and moves the
  629. // definition into httplib.cc, so detail::base64_encode is not visible from the
  630. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  631. // in both header-only and split builds.
  632. namespace httplib {
  633. namespace detail {
  634. std::string base64_encode(const std::string &in);
  635. } // namespace detail
  636. } // namespace httplib
  637. TEST(Base64EncodeTest, KnownAnswers) {
  638. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  639. // where the accumulator's top bit is already set before the next shift.
  640. EXPECT_EQ("", detail::base64_encode(""));
  641. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  642. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  643. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  644. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  645. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  646. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  647. // High bytes keep the top bit set across several rounds.
  648. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  649. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  650. }
  651. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  652. string unescapedCharacters = "-_.!~*'()";
  653. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  654. }
  655. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  656. string reservedCharacters = ";,/?:@&=+$";
  657. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  658. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  659. }
  660. TEST(ClientQueryOrder, PreserveOrder) {
  661. // This test reproduces Issue #2259: client may reorder query parameters
  662. // when sending a GET request. The expected behavior is that the client
  663. // preserves the original query string order when the caller supplied it
  664. // as part of the path.
  665. Server svr;
  666. svr.Get("/", [&](const Request &req, Response &res) {
  667. // Echo back the raw target so the test can assert ordering
  668. res.set_content(req.target, "text/plain");
  669. });
  670. std::thread t{[&] { svr.listen(HOST, PORT); }};
  671. auto se = detail::scope_exit([&] {
  672. svr.stop();
  673. t.join();
  674. ASSERT_FALSE(svr.is_running());
  675. });
  676. svr.wait_until_ready();
  677. Client cli(HOST, PORT);
  678. ASSERT_TRUE(cli.is_valid());
  679. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  680. auto res = cli.Get(original);
  681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  682. // Expect the echoed target to exactly match the original path (order
  683. // preserved)
  684. EXPECT_EQ(res->body, original);
  685. }
  686. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  687. string chineseCharacters = U8("中国語");
  688. string russianCharacters = U8("дом");
  689. string brazilianCharacters = U8("óculos");
  690. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  691. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  692. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  693. "%D0%B4%D0%BE%D0%BC");
  694. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  695. }
  696. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  697. string unescapedCharacters = "-_.!~*'()";
  698. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  699. }
  700. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  701. string reservedCharacters = ";,/?:@&=+$";
  702. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  703. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  704. }
  705. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  706. string chineseCharacters = U8("中国語");
  707. string russianCharacters = U8("дом");
  708. string brazilianCharacters = U8("óculos");
  709. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  710. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  711. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  712. "%D0%B4%D0%BE%D0%BC");
  713. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  714. }
  715. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  716. // Issue #2082 use case: encoding path component with ampersand
  717. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  718. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  719. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  720. }
  721. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  722. string unescapedCharacters = "-_.!~*'()";
  723. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  724. }
  725. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  726. string reservedCharacters = ";,/?:@&=+$#";
  727. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  728. }
  729. TEST(EncodeUriTest, TestUTF8Characters) {
  730. string chineseCharacters = U8("中国語");
  731. string russianCharacters = U8("дом");
  732. string brazilianCharacters = U8("óculos");
  733. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  734. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  735. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  736. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  737. }
  738. TEST(EncodeUriTest, TestCompleteUri) {
  739. string uri =
  740. "https://example.com/path/to/resource?query=value&param=test#fragment";
  741. EXPECT_EQ(
  742. httplib::encode_uri(uri),
  743. "https://example.com/path/to/resource?query=value&param=test#fragment");
  744. }
  745. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  746. string uri =
  747. "https://example.com/path with spaces/file name.html?q=hello world";
  748. EXPECT_EQ(httplib::encode_uri(uri),
  749. "https://example.com/path%20with%20spaces/"
  750. "file%20name.html?q=hello%20world");
  751. }
  752. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  753. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  754. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  755. }
  756. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  757. string unescapedCharacters = "-_.!~*'()";
  758. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  759. }
  760. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  761. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  762. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  763. string encodedBrazilian = "%C3%B3culos";
  764. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  765. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  766. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  767. }
  768. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  769. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  770. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  771. "Piri Tommy Villiers - on & on");
  772. }
  773. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  774. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  775. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  776. }
  777. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  778. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  779. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  780. }
  781. TEST(DecodeUriTest, TestUTF8Characters) {
  782. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  783. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  784. string encodedBrazilian = "%C3%B3culos";
  785. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  786. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  787. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  788. }
  789. TEST(DecodeUriTest, TestCompleteUri) {
  790. string encodedUri = "https://example.com/path%20with%20spaces/"
  791. "file%20name.html?q=hello%20world";
  792. EXPECT_EQ(
  793. httplib::decode_uri(encodedUri),
  794. "https://example.com/path with spaces/file name.html?q=hello world");
  795. }
  796. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  797. string original =
  798. "https://example.com/path with spaces/file name.html?q=hello world";
  799. string encoded = httplib::encode_uri(original);
  800. string decoded = httplib::decode_uri(encoded);
  801. EXPECT_EQ(decoded, original);
  802. }
  803. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  804. // decode_uri is the inverse of encode_uri: an escaped reserved character
  805. // stays encoded so it is not promoted into a real delimiter, while
  806. // non-reserved escapes still decode (like JS decodeURI).
  807. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  808. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  809. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  810. "%3F%3A%40%26%3D%2B%24%2C%3B");
  811. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  812. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  813. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  814. "http://example.com/a%2Fb");
  815. // decode_uri_component still decodes the reserved character.
  816. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  817. }
  818. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  819. string original = "Piri Tommy Villiers - on & on";
  820. string encoded = httplib::encode_uri_component(original);
  821. string decoded = httplib::decode_uri_component(encoded);
  822. EXPECT_EQ(decoded, original);
  823. }
  824. TEST(TrimTests, TrimStringTests) {
  825. EXPECT_EQ("abc", detail::trim_copy("abc"));
  826. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  827. EXPECT_TRUE(detail::trim_copy("").empty());
  828. }
  829. TEST(AsciiTest, LocaleIndependentClassification) {
  830. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  831. // which consult the global C locale: std::isalnum(0xC5) can return true
  832. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  833. // helpers must classify every byte by the ASCII grammar alone.
  834. for (int i = 0; i < 256; i++) {
  835. auto c = static_cast<char>(i);
  836. auto is_digit = i >= '0' && i <= '9';
  837. auto is_upper = i >= 'A' && i <= 'Z';
  838. auto is_lower = i >= 'a' && i <= 'z';
  839. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  840. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  841. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  842. << "byte " << i;
  843. }
  844. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  845. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  846. // Non-ASCII bytes must be percent-encoded, never passed through as
  847. // alphanumeric.
  848. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  849. }
  850. TEST(FromCharsTest, Double) {
  851. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  852. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  853. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  854. auto parse = [](const std::string &s, double &v) {
  855. return detail::from_chars(s.data(), s.data() + s.size(), v);
  856. };
  857. double v = -1.0;
  858. // Representative quality values.
  859. EXPECT_EQ(parse("0", v).ec, std::errc{});
  860. EXPECT_DOUBLE_EQ(v, 0.0);
  861. EXPECT_EQ(parse("1", v).ec, std::errc{});
  862. EXPECT_DOUBLE_EQ(v, 1.0);
  863. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  864. EXPECT_DOUBLE_EQ(v, 0.8);
  865. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  866. EXPECT_DOUBLE_EQ(v, 0.001);
  867. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  868. EXPECT_DOUBLE_EQ(v, 1.0);
  869. // A missing integer or fractional part is tolerated.
  870. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  871. EXPECT_DOUBLE_EQ(v, 0.5);
  872. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  873. EXPECT_DOUBLE_EQ(v, 5.0);
  874. // Values outside [0, 1] still parse; the caller range-checks them.
  875. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  876. EXPECT_DOUBLE_EQ(v, 123.456);
  877. // Stops at the first byte that is not part of the number and reports where.
  878. std::string trailing = "0.9, text/html";
  879. auto r = parse(trailing, v);
  880. EXPECT_EQ(r.ec, std::errc{});
  881. EXPECT_DOUBLE_EQ(v, 0.9);
  882. EXPECT_EQ(*r.ptr, ',');
  883. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  884. // outright, and an 'e'/'E' simply ends the number.
  885. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  886. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  887. std::string exp_input = "1.5e3";
  888. r = parse(exp_input, v);
  889. EXPECT_EQ(r.ec, std::errc{});
  890. EXPECT_DOUBLE_EQ(v, 1.5);
  891. EXPECT_EQ(*r.ptr, 'e');
  892. // Invalid inputs.
  893. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  894. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  895. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  896. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  897. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  898. // Pathological but well-formed inputs must stay bounded (no overflow, no
  899. // out-of-bounds table access) and stay within [0, 1] for the caller.
  900. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  901. std::errc{});
  902. EXPECT_DOUBLE_EQ(v, 0.0);
  903. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  904. std::errc{});
  905. EXPECT_GE(v, 0.0);
  906. EXPECT_LE(v, 1.0);
  907. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  908. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  909. }
  910. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  911. // Simple case without quality values
  912. std::vector<std::string> result1;
  913. EXPECT_TRUE(detail::parse_accept_header(
  914. "text/html,application/json,text/plain", result1));
  915. EXPECT_EQ(result1.size(), 3U);
  916. EXPECT_EQ(result1[0], "text/html");
  917. EXPECT_EQ(result1[1], "application/json");
  918. EXPECT_EQ(result1[2], "text/plain");
  919. // With quality values
  920. std::vector<std::string> result2;
  921. EXPECT_TRUE(detail::parse_accept_header(
  922. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  923. EXPECT_EQ(result2.size(), 3U);
  924. EXPECT_EQ(result2[0], "application/json"); // highest q value
  925. EXPECT_EQ(result2[1], "text/html");
  926. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  927. }
  928. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  929. // Mixed with and without quality values
  930. std::vector<std::string> result;
  931. EXPECT_TRUE(detail::parse_accept_header(
  932. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  933. EXPECT_EQ(result.size(), 3U);
  934. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  935. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  936. EXPECT_EQ(result[2], "application/json"); // q=0.5
  937. }
  938. TEST(ParseAcceptHeaderTest, EdgeCases) {
  939. // Empty header
  940. std::vector<std::string> empty_result;
  941. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  942. EXPECT_TRUE(empty_result.empty());
  943. // Single type
  944. std::vector<std::string> single_result;
  945. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  946. EXPECT_EQ(single_result.size(), 1U);
  947. EXPECT_EQ(single_result[0], "application/json");
  948. // Wildcard types
  949. std::vector<std::string> wildcard_result;
  950. EXPECT_TRUE(detail::parse_accept_header(
  951. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  952. EXPECT_EQ(wildcard_result.size(), 3U);
  953. EXPECT_EQ(wildcard_result[0], "application/json");
  954. EXPECT_EQ(wildcard_result[1], "text/*");
  955. EXPECT_EQ(wildcard_result[2], "*/*");
  956. }
  957. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  958. // Common browser Accept header
  959. std::vector<std::string> browser_result;
  960. EXPECT_TRUE(
  961. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  962. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  963. browser_result));
  964. EXPECT_EQ(browser_result.size(), 6U);
  965. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  966. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  967. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  968. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  969. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  970. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  971. // API client header
  972. std::vector<std::string> api_result;
  973. EXPECT_TRUE(detail::parse_accept_header(
  974. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  975. api_result));
  976. EXPECT_EQ(api_result.size(), 3U);
  977. EXPECT_EQ(api_result[0], "application/json");
  978. EXPECT_EQ(api_result[1], "application/xml");
  979. EXPECT_EQ(api_result[2], "text/plain");
  980. }
  981. TEST(ParseAcceptHeaderTest, SpecialCases) {
  982. // Quality value with 3 decimal places
  983. std::vector<std::string> decimal_result;
  984. EXPECT_TRUE(detail::parse_accept_header(
  985. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  986. EXPECT_EQ(decimal_result.size(), 2U);
  987. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  988. EXPECT_EQ(decimal_result[1], "text/html");
  989. // Zero quality (should still be included but with lowest priority)
  990. std::vector<std::string> zero_q_result;
  991. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  992. zero_q_result));
  993. EXPECT_EQ(zero_q_result.size(), 2U);
  994. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  995. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  996. // No spaces around commas
  997. std::vector<std::string> no_space_result;
  998. EXPECT_TRUE(detail::parse_accept_header(
  999. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1000. no_space_result));
  1001. EXPECT_EQ(no_space_result.size(), 3U);
  1002. EXPECT_EQ(no_space_result[0], "text/html");
  1003. EXPECT_EQ(no_space_result[1], "application/json");
  1004. EXPECT_EQ(no_space_result[2], "text/plain");
  1005. }
  1006. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1007. // Quality values always use '.' as the decimal separator, so parsing must
  1008. // not depend on the process locale. An embedding application may have
  1009. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1010. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1011. std::string saved = cur ? cur : "C";
  1012. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1013. "fr_FR.UTF-8"};
  1014. bool switched = false;
  1015. for (const auto loc : comma_locales) {
  1016. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1017. std::localeconv()->decimal_point[0] == ',') {
  1018. switched = true;
  1019. break;
  1020. }
  1021. }
  1022. if (!switched) {
  1023. std::setlocale(LC_NUMERIC, saved.c_str());
  1024. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1025. }
  1026. // The higher-weighted type appears later in the list, so a correct parse
  1027. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1028. // sensitive parse reads both weights as 0 and leaves the original order.
  1029. std::vector<std::string> result;
  1030. EXPECT_TRUE(detail::parse_accept_header(
  1031. "application/json;q=0.1,text/html;q=0.9", result));
  1032. ASSERT_EQ(result.size(), 2U);
  1033. EXPECT_EQ(result[0], "text/html");
  1034. EXPECT_EQ(result[1], "application/json");
  1035. std::setlocale(LC_NUMERIC, saved.c_str());
  1036. }
  1037. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1038. std::vector<std::string> result;
  1039. // Invalid quality value (> 1.0)
  1040. EXPECT_FALSE(
  1041. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1042. // Invalid quality value (< 0.0)
  1043. EXPECT_FALSE(
  1044. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1045. // Invalid quality value (not a number)
  1046. EXPECT_FALSE(detail::parse_accept_header(
  1047. "text/html;q=invalid,application/json", result));
  1048. // A valid numeric prefix does not make the entire quality value valid.
  1049. EXPECT_FALSE(detail::parse_accept_header(
  1050. "text/html;q=0.5junk,application/json", result));
  1051. // Empty quality value
  1052. EXPECT_FALSE(
  1053. detail::parse_accept_header("text/html;q=,application/json", result));
  1054. // Invalid media type format (no slash and not wildcard)
  1055. EXPECT_FALSE(
  1056. detail::parse_accept_header("invalidtype,application/json", result));
  1057. // Valid cases should still work
  1058. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1059. EXPECT_EQ(result.size(), 1U);
  1060. EXPECT_EQ(result[0], "*/*");
  1061. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1062. EXPECT_EQ(result.size(), 1U);
  1063. EXPECT_EQ(result[0], "*");
  1064. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1065. EXPECT_EQ(result.size(), 1U);
  1066. EXPECT_EQ(result[0], "text/*");
  1067. }
  1068. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1069. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1070. // and must not be answered with 400 Bad Request.
  1071. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1072. struct {
  1073. const char *value;
  1074. std::vector<std::string> expected;
  1075. } cases[] = {
  1076. {",application/json", {"application/json"}},
  1077. {"text/html,", {"text/html"}},
  1078. {"text/html,,*/*", {"text/html", "*/*"}},
  1079. // An empty element may be spelled with whitespace in it
  1080. {"text/html, , application/json", {"text/html", "application/json"}},
  1081. // Nothing but empty elements is an empty list, which means the same
  1082. // thing as no Accept header at all
  1083. {",,,", {}},
  1084. // Quality values still apply across ignored empty elements
  1085. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1086. };
  1087. for (const auto &c : cases) {
  1088. std::vector<std::string> result;
  1089. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1090. << "value: " << c.value;
  1091. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1092. }
  1093. // An invalid entry is still rejected when empty elements surround it
  1094. std::vector<std::string> result;
  1095. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1096. }
  1097. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1098. // or ';' inside one does not end the list element or the parameter. Section
  1099. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1100. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1101. struct {
  1102. const char *value;
  1103. std::vector<std::string> expected;
  1104. } cases[] = {
  1105. {"text/html;profile=\"a,b\",application/json",
  1106. {"text/html", "application/json"}},
  1107. // A "q=" inside a quoted value is not the weight
  1108. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1109. {"text/html", "application/json"}},
  1110. // The weight after a quoted value still applies
  1111. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1112. {"application/json", "text/html"}},
  1113. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1114. {"application/json", "text/html"}},
  1115. {"text/html;profile=\"a\\\"b\",application/json",
  1116. {"text/html", "application/json"}},
  1117. // An escaped backslash does not escape the '"' after it
  1118. {"text/html;profile=\"a\\\\\",application/json",
  1119. {"text/html", "application/json"}},
  1120. };
  1121. for (const auto &c : cases) {
  1122. std::vector<std::string> result;
  1123. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1124. << "value: " << c.value;
  1125. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1126. }
  1127. }
  1128. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1129. Server svr;
  1130. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1131. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1132. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1133. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1134. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1135. res.set_content("ok", "text/plain");
  1136. });
  1137. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1138. EXPECT_TRUE(false);
  1139. res.set_content("bad request", "text/plain");
  1140. });
  1141. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1142. auto se = detail::scope_exit([&] {
  1143. svr.stop();
  1144. listen_thread.join();
  1145. ASSERT_FALSE(svr.is_running());
  1146. });
  1147. svr.wait_until_ready();
  1148. Client cli("localhost", PORT);
  1149. {
  1150. auto res = cli.Get(
  1151. "/accept_ok",
  1152. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1154. EXPECT_EQ(StatusCode::OK_200, res->status);
  1155. }
  1156. {
  1157. auto res = cli.Get("/accept_bad_request",
  1158. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1160. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1161. }
  1162. }
  1163. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1164. Server svr;
  1165. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1166. res.set_content("ok", "text/plain");
  1167. });
  1168. std::atomic<int> start_count{0};
  1169. std::atomic<bool> running_when_called{false};
  1170. svr.set_start_handler([&]() {
  1171. running_when_called = svr.is_running();
  1172. start_count++;
  1173. });
  1174. auto port = svr.bind_to_any_port(HOST);
  1175. std::thread t([&]() { svr.listen_after_bind(); });
  1176. auto se = detail::scope_exit([&] {
  1177. svr.stop();
  1178. t.join();
  1179. ASSERT_FALSE(svr.is_running());
  1180. });
  1181. svr.wait_until_ready();
  1182. // A successful request proves the accept loop is running, which the start
  1183. // handler precedes; so by now the handler must have run exactly once.
  1184. Client cli(HOST, port);
  1185. cli.set_connection_timeout(std::chrono::seconds(5));
  1186. auto res = cli.Get("/");
  1187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1188. EXPECT_EQ(StatusCode::OK_200, res->status);
  1189. EXPECT_EQ(1, start_count.load());
  1190. EXPECT_TRUE(running_when_called.load());
  1191. }
  1192. TEST(DivideTest, DivideStringTests) {
  1193. auto divide = [](const std::string &str, char d) {
  1194. std::string lhs;
  1195. std::string rhs;
  1196. detail::divide(str, d,
  1197. [&](const char *lhs_data, std::size_t lhs_size,
  1198. const char *rhs_data, std::size_t rhs_size) {
  1199. lhs.assign(lhs_data, lhs_size);
  1200. rhs.assign(rhs_data, rhs_size);
  1201. });
  1202. return std::make_pair(std::move(lhs), std::move(rhs));
  1203. };
  1204. {
  1205. const auto res = divide("", '=');
  1206. EXPECT_EQ(res.first, "");
  1207. EXPECT_EQ(res.second, "");
  1208. }
  1209. {
  1210. const auto res = divide("=", '=');
  1211. EXPECT_EQ(res.first, "");
  1212. EXPECT_EQ(res.second, "");
  1213. }
  1214. {
  1215. const auto res = divide(" ", '=');
  1216. EXPECT_EQ(res.first, " ");
  1217. EXPECT_EQ(res.second, "");
  1218. }
  1219. {
  1220. const auto res = divide("a", '=');
  1221. EXPECT_EQ(res.first, "a");
  1222. EXPECT_EQ(res.second, "");
  1223. }
  1224. {
  1225. const auto res = divide("a=", '=');
  1226. EXPECT_EQ(res.first, "a");
  1227. EXPECT_EQ(res.second, "");
  1228. }
  1229. {
  1230. const auto res = divide("=b", '=');
  1231. EXPECT_EQ(res.first, "");
  1232. EXPECT_EQ(res.second, "b");
  1233. }
  1234. {
  1235. const auto res = divide("a=b", '=');
  1236. EXPECT_EQ(res.first, "a");
  1237. EXPECT_EQ(res.second, "b");
  1238. }
  1239. {
  1240. const auto res = divide("a=b=", '=');
  1241. EXPECT_EQ(res.first, "a");
  1242. EXPECT_EQ(res.second, "b=");
  1243. }
  1244. {
  1245. const auto res = divide("a=b=c", '=');
  1246. EXPECT_EQ(res.first, "a");
  1247. EXPECT_EQ(res.second, "b=c");
  1248. }
  1249. }
  1250. TEST(SplitTest, ParseQueryString) {
  1251. string s = "key1=val1&key2=val2&key3=val3";
  1252. Params dic;
  1253. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1254. [&](const char *b, const char *e) {
  1255. string key, val;
  1256. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1257. if (key.empty()) {
  1258. key.assign(b2, e2);
  1259. } else {
  1260. val.assign(b2, e2);
  1261. }
  1262. });
  1263. dic.emplace(key, val);
  1264. });
  1265. EXPECT_EQ("val1", dic.find("key1")->second);
  1266. EXPECT_EQ("val2", dic.find("key2")->second);
  1267. EXPECT_EQ("val3", dic.find("key3")->second);
  1268. }
  1269. TEST(SplitTest, ParseInvalidQueryTests) {
  1270. {
  1271. string s = " ";
  1272. Params dict;
  1273. detail::parse_query_text(s, dict);
  1274. EXPECT_TRUE(dict.empty());
  1275. }
  1276. {
  1277. string s = " = =";
  1278. Params dict;
  1279. detail::parse_query_text(s, dict);
  1280. EXPECT_TRUE(dict.empty());
  1281. }
  1282. }
  1283. TEST(ParseQueryTest, ParseQueryString) {
  1284. {
  1285. std::string s = "key1=val1&key2=val2&key3=val3";
  1286. Params dic;
  1287. detail::parse_query_text(s, dic);
  1288. EXPECT_EQ("val1", dic.find("key1")->second);
  1289. EXPECT_EQ("val2", dic.find("key2")->second);
  1290. EXPECT_EQ("val3", dic.find("key3")->second);
  1291. }
  1292. {
  1293. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1294. Params dic;
  1295. detail::parse_query_text(s, dic);
  1296. EXPECT_EQ("", dic.find("key1")->second);
  1297. EXPECT_EQ("val1", dic.find("key2")->second);
  1298. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1299. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1300. }
  1301. }
  1302. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1303. Params dic;
  1304. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1305. dic.emplace("key1", "val1");
  1306. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1307. dic.emplace("key2", "val2");
  1308. dic.emplace("key3", "val3");
  1309. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1310. }
  1311. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1312. Params params;
  1313. params.emplace("a", "1");
  1314. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1315. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1316. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1317. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1318. // Long enough to overflow the stack when matched with std::regex.
  1319. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1320. EXPECT_EQ("/p?" + long_query + "&a=1",
  1321. append_query_params("/p?" + long_query, params));
  1322. }
  1323. // Joins every entry of a Headers or Params into "key=value " so a whole
  1324. // traversal can be compared in one assertion. Both are instantiations of the
  1325. // same insertion-ordered container, so one helper serves both.
  1326. template <typename Map> static std::string entries_to_string(const Map &m) {
  1327. std::string s;
  1328. for (const auto &entry : m) {
  1329. s += entry.first + "=" + entry.second + " ";
  1330. }
  1331. return s;
  1332. }
  1333. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1334. // Params used to be a std::multimap, which sorted by name and handed the
  1335. // caller's query back alphabetised. A client signing its query string could
  1336. // not reproduce the order it asked for.
  1337. Params dic;
  1338. dic.emplace("zulu", "1");
  1339. dic.emplace("alpha", "2");
  1340. dic.emplace("mike", "3");
  1341. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1342. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1343. }
  1344. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1345. Params dic;
  1346. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1347. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1348. }
  1349. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1350. Request req;
  1351. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1352. req.params);
  1353. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1354. EXPECT_EQ("first", req.get_param_value("tag"));
  1355. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1356. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1357. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1358. EXPECT_EQ("", req.get_param_value("tag", 3));
  1359. }
  1360. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1361. // Params shares its container with Headers, which matches field names
  1362. // case-insensitively. Parameter names must not pick that up.
  1363. Params dic;
  1364. dic.emplace("Key", "upper");
  1365. dic.emplace("key", "lower");
  1366. EXPECT_EQ(2U, dic.size());
  1367. EXPECT_EQ(1U, dic.count("Key"));
  1368. EXPECT_EQ(1U, dic.count("key"));
  1369. EXPECT_EQ("upper", dic.find("Key")->second);
  1370. EXPECT_EQ("lower", dic.find("key")->second);
  1371. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1372. }
  1373. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1374. Server svr;
  1375. std::string order;
  1376. svr.Get("/order", [&](const Request &req, Response &res) {
  1377. order = entries_to_string(req.params);
  1378. res.set_content("ok", "text/plain");
  1379. });
  1380. auto port = svr.bind_to_any_port(HOST);
  1381. thread t = thread([&] { svr.listen_after_bind(); });
  1382. auto se = detail::scope_exit([&] {
  1383. svr.stop();
  1384. t.join();
  1385. ASSERT_FALSE(svr.is_running());
  1386. });
  1387. svr.wait_until_ready();
  1388. Client cli(HOST, port);
  1389. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1390. ASSERT_TRUE(res);
  1391. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1392. }
  1393. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1394. Server svr;
  1395. std::string field_order, file_order;
  1396. svr.Post("/order", [&](const Request &req, Response &res) {
  1397. for (const auto &field : req.form.fields) {
  1398. field_order += field.first + "=" + field.second.content + " ";
  1399. }
  1400. for (const auto &file : req.form.files) {
  1401. file_order += file.first + "=" + file.second.filename + " ";
  1402. }
  1403. res.set_content("ok", "text/plain");
  1404. });
  1405. auto port = svr.bind_to_any_port(HOST);
  1406. thread t = thread([&] { svr.listen_after_bind(); });
  1407. auto se = detail::scope_exit([&] {
  1408. svr.stop();
  1409. t.join();
  1410. ASSERT_FALSE(svr.is_running());
  1411. });
  1412. svr.wait_until_ready();
  1413. UploadFormDataItems items = {
  1414. {"zulu", "1", "", ""},
  1415. {"alpha", "2", "", ""},
  1416. {"mike", "3", "", ""},
  1417. {"zebra", "z", "z.txt", "text/plain"},
  1418. {"apple", "a", "a.txt", "text/plain"},
  1419. };
  1420. Client cli(HOST, port);
  1421. auto res = cli.Post("/order", items);
  1422. ASSERT_TRUE(res);
  1423. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1424. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1425. }
  1426. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1427. Server svr;
  1428. std::vector<std::string> values;
  1429. std::string first, second, out_of_range, order;
  1430. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1431. values = req.form.get_fields("tag");
  1432. first = req.form.get_field("tag", 0);
  1433. second = req.form.get_field("tag", 1);
  1434. out_of_range = req.form.get_field("tag", 2);
  1435. for (const auto &field : req.form.fields) {
  1436. order += field.first + "=" + field.second.content + " ";
  1437. }
  1438. res.set_content("ok", "text/plain");
  1439. });
  1440. auto port = svr.bind_to_any_port(HOST);
  1441. thread t = thread([&] { svr.listen_after_bind(); });
  1442. auto se = detail::scope_exit([&] {
  1443. svr.stop();
  1444. t.join();
  1445. ASSERT_FALSE(svr.is_running());
  1446. });
  1447. svr.wait_until_ready();
  1448. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1449. // not adjacent in the container.
  1450. UploadFormDataItems items = {
  1451. {"tag", "first", "", ""},
  1452. {"other", "x", "", ""},
  1453. {"tag", "second", "", ""},
  1454. };
  1455. Client cli(HOST, port);
  1456. auto res = cli.Post("/repeated", items);
  1457. ASSERT_TRUE(res);
  1458. ASSERT_EQ(2U, values.size());
  1459. EXPECT_EQ("first", values[0]);
  1460. EXPECT_EQ("second", values[1]);
  1461. EXPECT_EQ("first", first);
  1462. EXPECT_EQ("second", second);
  1463. // std::multimap already kept entries sharing a name in insertion order, so
  1464. // everything above passes without this change too. The whole traversal is
  1465. // what tells the two apart: sorting by name would hoist "other" to the front
  1466. // and the two "tag" parts would end up adjacent.
  1467. EXPECT_EQ("tag=first other=x tag=second ", order);
  1468. // Advancing past the last entry of a name used to run off the container;
  1469. // the container's saturating increment makes it return the default instead.
  1470. EXPECT_EQ("", out_of_range);
  1471. }
  1472. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1473. Server svr;
  1474. std::string file_names;
  1475. svr.Post("/upload", [&](const Request &req, Response &res) {
  1476. for (const auto &file : req.form.files) {
  1477. file_names += file.first + "|" + file.second.filename + " ";
  1478. }
  1479. res.set_content("ok", "text/plain");
  1480. });
  1481. auto port = svr.bind_to_any_port(HOST);
  1482. thread t = thread([&] { svr.listen_after_bind(); });
  1483. auto se = detail::scope_exit([&] {
  1484. svr.stop();
  1485. t.join();
  1486. ASSERT_FALSE(svr.is_running());
  1487. });
  1488. svr.wait_until_ready();
  1489. // A trailing backslash would otherwise escape the closing quote.
  1490. UploadFormDataItems items = {
  1491. {"dir\\", "x", "a.txt", "text/plain"},
  1492. {"b", "y", "a\\\\b.txt", "text/plain"},
  1493. };
  1494. Client cli(HOST, port);
  1495. auto res = cli.Post("/upload", items);
  1496. ASSERT_TRUE(res);
  1497. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1498. }
  1499. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1500. // Server::read_content() keeps a FormFields::iterator alive across the
  1501. // content callbacks that fill the part it points at. The container is
  1502. // vector-backed, so a later emplace can reallocate and invalidate an older
  1503. // iterator; 64 parts grow the vector through seven reallocations, which
  1504. // checks that every part's content still lands in its own entry.
  1505. const size_t part_count = 64;
  1506. // One formula for both the parts sent and the values expected back, so the
  1507. // two cannot drift apart.
  1508. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1509. auto content_of = [](size_t i) {
  1510. return std::string(64, static_cast<char>('a' + (i % 26)));
  1511. };
  1512. Server svr;
  1513. std::vector<std::pair<std::string, std::string>> received;
  1514. svr.Post("/many", [&](const Request &req, Response &res) {
  1515. for (const auto &field : req.form.fields) {
  1516. received.emplace_back(field.first, field.second.content);
  1517. }
  1518. res.set_content("ok", "text/plain");
  1519. });
  1520. auto port = svr.bind_to_any_port(HOST);
  1521. thread t = thread([&] { svr.listen_after_bind(); });
  1522. auto se = detail::scope_exit([&] {
  1523. svr.stop();
  1524. t.join();
  1525. ASSERT_FALSE(svr.is_running());
  1526. });
  1527. svr.wait_until_ready();
  1528. UploadFormDataItems items;
  1529. for (size_t i = 0; i < part_count; i++) {
  1530. items.push_back({name_of(i), content_of(i), "", ""});
  1531. }
  1532. Client cli(HOST, port);
  1533. auto res = cli.Post("/many", items);
  1534. ASSERT_TRUE(res);
  1535. ASSERT_EQ(part_count, received.size());
  1536. for (size_t i = 0; i < part_count; i++) {
  1537. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1538. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1539. }
  1540. }
  1541. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1542. string content_type = "multipart/form-data; boundary=something";
  1543. string boundary;
  1544. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1545. EXPECT_TRUE(ret);
  1546. EXPECT_EQ(boundary, "something");
  1547. }
  1548. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1549. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1550. string boundary;
  1551. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1552. EXPECT_TRUE(ret);
  1553. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1554. }
  1555. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1556. string content_type =
  1557. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1558. string boundary;
  1559. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1560. EXPECT_TRUE(ret);
  1561. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1562. }
  1563. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1564. string content_type =
  1565. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1566. string boundary;
  1567. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1568. EXPECT_TRUE(ret);
  1569. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1570. }
  1571. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1572. const string boundary(70, 'a');
  1573. string content_type = "multipart/form-data; boundary=" + boundary;
  1574. string parsed;
  1575. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1576. EXPECT_TRUE(ret);
  1577. EXPECT_EQ(parsed, boundary);
  1578. }
  1579. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1580. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1581. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1582. string parsed;
  1583. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1584. EXPECT_FALSE(ret);
  1585. }
  1586. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1587. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1588. // is 72 characters on the wire and still valid.
  1589. const string boundary(70, 'a');
  1590. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1591. string parsed;
  1592. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1593. EXPECT_EQ(parsed, boundary);
  1594. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1595. parsed.clear();
  1596. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1597. }
  1598. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1599. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1600. // The parameter parser must not treat that '=' as the key/value separator.
  1601. string content_type =
  1602. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1603. "charset=UTF-8";
  1604. string parsed;
  1605. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1606. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1607. }
  1608. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1609. // A ';' inside the quoted-string is part of the value, not a parameter
  1610. // separator, so it must not truncate the boundary.
  1611. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1612. string parsed;
  1613. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1614. EXPECT_EQ(parsed, "a;b");
  1615. }
  1616. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1617. string parsed;
  1618. EXPECT_TRUE(detail::parse_multipart_boundary(
  1619. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1620. EXPECT_EQ("a\\b", parsed);
  1621. EXPECT_TRUE(detail::parse_multipart_boundary(
  1622. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1623. EXPECT_EQ("a\"b", parsed);
  1624. }
  1625. TEST(ParseDispositionParamsTest, QuotedValues) {
  1626. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1627. // ';' and '=' are ordinary characters inside one.
  1628. struct {
  1629. const char *value;
  1630. std::vector<std::pair<const char *, const char *>> expected;
  1631. } cases[] = {
  1632. {"name=\"file1\"; filename=\"a.txt\"",
  1633. {{"name", "file1"}, {"filename", "a.txt"}}},
  1634. // Whitespace around '=' and ';' is still trimmed
  1635. {"name=\"file2\" ;filename = \"a.html\"",
  1636. {{"name", "file2"}, {"filename", "a.html"}}},
  1637. // '=' inside the value used to leave only the text after the last one
  1638. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1639. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1640. {"name=\"x=y\"", {{"name", "x=y"}}},
  1641. // ';' inside the value used to truncate the pair and leave a bogus one
  1642. {"name=\"file3\"; filename=\"a;b.txt\"",
  1643. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1644. // An unquoted value keeps working, and so does filename*
  1645. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1646. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1647. // A parameter with no key is dropped rather than turned into one whose
  1648. // key is the value
  1649. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1650. // An escaped quote does not end the value
  1651. {"name=\"a\\\"; filename=evil.php\"",
  1652. {{"name", "a\"; filename=evil.php"}}},
  1653. // Other backslashes, as in a Windows path, are kept
  1654. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1655. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1656. };
  1657. for (const auto &c : cases) {
  1658. Params params;
  1659. detail::parse_disposition_params(c.value, params);
  1660. for (const auto &kv : c.expected) {
  1661. auto it = params.find(kv.first);
  1662. ASSERT_NE(it, params.end())
  1663. << "value: " << c.value << ", key: " << kv.first;
  1664. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1665. }
  1666. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1667. }
  1668. }
  1669. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1670. Server svr;
  1671. std::string filename;
  1672. std::string content;
  1673. svr.Post("/upload", [&](const Request &req, Response &) {
  1674. const auto &file = req.form.get_file("file");
  1675. filename = file.filename;
  1676. content = file.content;
  1677. });
  1678. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1679. auto se = detail::scope_exit([&] {
  1680. svr.stop();
  1681. thread.join();
  1682. ASSERT_FALSE(svr.is_running());
  1683. });
  1684. svr.wait_until_ready();
  1685. std::string body = "--B\r\n"
  1686. "Content-Disposition: form-data; name=\"file\"; "
  1687. "filename=\"a.txt\"\r\n"
  1688. "Content-Type: text/plain\r\n"
  1689. "\r\n"
  1690. "hello\r\n"
  1691. "--B--\r\n";
  1692. Client cli(HOST, PORT);
  1693. auto res = cli.Post(
  1694. "/upload",
  1695. [&](size_t offset, DataSink &sink) {
  1696. if (offset < body.size()) {
  1697. sink.write(&body[offset], 1);
  1698. } else {
  1699. sink.done();
  1700. }
  1701. return true;
  1702. },
  1703. "multipart/form-data; boundary=B");
  1704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1705. EXPECT_EQ(StatusCode::OK_200, res->status);
  1706. EXPECT_EQ("a.txt", filename);
  1707. EXPECT_EQ("hello", content);
  1708. }
  1709. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1710. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1711. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1712. Server svr;
  1713. std::string field_value, file_name, file_filename;
  1714. bool has_field = false, has_file = false;
  1715. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1716. has_field = req.form.has_field("x=y");
  1717. field_value = req.form.get_field("x=y");
  1718. has_file = req.form.has_file("file1");
  1719. const auto &file = req.form.get_file("file1");
  1720. file_name = file.name;
  1721. file_filename = file.filename;
  1722. res.set_content("ok", "text/plain");
  1723. });
  1724. auto port = svr.bind_to_any_port(HOST);
  1725. thread t = thread([&] { svr.listen_after_bind(); });
  1726. auto se = detail::scope_exit([&] {
  1727. svr.stop();
  1728. t.join();
  1729. ASSERT_FALSE(svr.is_running());
  1730. });
  1731. svr.wait_until_ready();
  1732. UploadFormDataItems items = {
  1733. {"x=y", "field-value", "", ""},
  1734. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1735. };
  1736. Client cli(HOST, port);
  1737. auto res = cli.Post("/quoted", items);
  1738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1739. ASSERT_EQ(StatusCode::OK_200, res->status);
  1740. EXPECT_TRUE(has_field);
  1741. EXPECT_EQ("field-value", field_value);
  1742. EXPECT_TRUE(has_file);
  1743. EXPECT_EQ("file1", file_name);
  1744. EXPECT_EQ("a;b=report.pdf", file_filename);
  1745. }
  1746. TEST(GetHeaderValueTest, DefaultValue) {
  1747. Headers headers = {{"Dummy", "Dummy"}};
  1748. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1749. EXPECT_STREQ("text/plain", val);
  1750. }
  1751. TEST(GetHeaderValueTest, DefaultValueInt) {
  1752. Headers headers = {{"Dummy", "Dummy"}};
  1753. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1754. EXPECT_EQ(100ull, val);
  1755. }
  1756. TEST(GetHeaderValueTest, RegularValue) {
  1757. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1758. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1759. EXPECT_STREQ("text/html", val);
  1760. }
  1761. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1762. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1763. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1764. EXPECT_STREQ("text/html", val);
  1765. }
  1766. TEST(GetHeaderValueTest, SetContent) {
  1767. Response res;
  1768. res.set_content("html", "text/html");
  1769. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1770. res.set_content("text", "text/plain");
  1771. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1772. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1773. }
  1774. TEST(GetHeaderValueTest, RegularValueInt) {
  1775. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1776. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1777. EXPECT_EQ(100ull, val);
  1778. }
  1779. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1780. Headers headers = {{"Content-Length", "x"}};
  1781. auto is_invalid_value = false;
  1782. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1783. is_invalid_value);
  1784. EXPECT_EQ(0ull, val);
  1785. EXPECT_TRUE(is_invalid_value);
  1786. }
  1787. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1788. // An all-digit value that overflows size_t must be reported as invalid, not
  1789. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1790. // a large length to a small one on 32-bit builds, leaving the framing length
  1791. // wrong while is_invalid_value stayed false.
  1792. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1793. auto is_invalid_value = false;
  1794. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1795. is_invalid_value);
  1796. EXPECT_TRUE(is_invalid_value);
  1797. // A well-formed length is unaffected.
  1798. Headers ok = {{"Content-Length", "1234"}};
  1799. is_invalid_value = false;
  1800. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1801. is_invalid_value);
  1802. EXPECT_EQ(1234ull, val);
  1803. EXPECT_FALSE(is_invalid_value);
  1804. }
  1805. TEST(GetHeaderValueTest, Range) {
  1806. {
  1807. Headers headers = {make_range_header({{1, -1}})};
  1808. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1809. EXPECT_STREQ("bytes=1-", val);
  1810. }
  1811. {
  1812. Headers headers = {make_range_header({{-1, 1}})};
  1813. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1814. EXPECT_STREQ("bytes=-1", val);
  1815. }
  1816. {
  1817. Headers headers = {make_range_header({{1, 10}})};
  1818. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1819. EXPECT_STREQ("bytes=1-10", val);
  1820. }
  1821. {
  1822. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1823. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1824. EXPECT_STREQ("bytes=1-10, 100-", val);
  1825. }
  1826. {
  1827. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1828. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1829. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1830. }
  1831. {
  1832. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1833. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1834. EXPECT_STREQ("bytes=0-0, -1", val);
  1835. }
  1836. }
  1837. TEST(BearerTokenAuthTest, SchemeValidation) {
  1838. // A value shorter than "Bearer " must not throw from the fixed-length
  1839. // substr, and a non-Bearer scheme must not be reported as a token.
  1840. struct {
  1841. const char *value;
  1842. const char *expected;
  1843. } cases[] = {
  1844. {"x", ""},
  1845. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1846. {"Bearer abc123", "abc123"},
  1847. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1848. };
  1849. for (const auto &c : cases) {
  1850. Request req;
  1851. req.set_header("Authorization", c.value);
  1852. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1853. }
  1854. }
  1855. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1856. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1857. // to depend on the standard library (libstdc++ handed back duplicates in
  1858. // reverse insertion order, libc++ in insertion order).
  1859. Request req;
  1860. req.set_header("Accept-Encoding", "gzip");
  1861. req.set_header("Accept-Encoding", "deflate");
  1862. req.set_header("Accept-Encoding", "br");
  1863. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1864. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1865. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1866. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1867. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1868. }
  1869. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1870. Request req;
  1871. req.set_header("X-Test", "only");
  1872. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1873. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1874. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1875. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1876. }
  1877. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1878. Request req;
  1879. req.set_header("X-First", "1");
  1880. req.set_header("X-Test", "2");
  1881. req.params.emplace("first", "1");
  1882. req.params.emplace("test", "2");
  1883. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1884. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1885. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1886. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1887. // The second one is negative when read as a signed value
  1888. const auto max_id = (std::numeric_limits<size_t>::max)();
  1889. for (auto id : {max_id / 2, max_id}) {
  1890. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1891. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1892. EXPECT_EQ("", req.get_param_value("test", id));
  1893. EXPECT_EQ("", req.form.get_field("test", id));
  1894. EXPECT_EQ("", req.form.get_file("test", id).content);
  1895. }
  1896. }
  1897. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1898. Headers headers;
  1899. headers.emplace("Host", "example.com");
  1900. headers.emplace("Accept-Encoding", "gzip");
  1901. headers.emplace("User-Agent", "test");
  1902. headers.emplace("Accept-Encoding", "deflate");
  1903. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1904. "Accept-Encoding=deflate ",
  1905. entries_to_string(headers));
  1906. }
  1907. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1908. Headers headers = {{"Content-Type", "text/html"},
  1909. {"CONTENT-TYPE", "text/xml"}};
  1910. EXPECT_EQ(2U, headers.count("content-type"));
  1911. auto it = headers.find("content-type");
  1912. ASSERT_TRUE(it != headers.end());
  1913. EXPECT_EQ("text/html", it->second);
  1914. }
  1915. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1916. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1917. // drop only those fields and leave everything positioned between them.
  1918. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1919. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1920. auto rng = headers.equal_range("a");
  1921. headers.erase(rng.first, rng.second);
  1922. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1923. }
  1924. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1925. Headers headers = {
  1926. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1927. EXPECT_EQ(3U, headers.erase("A"));
  1928. EXPECT_EQ(0U, headers.count("A"));
  1929. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1930. }
  1931. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1932. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1933. headers.emplace_front("Host", "example.com");
  1934. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1935. entries_to_string(headers));
  1936. }
  1937. TEST(ParseHeaderValueTest, Range) {
  1938. {
  1939. Ranges ranges;
  1940. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1941. EXPECT_TRUE(ret);
  1942. EXPECT_EQ(1u, ranges.size());
  1943. EXPECT_EQ(1u, ranges[0].first);
  1944. EXPECT_EQ(-1, ranges[0].second);
  1945. }
  1946. {
  1947. Ranges ranges;
  1948. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1949. EXPECT_TRUE(ret);
  1950. EXPECT_EQ(1u, ranges.size());
  1951. EXPECT_EQ(-1, ranges[0].first);
  1952. EXPECT_EQ(1u, ranges[0].second);
  1953. }
  1954. {
  1955. Ranges ranges;
  1956. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1957. EXPECT_TRUE(ret);
  1958. EXPECT_EQ(1u, ranges.size());
  1959. EXPECT_EQ(1u, ranges[0].first);
  1960. EXPECT_EQ(10u, ranges[0].second);
  1961. }
  1962. {
  1963. Ranges ranges;
  1964. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1965. EXPECT_FALSE(ret);
  1966. }
  1967. {
  1968. Ranges ranges;
  1969. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1970. EXPECT_TRUE(ret);
  1971. EXPECT_EQ(2u, ranges.size());
  1972. EXPECT_EQ(1u, ranges[0].first);
  1973. EXPECT_EQ(10u, ranges[0].second);
  1974. EXPECT_EQ(100u, ranges[1].first);
  1975. EXPECT_EQ(-1, ranges[1].second);
  1976. }
  1977. {
  1978. Ranges ranges;
  1979. auto ret =
  1980. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1981. EXPECT_TRUE(ret);
  1982. EXPECT_EQ(3u, ranges.size());
  1983. EXPECT_EQ(1u, ranges[0].first);
  1984. EXPECT_EQ(10u, ranges[0].second);
  1985. EXPECT_EQ(100u, ranges[1].first);
  1986. EXPECT_EQ(200u, ranges[1].second);
  1987. EXPECT_EQ(300u, ranges[2].first);
  1988. EXPECT_EQ(400u, ranges[2].second);
  1989. }
  1990. {
  1991. Ranges ranges;
  1992. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1993. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1994. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1995. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1996. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1997. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1998. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1999. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  2000. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2001. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2002. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2003. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2004. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2005. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2006. EXPECT_FALSE(
  2007. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2008. EXPECT_TRUE(ranges.empty());
  2009. }
  2010. {
  2011. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2012. // remainder of the representation, so it stays accepted.
  2013. Ranges ranges;
  2014. auto ret =
  2015. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2016. EXPECT_TRUE(ret);
  2017. ASSERT_EQ(1u, ranges.size());
  2018. EXPECT_EQ(0, ranges[0].first);
  2019. EXPECT_EQ(-1, ranges[0].second);
  2020. }
  2021. // RFC 9110 14.1: range unit names are case-insensitive.
  2022. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2023. Ranges ranges;
  2024. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2025. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2026. }
  2027. }
  2028. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2029. Request req;
  2030. req.set_header("Accept-Encoding", "gzip");
  2031. Response res;
  2032. res.set_header("Content-Type", "text/plain");
  2033. auto ret = detail::encoding_type(req, res);
  2034. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2035. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2036. #else
  2037. EXPECT_TRUE(ret == detail::EncodingType::None);
  2038. #endif
  2039. }
  2040. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2041. Request req;
  2042. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2043. Response res;
  2044. res.set_header("Content-Type", "text/plain");
  2045. auto ret = detail::encoding_type(req, res);
  2046. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2047. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2048. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2049. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2050. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2051. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2052. #else
  2053. EXPECT_TRUE(ret == detail::EncodingType::None);
  2054. #endif
  2055. }
  2056. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2057. Request req;
  2058. req.set_header("Accept-Encoding",
  2059. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2060. Response res;
  2061. res.set_header("Content-Type", "text/plain");
  2062. auto ret = detail::encoding_type(req, res);
  2063. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2064. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2065. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2066. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2067. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2068. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2069. #else
  2070. EXPECT_TRUE(ret == detail::EncodingType::None);
  2071. #endif
  2072. }
  2073. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2074. // All supported encodings rejected with q=0 should return None
  2075. Request req;
  2076. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2077. Response res;
  2078. res.set_header("Content-Type", "text/plain");
  2079. auto ret = detail::encoding_type(req, res);
  2080. EXPECT_TRUE(ret == detail::EncodingType::None);
  2081. }
  2082. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2083. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2084. Request req;
  2085. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2086. Response res;
  2087. res.set_header("Content-Type", "text/plain");
  2088. auto ret = detail::encoding_type(req, res);
  2089. EXPECT_TRUE(ret == detail::EncodingType::None);
  2090. }
  2091. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2092. Request req;
  2093. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2094. Response res;
  2095. res.set_header("Content-Type", "text/plain");
  2096. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2097. }
  2098. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2099. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2100. Request req;
  2101. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2102. Response res;
  2103. res.set_header("Content-Type", "text/plain");
  2104. auto ret = detail::encoding_type(req, res);
  2105. EXPECT_TRUE(ret == detail::EncodingType::None);
  2106. }
  2107. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2108. // RFC 7231: Accept-Encoding values are case-insensitive
  2109. Request req;
  2110. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2111. Response res;
  2112. res.set_header("Content-Type", "text/plain");
  2113. auto ret = detail::encoding_type(req, res);
  2114. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2115. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2116. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2117. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2118. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2119. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2120. #else
  2121. EXPECT_TRUE(ret == detail::EncodingType::None);
  2122. #endif
  2123. }
  2124. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2125. // q value should determine priority, not hardcoded order
  2126. Request req;
  2127. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2128. Response res;
  2129. res.set_header("Content-Type", "text/plain");
  2130. auto ret = detail::encoding_type(req, res);
  2131. // gzip has highest q=1.0, so it should be selected even though
  2132. // br and zstd are also supported
  2133. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2134. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2135. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2136. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2137. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2138. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2139. #else
  2140. EXPECT_TRUE(ret == detail::EncodingType::None);
  2141. #endif
  2142. }
  2143. TEST(BufferStreamTest, read) {
  2144. detail::BufferStream strm1;
  2145. Stream &strm = strm1;
  2146. EXPECT_EQ(5, strm.write("hello"));
  2147. char buf[512];
  2148. EXPECT_EQ(2, strm.read(buf, 2));
  2149. EXPECT_EQ('h', buf[0]);
  2150. EXPECT_EQ('e', buf[1]);
  2151. EXPECT_EQ(2, strm.read(buf, 2));
  2152. EXPECT_EQ('l', buf[0]);
  2153. EXPECT_EQ('l', buf[1]);
  2154. EXPECT_EQ(1, strm.read(buf, 1));
  2155. EXPECT_EQ('o', buf[0]);
  2156. EXPECT_EQ(0, strm.read(buf, 1));
  2157. }
  2158. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2159. auto host = "www.httpwatch.com";
  2160. auto ip = hosted_at(host);
  2161. EXPECT_EQ("23.96.13.243", ip);
  2162. std::vector<std::string> addrs;
  2163. hosted_at(host, addrs);
  2164. EXPECT_EQ(1u, addrs.size());
  2165. }
  2166. #if 0 // It depends on each test environment...
  2167. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2168. auto host = "www.youtube.com";
  2169. std::vector<std::string> addrs;
  2170. hosted_at(host, addrs);
  2171. EXPECT_EQ(20u, addrs.size());
  2172. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2173. EXPECT_TRUE(it != addrs.end());
  2174. }
  2175. #endif
  2176. class ChunkedEncodingTest : public ::testing::Test {
  2177. protected:
  2178. ChunkedEncodingTest()
  2179. : cli_(HOST, PORT)
  2180. #ifdef CPPHTTPLIB_SSL_ENABLED
  2181. ,
  2182. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2183. #endif
  2184. {
  2185. cli_.set_connection_timeout(2);
  2186. #ifdef CPPHTTPLIB_SSL_ENABLED
  2187. cli_.enable_server_certificate_verification(false);
  2188. #endif
  2189. }
  2190. virtual void SetUp() {
  2191. read_file("./image.jpg", image_data_);
  2192. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2193. res.set_content("Hello World!", "text/plain");
  2194. });
  2195. svr_.Get(
  2196. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2197. res.set_chunked_content_provider(
  2198. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2199. size_t remaining = image_data_.size() - offset;
  2200. if (remaining == 0) {
  2201. sink.done();
  2202. } else {
  2203. constexpr size_t CHUNK_SIZE = 1024;
  2204. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2205. sink.write(&image_data_[offset], send_size);
  2206. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2207. }
  2208. return true;
  2209. });
  2210. });
  2211. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2212. svr_.wait_until_ready();
  2213. }
  2214. virtual void TearDown() {
  2215. svr_.stop();
  2216. if (!request_threads_.empty()) {
  2217. std::this_thread::sleep_for(std::chrono::seconds(1));
  2218. for (auto &t : request_threads_) {
  2219. t.join();
  2220. }
  2221. }
  2222. t_.join();
  2223. }
  2224. #ifdef CPPHTTPLIB_SSL_ENABLED
  2225. SSLClient cli_;
  2226. SSLServer svr_;
  2227. #else
  2228. Client cli_;
  2229. Server svr_;
  2230. #endif
  2231. thread t_;
  2232. std::vector<thread> request_threads_;
  2233. std::string image_data_;
  2234. };
  2235. TEST_F(ChunkedEncodingTest, NormalGet) {
  2236. auto res = cli_.Get("/chunked");
  2237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2238. std::string out;
  2239. read_file("./image.jpg", out);
  2240. EXPECT_EQ(StatusCode::OK_200, res->status);
  2241. EXPECT_EQ(out, res->body);
  2242. }
  2243. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2244. std::string body;
  2245. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2246. body.append(data, data_length);
  2247. return true;
  2248. });
  2249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2250. std::string out;
  2251. read_file("./image.jpg", out);
  2252. EXPECT_EQ(StatusCode::OK_200, res->status);
  2253. EXPECT_EQ(out, body);
  2254. }
  2255. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2256. std::string body;
  2257. auto res = cli_.Get(
  2258. "/chunked",
  2259. [&](const Response &response) {
  2260. EXPECT_EQ(StatusCode::OK_200, response.status);
  2261. return true;
  2262. },
  2263. [&](const char *data, size_t data_length) {
  2264. body.append(data, data_length);
  2265. return true;
  2266. });
  2267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2268. std::string out;
  2269. read_file("./image.jpg", out);
  2270. EXPECT_EQ(StatusCode::OK_200, res->status);
  2271. EXPECT_EQ(out, body);
  2272. }
  2273. TEST(RangeTest, FromHTTPBin_Online) {
  2274. auto host = "httpbingo.org";
  2275. auto path = std::string{"/range/32"};
  2276. #ifdef CPPHTTPLIB_SSL_ENABLED
  2277. auto port = 443;
  2278. SSLClient cli(host, port);
  2279. #else
  2280. auto port = 80;
  2281. Client cli(host, port);
  2282. #endif
  2283. cli.set_connection_timeout(5);
  2284. {
  2285. auto res = cli.Get(path);
  2286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2287. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2288. EXPECT_EQ(StatusCode::OK_200, res->status);
  2289. }
  2290. {
  2291. Headers headers = {make_range_header({{1, -1}})};
  2292. auto res = cli.Get(path, headers);
  2293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2294. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2295. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2296. }
  2297. {
  2298. Headers headers = {make_range_header({{1, 10}})};
  2299. auto res = cli.Get(path, headers);
  2300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2301. EXPECT_EQ("bcdefghijk", res->body);
  2302. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2303. }
  2304. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2305. // entire resource, while the original httpbin returned 200. Both are
  2306. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2307. {
  2308. Headers headers = {make_range_header({{0, 31}})};
  2309. auto res = cli.Get(path, headers);
  2310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2311. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2312. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2313. res->status == StatusCode::PartialContent_206);
  2314. }
  2315. {
  2316. Headers headers = {make_range_header({{0, -1}})};
  2317. auto res = cli.Get(path, headers);
  2318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2319. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2320. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2321. res->status == StatusCode::PartialContent_206);
  2322. }
  2323. // go-httpbin returns 206 with clamped range for over-range requests,
  2324. // while the original httpbin returned 416. Both behaviors are observed
  2325. // in real servers, so we only verify the request succeeds.
  2326. {
  2327. Headers headers = {make_range_header({{0, 32}})};
  2328. auto res = cli.Get(path, headers);
  2329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2330. }
  2331. }
  2332. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2333. auto host = "unresolvableaddress.local";
  2334. auto path = std::string{"/"};
  2335. #ifdef CPPHTTPLIB_SSL_ENABLED
  2336. auto port = 443;
  2337. SSLClient cli(host, port);
  2338. #else
  2339. auto port = 80;
  2340. Client cli(host, port);
  2341. #endif
  2342. cli.set_connection_timeout(1);
  2343. {
  2344. auto res = cli.Get(path);
  2345. ASSERT_FALSE(res);
  2346. }
  2347. std::this_thread::sleep_for(std::chrono::seconds(8));
  2348. }
  2349. #if defined(__linux__) && defined(__GLIBC__) && \
  2350. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2351. // Forward declaration: in split builds split.py strips `inline` and moves the
  2352. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2353. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2354. // against the symbol in both header-only and split builds.
  2355. namespace httplib {
  2356. namespace detail {
  2357. int getaddrinfo_with_timeout(const char *node, const char *service,
  2358. const struct addrinfo *hints,
  2359. struct addrinfo **res, time_t timeout_sec);
  2360. } // namespace detail
  2361. } // namespace httplib
  2362. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2363. //
  2364. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2365. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2366. // gai_suspend() call hits the connection timeout the function calls
  2367. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2368. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2369. // still alive and still references the now-destroyed stack frame.
  2370. //
  2371. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2372. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2373. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2374. // and runs them in a container.
  2375. namespace {
  2376. bool should_run_issue_2431_tests() {
  2377. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2378. return v && *v && std::string(v) != "0";
  2379. }
  2380. std::string unique_unresolvable_host(int n) {
  2381. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2382. // glibc still asks the configured nameserver — which is exactly the path
  2383. // we want to exercise. A unique label per call avoids the resolver cache.
  2384. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2385. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2386. std::to_string(n) + ".invalid";
  2387. }
  2388. } // namespace
  2389. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2390. if (!should_run_issue_2431_tests()) {
  2391. GTEST_SKIP()
  2392. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2393. }
  2394. for (int i = 0; i < 8; ++i) {
  2395. struct addrinfo hints;
  2396. memset(&hints, 0, sizeof(hints));
  2397. hints.ai_family = AF_UNSPEC;
  2398. hints.ai_socktype = SOCK_STREAM;
  2399. auto host = unique_unresolvable_host(i);
  2400. struct addrinfo *result = nullptr;
  2401. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2402. &result, /*timeout_sec=*/1);
  2403. if (rc == 0 && result) { freeaddrinfo(result); }
  2404. }
  2405. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2406. // stack region they still believe holds their gaicb.
  2407. std::this_thread::sleep_for(std::chrono::seconds(3));
  2408. }
  2409. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2410. if (!should_run_issue_2431_tests()) {
  2411. GTEST_SKIP()
  2412. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2413. }
  2414. std::atomic<bool> stop{false};
  2415. std::vector<std::thread> threads;
  2416. for (int t = 0; t < 8; ++t) {
  2417. threads.emplace_back([t, &stop] {
  2418. int i = 0;
  2419. while (!stop.load(std::memory_order_relaxed)) {
  2420. struct addrinfo hints;
  2421. memset(&hints, 0, sizeof(hints));
  2422. hints.ai_family = AF_UNSPEC;
  2423. hints.ai_socktype = SOCK_STREAM;
  2424. auto host = unique_unresolvable_host(t * 100000 + i++);
  2425. struct addrinfo *result = nullptr;
  2426. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2427. &result, /*timeout_sec=*/1);
  2428. if (rc == 0 && result) { freeaddrinfo(result); }
  2429. }
  2430. });
  2431. }
  2432. std::this_thread::sleep_for(std::chrono::seconds(8));
  2433. stop.store(true, std::memory_order_relaxed);
  2434. for (auto &th : threads) {
  2435. th.join();
  2436. }
  2437. std::this_thread::sleep_for(std::chrono::seconds(3));
  2438. }
  2439. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2440. if (!should_run_issue_2431_tests()) {
  2441. GTEST_SKIP()
  2442. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2443. }
  2444. std::atomic<bool> stop{false};
  2445. std::vector<std::thread> threads;
  2446. for (int t = 0; t < 8; ++t) {
  2447. threads.emplace_back([t, &stop] {
  2448. int i = 0;
  2449. while (!stop.load(std::memory_order_relaxed)) {
  2450. auto host = unique_unresolvable_host(t * 100000 + i++);
  2451. Client cli(host, 80);
  2452. cli.set_connection_timeout(1, 0);
  2453. cli.set_read_timeout(1, 0);
  2454. cli.set_write_timeout(1, 0);
  2455. (void)cli.Get("/");
  2456. }
  2457. });
  2458. }
  2459. std::this_thread::sleep_for(std::chrono::seconds(8));
  2460. stop.store(true, std::memory_order_relaxed);
  2461. for (auto &th : threads) {
  2462. th.join();
  2463. }
  2464. std::this_thread::sleep_for(std::chrono::seconds(3));
  2465. }
  2466. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2467. TEST(ConnectionErrorTest, InvalidHost) {
  2468. auto host = "-abcde.com";
  2469. #ifdef CPPHTTPLIB_SSL_ENABLED
  2470. auto port = 443;
  2471. SSLClient cli(host, port);
  2472. #else
  2473. auto port = 80;
  2474. Client cli(host, port);
  2475. #endif
  2476. cli.set_connection_timeout(std::chrono::seconds(2));
  2477. auto res = cli.Get("/");
  2478. ASSERT_TRUE(!res);
  2479. EXPECT_EQ(Error::Connection, res.error());
  2480. }
  2481. TEST(ConnectionErrorTest, InvalidHost2) {
  2482. auto host = "httpcan.org/";
  2483. #ifdef CPPHTTPLIB_SSL_ENABLED
  2484. SSLClient cli(host);
  2485. #else
  2486. Client cli(host);
  2487. #endif
  2488. cli.set_connection_timeout(std::chrono::seconds(2));
  2489. auto res = cli.Get("/");
  2490. ASSERT_TRUE(!res);
  2491. EXPECT_EQ(Error::Connection, res.error());
  2492. }
  2493. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2494. auto host = "httpcan.org/";
  2495. #ifdef CPPHTTPLIB_SSL_ENABLED
  2496. SSLClient cli(host);
  2497. #else
  2498. Client cli(host);
  2499. #endif
  2500. cli.set_connection_timeout(std::chrono::seconds(2));
  2501. auto res = cli.Get("/");
  2502. ASSERT_TRUE(!res);
  2503. stringstream s;
  2504. s << "error code: " << res.error();
  2505. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2506. }
  2507. TEST(ConnectionErrorTest, InvalidPort) {
  2508. auto host = "localhost";
  2509. auto port = 44380;
  2510. #ifdef CPPHTTPLIB_SSL_ENABLED
  2511. SSLClient cli(host, port);
  2512. #else
  2513. Client cli(host, port);
  2514. #endif
  2515. cli.set_connection_timeout(std::chrono::seconds(2));
  2516. auto res = cli.Get("/");
  2517. ASSERT_TRUE(!res);
  2518. EXPECT_TRUE(Error::Connection == res.error() ||
  2519. Error::ConnectionTimeout == res.error());
  2520. }
  2521. TEST(ConnectionErrorTest, Timeout_Online) {
  2522. auto host = "google.com";
  2523. #ifdef CPPHTTPLIB_SSL_ENABLED
  2524. auto port = 44380;
  2525. SSLClient cli(host, port);
  2526. #else
  2527. auto port = 8080;
  2528. Client cli(host, port);
  2529. #endif
  2530. cli.set_connection_timeout(std::chrono::seconds(2));
  2531. // only probe one address type so that the error reason
  2532. // correlates to the timed-out IPv4, not the unsupported
  2533. // IPv6 connection attempt
  2534. cli.set_address_family(AF_INET);
  2535. auto res = cli.Get("/");
  2536. ASSERT_TRUE(!res);
  2537. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2538. }
  2539. TEST(CancelTest, NoCancel_Online) {
  2540. auto host = "httpbingo.org";
  2541. auto path = std::string{"/range/32"};
  2542. #ifdef CPPHTTPLIB_SSL_ENABLED
  2543. auto port = 443;
  2544. SSLClient cli(host, port);
  2545. #else
  2546. auto port = 80;
  2547. Client cli(host, port);
  2548. #endif
  2549. cli.set_connection_timeout(std::chrono::seconds(5));
  2550. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2552. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2553. EXPECT_EQ(StatusCode::OK_200, res->status);
  2554. }
  2555. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2556. // Use /bytes with a large payload so that the DownloadProgress callback
  2557. // (which only fires for Content-Length responses) is invoked before the
  2558. // entire body is received, giving cancellation a chance to fire.
  2559. auto host = "httpbingo.org";
  2560. auto path = std::string{"/bytes/524288"};
  2561. #ifdef CPPHTTPLIB_SSL_ENABLED
  2562. auto port = 443;
  2563. SSLClient cli(host, port);
  2564. #else
  2565. auto port = 80;
  2566. Client cli(host, port);
  2567. #endif
  2568. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2569. cli.set_connection_timeout(std::chrono::seconds(5));
  2570. ASSERT_TRUE(!res);
  2571. EXPECT_EQ(Error::Canceled, res.error());
  2572. }
  2573. TEST(CancelTest, WithCancelLargePayload_Online) {
  2574. auto host = "httpbingo.org";
  2575. auto path = std::string{"/bytes/524288"};
  2576. #ifdef CPPHTTPLIB_SSL_ENABLED
  2577. auto port = 443;
  2578. SSLClient cli(host, port);
  2579. #else
  2580. auto port = 80;
  2581. Client cli(host, port);
  2582. #endif
  2583. cli.set_connection_timeout(std::chrono::seconds(5));
  2584. uint32_t count = 0;
  2585. auto res =
  2586. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2587. ASSERT_TRUE(!res);
  2588. EXPECT_EQ(Error::Canceled, res.error());
  2589. }
  2590. TEST(CancelTest, NoCancelPost) {
  2591. Server svr;
  2592. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2593. res.set_content("Hello World!", "text/plain");
  2594. });
  2595. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2596. auto se = detail::scope_exit([&] {
  2597. svr.stop();
  2598. thread.join();
  2599. ASSERT_FALSE(svr.is_running());
  2600. });
  2601. svr.wait_until_ready();
  2602. Client cli(HOST, PORT);
  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 true; });
  2607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2608. EXPECT_EQ("Hello World!", res->body);
  2609. EXPECT_EQ(StatusCode::OK_200, res->status);
  2610. }
  2611. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2612. Server svr;
  2613. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2614. res.set_content("Hello World!", "text/plain");
  2615. });
  2616. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2617. auto se = detail::scope_exit([&] {
  2618. svr.stop();
  2619. thread.join();
  2620. ASSERT_FALSE(svr.is_running());
  2621. });
  2622. svr.wait_until_ready();
  2623. Client cli(HOST, PORT);
  2624. cli.set_connection_timeout(std::chrono::seconds(5));
  2625. auto res =
  2626. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2627. "application/json", [](uint64_t, uint64_t) { return false; });
  2628. ASSERT_TRUE(!res);
  2629. EXPECT_EQ(Error::Canceled, res.error());
  2630. }
  2631. TEST(CancelTest, WithCancelLargePayloadPost) {
  2632. Server svr;
  2633. svr.set_payload_max_length(200 * 1024 * 1024);
  2634. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2635. res.set_content(LARGE_DATA, "text/plain");
  2636. });
  2637. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2638. auto se = detail::scope_exit([&] {
  2639. svr.stop();
  2640. thread.join();
  2641. ASSERT_FALSE(svr.is_running());
  2642. });
  2643. svr.wait_until_ready();
  2644. Client cli(HOST, PORT);
  2645. cli.set_payload_max_length(200 * 1024 * 1024);
  2646. cli.set_connection_timeout(std::chrono::seconds(5));
  2647. auto res =
  2648. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2649. "application/json", [](uint64_t, uint64_t) { return false; });
  2650. ASSERT_TRUE(!res);
  2651. EXPECT_EQ(Error::Canceled, res.error());
  2652. }
  2653. TEST(CancelTest, NoCancelPut) {
  2654. Server svr;
  2655. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2656. res.set_content("Hello World!", "text/plain");
  2657. });
  2658. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2659. auto se = detail::scope_exit([&] {
  2660. svr.stop();
  2661. thread.join();
  2662. ASSERT_FALSE(svr.is_running());
  2663. });
  2664. svr.wait_until_ready();
  2665. Client cli(HOST, PORT);
  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 true; });
  2670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2671. EXPECT_EQ("Hello World!", res->body);
  2672. EXPECT_EQ(StatusCode::OK_200, res->status);
  2673. }
  2674. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2675. Server svr;
  2676. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2677. res.set_content("Hello World!", "text/plain");
  2678. });
  2679. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2680. auto se = detail::scope_exit([&] {
  2681. svr.stop();
  2682. thread.join();
  2683. ASSERT_FALSE(svr.is_running());
  2684. });
  2685. svr.wait_until_ready();
  2686. Client cli(HOST, PORT);
  2687. cli.set_connection_timeout(std::chrono::seconds(5));
  2688. auto res =
  2689. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2690. "application/json", [](uint64_t, uint64_t) { return false; });
  2691. ASSERT_TRUE(!res);
  2692. EXPECT_EQ(Error::Canceled, res.error());
  2693. }
  2694. TEST(CancelTest, WithCancelLargePayloadPut) {
  2695. Server svr;
  2696. svr.set_payload_max_length(200 * 1024 * 1024);
  2697. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2698. res.set_content(LARGE_DATA, "text/plain");
  2699. });
  2700. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2701. auto se = detail::scope_exit([&] {
  2702. svr.stop();
  2703. thread.join();
  2704. ASSERT_FALSE(svr.is_running());
  2705. });
  2706. svr.wait_until_ready();
  2707. Client cli(HOST, PORT);
  2708. cli.set_payload_max_length(200 * 1024 * 1024);
  2709. cli.set_connection_timeout(std::chrono::seconds(5));
  2710. auto res =
  2711. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2712. "application/json", [](uint64_t, uint64_t) { return false; });
  2713. ASSERT_TRUE(!res);
  2714. EXPECT_EQ(Error::Canceled, res.error());
  2715. }
  2716. TEST(CancelTest, NoCancelPatch) {
  2717. Server svr;
  2718. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2719. res.set_content("Hello World!", "text/plain");
  2720. });
  2721. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2722. auto se = detail::scope_exit([&] {
  2723. svr.stop();
  2724. thread.join();
  2725. ASSERT_FALSE(svr.is_running());
  2726. });
  2727. svr.wait_until_ready();
  2728. Client cli(HOST, PORT);
  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 true; });
  2733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2734. EXPECT_EQ("Hello World!", res->body);
  2735. EXPECT_EQ(StatusCode::OK_200, res->status);
  2736. }
  2737. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2738. Server svr;
  2739. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2740. res.set_content("Hello World!", "text/plain");
  2741. });
  2742. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2743. auto se = detail::scope_exit([&] {
  2744. svr.stop();
  2745. thread.join();
  2746. ASSERT_FALSE(svr.is_running());
  2747. });
  2748. svr.wait_until_ready();
  2749. Client cli(HOST, PORT);
  2750. cli.set_connection_timeout(std::chrono::seconds(5));
  2751. auto res =
  2752. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2753. "application/json", [](uint64_t, uint64_t) { return false; });
  2754. ASSERT_TRUE(!res);
  2755. EXPECT_EQ(Error::Canceled, res.error());
  2756. }
  2757. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2758. Server svr;
  2759. svr.set_payload_max_length(200 * 1024 * 1024);
  2760. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2761. res.set_content(LARGE_DATA, "text/plain");
  2762. });
  2763. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2764. auto se = detail::scope_exit([&] {
  2765. svr.stop();
  2766. thread.join();
  2767. ASSERT_FALSE(svr.is_running());
  2768. });
  2769. svr.wait_until_ready();
  2770. Client cli(HOST, PORT);
  2771. cli.set_payload_max_length(200 * 1024 * 1024);
  2772. cli.set_connection_timeout(std::chrono::seconds(5));
  2773. auto res =
  2774. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2775. "application/json", [](uint64_t, uint64_t) { return false; });
  2776. ASSERT_TRUE(!res);
  2777. EXPECT_EQ(Error::Canceled, res.error());
  2778. }
  2779. TEST(CancelTest, NoCancelDelete) {
  2780. Server svr;
  2781. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2782. res.set_content("Hello World!", "text/plain");
  2783. });
  2784. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2785. auto se = detail::scope_exit([&] {
  2786. svr.stop();
  2787. thread.join();
  2788. ASSERT_FALSE(svr.is_running());
  2789. });
  2790. svr.wait_until_ready();
  2791. Client cli(HOST, PORT);
  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 true; });
  2796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2797. EXPECT_EQ("Hello World!", res->body);
  2798. EXPECT_EQ(StatusCode::OK_200, res->status);
  2799. }
  2800. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2801. Server svr;
  2802. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2803. res.set_content("Hello World!", "text/plain");
  2804. });
  2805. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2806. auto se = detail::scope_exit([&] {
  2807. svr.stop();
  2808. thread.join();
  2809. ASSERT_FALSE(svr.is_running());
  2810. });
  2811. svr.wait_until_ready();
  2812. Client cli(HOST, PORT);
  2813. cli.set_connection_timeout(std::chrono::seconds(5));
  2814. auto res =
  2815. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2816. "application/json", [](uint64_t, uint64_t) { return false; });
  2817. ASSERT_TRUE(!res);
  2818. EXPECT_EQ(Error::Canceled, res.error());
  2819. }
  2820. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2821. Server svr;
  2822. svr.set_payload_max_length(200 * 1024 * 1024);
  2823. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2824. res.set_content(LARGE_DATA, "text/plain");
  2825. });
  2826. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2827. auto se = detail::scope_exit([&] {
  2828. svr.stop();
  2829. thread.join();
  2830. ASSERT_FALSE(svr.is_running());
  2831. });
  2832. svr.wait_until_ready();
  2833. Client cli(HOST, PORT);
  2834. cli.set_payload_max_length(200 * 1024 * 1024);
  2835. cli.set_connection_timeout(std::chrono::seconds(5));
  2836. auto res =
  2837. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2838. "application/json", [](uint64_t, uint64_t) { return false; });
  2839. ASSERT_TRUE(!res);
  2840. EXPECT_EQ(Error::Canceled, res.error());
  2841. }
  2842. static std::string remove_whitespace(const std::string &input) {
  2843. std::string output;
  2844. output.reserve(input.size());
  2845. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2846. [](unsigned char c) { return !std::isspace(c); });
  2847. return output;
  2848. }
  2849. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2850. auto host = "httpbingo.org";
  2851. auto path = std::string{"/basic-auth/hello/world"};
  2852. #ifdef CPPHTTPLIB_SSL_ENABLED
  2853. auto port = 443;
  2854. SSLClient cli(host, port);
  2855. #else
  2856. auto port = 80;
  2857. Client cli(host, port);
  2858. #endif
  2859. {
  2860. auto res = cli.Get(path);
  2861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2862. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2863. }
  2864. {
  2865. auto res = cli.Get(
  2866. path, Headers{make_basic_authentication_header("hello", "world")});
  2867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2868. auto body = remove_whitespace(res->body);
  2869. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2870. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2871. EXPECT_EQ(StatusCode::OK_200, res->status);
  2872. }
  2873. {
  2874. cli.set_basic_auth("hello", "world");
  2875. auto res = cli.Get(path);
  2876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2877. auto body = remove_whitespace(res->body);
  2878. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2879. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2880. EXPECT_EQ(StatusCode::OK_200, res->status);
  2881. }
  2882. {
  2883. cli.set_basic_auth("hello", "bad");
  2884. auto res = cli.Get(path);
  2885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2886. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2887. }
  2888. {
  2889. cli.set_basic_auth("bad", "world");
  2890. auto res = cli.Get(path);
  2891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2892. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2893. }
  2894. }
  2895. #ifdef CPPHTTPLIB_SSL_ENABLED
  2896. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2897. auto host = "httpbingo.org";
  2898. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2899. auto paths = std::vector<std::string>{
  2900. "/digest-auth/auth/hello/world/MD5",
  2901. "/digest-auth/auth/hello/world/SHA-256",
  2902. };
  2903. auto port = 443;
  2904. SSLClient cli(host, port);
  2905. {
  2906. auto res = cli.Get(unauth_path);
  2907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2908. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2909. }
  2910. {
  2911. cli.set_digest_auth("hello", "world");
  2912. for (const auto &path : paths) {
  2913. auto res = cli.Get(path.c_str());
  2914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2915. auto body = remove_whitespace(res->body);
  2916. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2917. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2918. EXPECT_EQ(StatusCode::OK_200, res->status);
  2919. }
  2920. cli.set_digest_auth("hello", "bad");
  2921. for (const auto &path : paths) {
  2922. auto res = cli.Get(path.c_str());
  2923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2924. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2925. }
  2926. }
  2927. }
  2928. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2929. // comma-separated list of challenges, and each challenge may itself carry a
  2930. // comma-separated auth-param list, so a server can legally offer Basic
  2931. // before Digest, either as two field lines or packed into one. Runs one 401
  2932. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2933. // value() joins them in receipt order) and checks that the retry carries a
  2934. // well-formed Digest Authorization header naming expected_realm.
  2935. static void
  2936. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2937. const std::string &expected_realm) {
  2938. std::atomic<int> hits{0};
  2939. Server svr;
  2940. svr.Get("/x", [&](const Request &req, Response &res) {
  2941. if (++hits == 1) {
  2942. res.status = StatusCode::Unauthorized_401;
  2943. for (const auto &challenge : challenges) {
  2944. res.set_header("WWW-Authenticate", challenge);
  2945. }
  2946. } else {
  2947. auto authorization = req.get_header_value("Authorization");
  2948. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2949. EXPECT_NE(std::string::npos,
  2950. authorization.find("realm=\"" + expected_realm + "\""));
  2951. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2952. res.set_content("ok", "text/plain");
  2953. }
  2954. });
  2955. auto port = svr.bind_to_any_port(HOST);
  2956. std::thread t([&]() { svr.listen_after_bind(); });
  2957. auto se = detail::scope_exit([&] {
  2958. svr.stop();
  2959. t.join();
  2960. });
  2961. svr.wait_until_ready();
  2962. Client cli(HOST, port);
  2963. cli.set_digest_auth("hello", "world");
  2964. auto res = cli.Get("/x");
  2965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2966. EXPECT_EQ(2, hits.load());
  2967. }
  2968. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2969. static const char *kDigestChallenge =
  2970. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2971. "algorithm=MD5";
  2972. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2973. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2974. "testrealm");
  2975. }
  2976. // Same challenge list with the schemes in the opposite order, to make sure
  2977. // the fix above didn't just special-case "Basic first".
  2978. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2979. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2980. "testrealm");
  2981. }
  2982. // A comma inside a quoted auth-param value must not be mistaken for the
  2983. // separator between two challenges (or two auth-params).
  2984. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2985. run_digest_challenge_list_test(
  2986. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2987. "algorithm=MD5"},
  2988. "test,realm");
  2989. }
  2990. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  2991. // the params and leaves out the fragment.
  2992. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  2993. Server svr;
  2994. std::string uri, target;
  2995. svr.Get("/a b", [&](const Request &req, Response &res) {
  2996. auto auth = req.get_header_value("Authorization");
  2997. if (auth.empty()) {
  2998. res.status = StatusCode::Unauthorized_401;
  2999. res.set_header("WWW-Authenticate",
  3000. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3001. return;
  3002. }
  3003. auto b = auth.find("uri=\"") + 5;
  3004. uri = auth.substr(b, auth.find('"', b) - b);
  3005. target = req.target;
  3006. });
  3007. auto port = svr.bind_to_any_port(HOST);
  3008. std::thread t([&]() { svr.listen_after_bind(); });
  3009. auto se = detail::scope_exit([&] {
  3010. svr.stop();
  3011. t.join();
  3012. });
  3013. svr.wait_until_ready();
  3014. Client cli(HOST, port);
  3015. cli.set_digest_auth("hello", "world");
  3016. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3018. EXPECT_EQ("/a%20b?x=1", target);
  3019. EXPECT_EQ(target, uri);
  3020. }
  3021. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3022. // make_digest_authentication_header() dereferences both unconditionally, so
  3023. // a server sending a challenge missing either one must not be treated as
  3024. // usable -- doing so used to crash the client with std::out_of_range.
  3025. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3026. Server svr;
  3027. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3028. res.status = StatusCode::Unauthorized_401;
  3029. res.set_header("WWW-Authenticate", challenge);
  3030. });
  3031. auto port = svr.bind_to_any_port(HOST);
  3032. std::thread t([&]() { svr.listen_after_bind(); });
  3033. auto se = detail::scope_exit([&] {
  3034. svr.stop();
  3035. t.join();
  3036. });
  3037. svr.wait_until_ready();
  3038. Client cli(HOST, port);
  3039. cli.set_digest_auth("hello", "world");
  3040. auto res = cli.Get("/x");
  3041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3042. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3043. }
  3044. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3045. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3046. }
  3047. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3048. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3049. }
  3050. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3051. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3052. }
  3053. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3054. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3055. // when storing the values, so the header builder has to re-escape them (and
  3056. // keep algorithm a bare token); otherwise the value breaks out of its
  3057. // quoted-string and injects extra auth-params into the client's Authorization.
  3058. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3059. std::atomic<int> hits{0};
  3060. std::string authorization;
  3061. Server svr;
  3062. svr.Get("/x", [&](const Request &req, Response &res) {
  3063. if (++hits == 1) {
  3064. res.status = StatusCode::Unauthorized_401;
  3065. // On the wire the quotes embedded in the values are backslash-escaped.
  3066. res.set_header("WWW-Authenticate",
  3067. "Digest realm=\"testrealm\", "
  3068. "nonce=\"n\\\"; injected=\\\"x\", "
  3069. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3070. } else {
  3071. authorization = req.get_header_value("Authorization");
  3072. res.set_content("ok", "text/plain");
  3073. }
  3074. });
  3075. auto port = svr.bind_to_any_port(HOST);
  3076. std::thread t([&]() { svr.listen_after_bind(); });
  3077. auto se = detail::scope_exit([&] {
  3078. svr.stop();
  3079. t.join();
  3080. });
  3081. svr.wait_until_ready();
  3082. Client cli(HOST, port);
  3083. cli.set_digest_auth("hello", "world");
  3084. auto res = cli.Get("/x");
  3085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3086. EXPECT_EQ(2, hits.load());
  3087. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3088. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3089. // inside its quoted-string rather than starting an "injected" auth-param.
  3090. EXPECT_NE(std::string::npos,
  3091. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3092. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3093. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3094. }
  3095. #endif
  3096. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3097. auto host = "google.com";
  3098. auto another_host = "example.com";
  3099. auto wrong_ip = "0.0.0.0";
  3100. #ifdef CPPHTTPLIB_SSL_ENABLED
  3101. SSLClient cli(host);
  3102. #else
  3103. Client cli(host);
  3104. #endif
  3105. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3106. auto res = cli.Get("/");
  3107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3108. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3109. }
  3110. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3111. auto host = "google.com";
  3112. auto wrong_ip = "0.0.0.0";
  3113. #ifdef CPPHTTPLIB_SSL_ENABLED
  3114. SSLClient cli(host);
  3115. #else
  3116. Client cli(host);
  3117. #endif
  3118. cli.set_hostname_addr_map({{host, wrong_ip}});
  3119. auto res = cli.Get("/");
  3120. ASSERT_TRUE(!res);
  3121. EXPECT_EQ(Error::Connection, res.error());
  3122. }
  3123. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3124. // A mapped value that is not an IP literal must be resolved. "localhost"
  3125. // resolves from the hosts file, so this test needs no external DNS.
  3126. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3127. auto host = "target.invalid";
  3128. Server svr;
  3129. std::string received_host;
  3130. svr.Get("/hi", [&](const Request &req, Response &res) {
  3131. received_host = req.get_header_value("Host");
  3132. res.set_content("Hello World!", "text/plain");
  3133. });
  3134. auto port = svr.bind_to_any_port(HOST);
  3135. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3136. auto se = detail::scope_exit([&] {
  3137. svr.stop();
  3138. thread.join();
  3139. ASSERT_FALSE(svr.is_running());
  3140. });
  3141. svr.wait_until_ready();
  3142. Client cli(host, port);
  3143. cli.set_hostname_addr_map({{host, HOST}});
  3144. auto res = cli.Get("/hi");
  3145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3146. EXPECT_EQ(StatusCode::OK_200, res->status);
  3147. // The mapping only redirects the connection; the identity stays host_.
  3148. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3149. }
  3150. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3151. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3152. auto host = "target.invalid";
  3153. Server svr;
  3154. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3155. res.set_content("Hello World!", "text/plain");
  3156. });
  3157. auto port = svr.bind_to_any_port("127.0.0.1");
  3158. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3159. auto se = detail::scope_exit([&] {
  3160. svr.stop();
  3161. thread.join();
  3162. ASSERT_FALSE(svr.is_running());
  3163. });
  3164. svr.wait_until_ready();
  3165. Client cli(host, port);
  3166. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3167. auto res = cli.Get("/hi");
  3168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3169. EXPECT_EQ(StatusCode::OK_200, res->status);
  3170. }
  3171. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3172. // An empty mapped value must leave host_ as the connection target. Without
  3173. // that guard the empty value would become the host argument, getaddrinfo
  3174. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3175. // loopback - silently connecting somewhere the caller never asked for.
  3176. // The server listens on loopback, so such a fallback would succeed and is
  3177. // therefore observable as a failure of this test.
  3178. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3179. Server svr;
  3180. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3181. res.set_content("Hello World!", "text/plain");
  3182. });
  3183. auto port = svr.bind_to_any_port(HOST);
  3184. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3185. auto se = detail::scope_exit([&] {
  3186. svr.stop();
  3187. thread.join();
  3188. ASSERT_FALSE(svr.is_running());
  3189. });
  3190. svr.wait_until_ready();
  3191. Client cli(blackhole, port);
  3192. cli.set_hostname_addr_map({{blackhole, ""}});
  3193. cli.set_connection_timeout(1);
  3194. auto res = cli.Get("/hi");
  3195. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3196. }
  3197. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3198. auto host = "httpbingo.org";
  3199. auto path = std::string{"/absolute-redirect/3"};
  3200. #ifdef CPPHTTPLIB_SSL_ENABLED
  3201. SSLClient cli(host);
  3202. #else
  3203. Client cli(host);
  3204. #endif
  3205. cli.set_follow_location(true);
  3206. auto res = cli.Get(path);
  3207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3208. EXPECT_EQ(StatusCode::OK_200, res->status);
  3209. }
  3210. TEST(RedirectTest, Redirect_Online) {
  3211. auto host = "httpbingo.org";
  3212. auto path = std::string{"/redirect/3"};
  3213. #ifdef CPPHTTPLIB_SSL_ENABLED
  3214. SSLClient cli(host);
  3215. #else
  3216. Client cli(host);
  3217. #endif
  3218. cli.set_follow_location(true);
  3219. auto res = cli.Get(path);
  3220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3221. EXPECT_EQ(StatusCode::OK_200, res->status);
  3222. }
  3223. TEST(RelativeRedirectTest, Redirect_Online) {
  3224. auto host = "httpbingo.org";
  3225. auto path = std::string{"/relative-redirect/3"};
  3226. #ifdef CPPHTTPLIB_SSL_ENABLED
  3227. SSLClient cli(host);
  3228. #else
  3229. Client cli(host);
  3230. #endif
  3231. cli.set_follow_location(true);
  3232. auto res = cli.Get(path);
  3233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3234. EXPECT_EQ(StatusCode::OK_200, res->status);
  3235. }
  3236. TEST(TooManyRedirectTest, Redirect_Online) {
  3237. auto host = "httpbingo.org";
  3238. auto path = std::string{"/redirect/21"};
  3239. #ifdef CPPHTTPLIB_SSL_ENABLED
  3240. SSLClient cli(host);
  3241. #else
  3242. Client cli(host);
  3243. #endif
  3244. cli.set_follow_location(true);
  3245. auto res = cli.Get(path);
  3246. ASSERT_TRUE(!res);
  3247. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3248. }
  3249. #ifdef CPPHTTPLIB_SSL_ENABLED
  3250. TEST(YahooRedirectTest, Redirect_Online) {
  3251. Client cli("yahoo.com");
  3252. auto res = cli.Get("/");
  3253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3254. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3255. cli.set_follow_location(true);
  3256. res = cli.Get("/");
  3257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3258. EXPECT_EQ(StatusCode::OK_200, res->status);
  3259. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3260. }
  3261. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3262. #define REDIR_HOST "httpbingo.org"
  3263. #define REDIR_PATH "/redirect-to"
  3264. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3265. SSLClient cli(REDIR_HOST);
  3266. cli.set_follow_location(true);
  3267. auto res =
  3268. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3270. EXPECT_EQ(StatusCode::OK_200, res->status);
  3271. }
  3272. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3273. SSLClient cli(REDIR_HOST);
  3274. cli.set_follow_location(true);
  3275. Params params;
  3276. params.emplace("url", "http://example.com");
  3277. params.emplace("status_code", "302");
  3278. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3280. EXPECT_EQ(StatusCode::OK_200, res->status);
  3281. }
  3282. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3283. SSLClient cli(REDIR_HOST);
  3284. cli.set_follow_location(true);
  3285. Params params;
  3286. params.emplace("url", "http://example.com");
  3287. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3289. EXPECT_EQ(StatusCode::OK_200, res->status);
  3290. }
  3291. TEST(UrlWithSpace, Redirect_Online) {
  3292. SSLClient cli("edge.forgecdn.net");
  3293. cli.set_follow_location(true);
  3294. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3296. EXPECT_EQ(StatusCode::OK_200, res->status);
  3297. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3298. }
  3299. #endif
  3300. #if !defined(_WIN32) && !defined(_WIN64)
  3301. TEST(ReceiveSignals, Signal) {
  3302. auto setupSignalHandlers = []() {
  3303. struct sigaction act;
  3304. sigemptyset(&act.sa_mask);
  3305. act.sa_flags = SA_SIGINFO;
  3306. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3307. switch (sig) {
  3308. case SIGINT:
  3309. default: break;
  3310. }
  3311. };
  3312. ::sigaction(SIGINT, &act, nullptr);
  3313. };
  3314. Server svr;
  3315. int port = 0;
  3316. auto thread = std::thread([&]() {
  3317. setupSignalHandlers();
  3318. port = svr.bind_to_any_port(HOST);
  3319. svr.listen_after_bind();
  3320. });
  3321. auto se = detail::scope_exit([&] {
  3322. svr.stop();
  3323. thread.join();
  3324. ASSERT_FALSE(svr.is_running());
  3325. });
  3326. svr.wait_until_ready();
  3327. ASSERT_TRUE(svr.is_running());
  3328. pthread_kill(thread.native_handle(), SIGINT);
  3329. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3330. ASSERT_TRUE(svr.is_running());
  3331. }
  3332. #endif
  3333. TEST(RedirectToDifferentPort, Redirect) {
  3334. Server svr1;
  3335. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3336. res.set_content("Hello World!", "text/plain");
  3337. });
  3338. int svr1_port = 0;
  3339. auto thread1 = std::thread([&]() {
  3340. svr1_port = svr1.bind_to_any_port(HOST);
  3341. svr1.listen_after_bind();
  3342. });
  3343. Server svr2;
  3344. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3345. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3346. });
  3347. int svr2_port = 0;
  3348. auto thread2 = std::thread([&]() {
  3349. svr2_port = svr2.bind_to_any_port(HOST);
  3350. svr2.listen_after_bind();
  3351. });
  3352. auto se = detail::scope_exit([&] {
  3353. svr2.stop();
  3354. thread2.join();
  3355. svr1.stop();
  3356. thread1.join();
  3357. ASSERT_FALSE(svr2.is_running());
  3358. ASSERT_FALSE(svr1.is_running());
  3359. });
  3360. svr1.wait_until_ready();
  3361. svr2.wait_until_ready();
  3362. Client cli("localhost", svr2_port);
  3363. cli.set_follow_location(true);
  3364. auto res = cli.Get("/2");
  3365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3366. EXPECT_EQ(StatusCode::OK_200, res->status);
  3367. EXPECT_EQ("Hello World!", res->body);
  3368. }
  3369. // GET /redir on one server redirects to /target on another port, so the
  3370. // client follows it with a new client.
  3371. static Result
  3372. GetThroughRedirectToDifferentPort(Server::Handler target,
  3373. const std::function<void(Client &)> &setup,
  3374. const Headers &headers = Headers()) {
  3375. Server target_svr;
  3376. target_svr.Get("/target", target);
  3377. int target_port = 0;
  3378. auto target_thread = std::thread([&]() {
  3379. target_port = target_svr.bind_to_any_port(HOST);
  3380. target_svr.listen_after_bind();
  3381. });
  3382. Server origin_svr;
  3383. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3384. res.set_redirect(
  3385. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3386. });
  3387. int origin_port = 0;
  3388. auto origin_thread = std::thread([&]() {
  3389. origin_port = origin_svr.bind_to_any_port(HOST);
  3390. origin_svr.listen_after_bind();
  3391. });
  3392. auto se = detail::scope_exit([&] {
  3393. origin_svr.stop();
  3394. origin_thread.join();
  3395. target_svr.stop();
  3396. target_thread.join();
  3397. });
  3398. target_svr.wait_until_ready();
  3399. origin_svr.wait_until_ready();
  3400. Client cli("localhost", origin_port);
  3401. cli.set_follow_location(true);
  3402. setup(cli);
  3403. return cli.Get("/redir", headers);
  3404. }
  3405. static void
  3406. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3407. std::string captured_authorization;
  3408. auto result = GetThroughRedirectToDifferentPort(
  3409. [&](const Request &req, Response &res) {
  3410. captured_authorization = req.get_header_value("Authorization");
  3411. res.set_content("OK", "text/plain");
  3412. },
  3413. set_auth);
  3414. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3415. EXPECT_EQ(StatusCode::OK_200, result->status);
  3416. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3417. EXPECT_TRUE(captured_authorization.empty());
  3418. }
  3419. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3420. TestDoNotForwardCredentialsOnRedirect(
  3421. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3422. }
  3423. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3424. TestDoNotForwardCredentialsOnRedirect(
  3425. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3426. }
  3427. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3428. std::string captured_cookie;
  3429. auto result = GetThroughRedirectToDifferentPort(
  3430. [&](const Request &req, Response &res) {
  3431. captured_cookie = req.get_header_value("Cookie");
  3432. res.set_content("OK", "text/plain");
  3433. },
  3434. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3435. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3436. EXPECT_EQ(StatusCode::OK_200, result->status);
  3437. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3438. EXPECT_TRUE(captured_cookie.empty());
  3439. }
  3440. TEST(RedirectToSamePort, ForwardCookie) {
  3441. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3442. // header so that ordinary session flows keep working.
  3443. Server svr;
  3444. std::string captured_cookie;
  3445. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3446. res.set_redirect("/target", 302);
  3447. });
  3448. svr.Get("/target", [&](const Request &req, Response &res) {
  3449. captured_cookie = req.get_header_value("Cookie");
  3450. res.set_content("OK", "text/plain");
  3451. });
  3452. auto port = svr.bind_to_any_port(HOST);
  3453. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3454. auto se = detail::scope_exit([&] {
  3455. svr.stop();
  3456. thread.join();
  3457. ASSERT_FALSE(svr.is_running());
  3458. });
  3459. svr.wait_until_ready();
  3460. Client cli(HOST, port);
  3461. cli.set_follow_location(true);
  3462. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3463. auto res = cli.Get("/redir", headers);
  3464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3465. EXPECT_EQ(StatusCode::OK_200, res->status);
  3466. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3467. }
  3468. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3469. std::string authorization;
  3470. std::string trace_id;
  3471. auto result = GetThroughRedirectToDifferentPort(
  3472. [&](const Request &req, Response &res) {
  3473. authorization = req.get_header_value("Authorization");
  3474. trace_id = req.get_header_value("X-Trace-Id");
  3475. res.set_content("OK", "text/plain");
  3476. },
  3477. [](Client &cli) {
  3478. cli.set_default_headers(
  3479. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3480. });
  3481. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3482. EXPECT_EQ(StatusCode::OK_200, result->status);
  3483. // Like a header given with the request, a default one goes along unless it
  3484. // carries credentials (RFC 9110 15.4).
  3485. EXPECT_TRUE(authorization.empty());
  3486. EXPECT_EQ("42", trace_id);
  3487. }
  3488. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3489. auto result = GetThroughRedirectToDifferentPort(
  3490. [](const Request &, Response &res) {
  3491. res.set_content(std::string(2048, 'x'), "text/plain");
  3492. },
  3493. [](Client &cli) { cli.set_payload_max_length(1024); });
  3494. EXPECT_FALSE(result);
  3495. }
  3496. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3497. auto result = GetThroughRedirectToDifferentPort(
  3498. [](const Request &req, Response &res) {
  3499. // Answer after a second, or once the client gives up.
  3500. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3501. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3502. }
  3503. res.set_content("late", "text/plain");
  3504. },
  3505. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3506. ASSERT_FALSE(result);
  3507. EXPECT_EQ(Error::Read, result.error());
  3508. }
  3509. #ifdef CPPHTTPLIB_SSL_ENABLED
  3510. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3511. auto result = GetThroughRedirectToDifferentPort(
  3512. [](const Request &, Response &res) {
  3513. res.status = StatusCode::Unauthorized_401;
  3514. res.set_header("WWW-Authenticate",
  3515. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3516. },
  3517. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3518. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3519. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3520. }
  3521. #endif
  3522. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3523. Server svr;
  3524. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3525. // Port number that overflows int — should not crash
  3526. res.set_redirect("http://localhost:99999999999999999999/target");
  3527. });
  3528. auto port = svr.bind_to_any_port(HOST);
  3529. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3530. auto se = detail::scope_exit([&] {
  3531. svr.stop();
  3532. thread.join();
  3533. ASSERT_FALSE(svr.is_running());
  3534. });
  3535. svr.wait_until_ready();
  3536. Client cli(HOST, port);
  3537. cli.set_follow_location(true);
  3538. auto res = cli.Get("/redir");
  3539. // Should fail gracefully, not crash (no valid response due to bad port)
  3540. EXPECT_FALSE(res);
  3541. }
  3542. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3543. Server svr;
  3544. auto port = svr.bind_to_any_port(HOST);
  3545. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3546. // The server's own port followed by junk must not be followed
  3547. res.set_redirect("http://" + std::string(HOST) + ":" +
  3548. std::to_string(port) + "junk/target");
  3549. });
  3550. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3551. res.set_content("target", "text/plain");
  3552. });
  3553. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3554. auto se = detail::scope_exit([&] {
  3555. svr.stop();
  3556. thread.join();
  3557. ASSERT_FALSE(svr.is_running());
  3558. });
  3559. svr.wait_until_ready();
  3560. Client cli(HOST, port);
  3561. cli.set_follow_location(true);
  3562. auto res = cli.Get("/redir");
  3563. EXPECT_FALSE(res);
  3564. }
  3565. TEST(RedirectFromPageWithContent, Redirect) {
  3566. Server svr;
  3567. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3568. res.set_content("___", "text/plain");
  3569. res.set_redirect("/2");
  3570. });
  3571. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3572. res.set_content("Hello World!", "text/plain");
  3573. });
  3574. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3575. auto se = detail::scope_exit([&] {
  3576. svr.stop();
  3577. th.join();
  3578. ASSERT_FALSE(svr.is_running());
  3579. });
  3580. svr.wait_until_ready();
  3581. {
  3582. Client cli("localhost", PORT);
  3583. cli.set_follow_location(true);
  3584. std::string body;
  3585. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3586. body.append(data, data_length);
  3587. return true;
  3588. });
  3589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3590. EXPECT_EQ(StatusCode::OK_200, res->status);
  3591. EXPECT_EQ("Hello World!", body);
  3592. }
  3593. {
  3594. Client cli("localhost", PORT);
  3595. std::string body;
  3596. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3597. body.append(data, data_length);
  3598. return true;
  3599. });
  3600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3601. EXPECT_EQ(StatusCode::Found_302, res->status);
  3602. EXPECT_EQ("___", body);
  3603. }
  3604. }
  3605. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3606. Server svr;
  3607. auto port_str = std::to_string(PORT);
  3608. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3609. auto expected_host = "[::1]:" + port_str;
  3610. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3611. res.set_content("___", "text/plain");
  3612. // res.set_redirect("/2");
  3613. res.set_redirect(redirect_url);
  3614. });
  3615. svr.Get("/2", [&](const Request &req, Response &res) {
  3616. auto host_header = req.headers.find("Host");
  3617. ASSERT_TRUE(host_header != req.headers.end());
  3618. EXPECT_EQ(expected_host, host_header->second);
  3619. res.set_content("Hello World!", "text/plain");
  3620. });
  3621. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3622. auto se = detail::scope_exit([&] {
  3623. svr.stop();
  3624. th.join();
  3625. ASSERT_FALSE(svr.is_running());
  3626. });
  3627. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3628. // actually starts anything, so the condition !svr.is_running() will
  3629. // always remain true, and the loop never stops.
  3630. // This basically counts how many milliseconds have passed since the
  3631. // call to svr.listen(), and if after 5 seconds nothing started yet
  3632. // aborts the test.
  3633. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3634. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3635. ASSERT_LT(milliseconds, 5000U);
  3636. }
  3637. {
  3638. Client cli("::1", PORT);
  3639. cli.set_follow_location(true);
  3640. std::string body;
  3641. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3642. body.append(data, data_length);
  3643. return true;
  3644. });
  3645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3646. EXPECT_EQ(StatusCode::OK_200, res->status);
  3647. EXPECT_EQ("Hello World!", body);
  3648. }
  3649. {
  3650. Client cli("::1", PORT);
  3651. std::string body;
  3652. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3653. body.append(data, data_length);
  3654. return true;
  3655. });
  3656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3657. EXPECT_EQ(StatusCode::Found_302, res->status);
  3658. EXPECT_EQ("___", body);
  3659. }
  3660. }
  3661. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3662. Server svr;
  3663. svr.Get("/foo", [](const Request &req, Response &res) {
  3664. auto a = req.params.find("a");
  3665. if (a != req.params.end()) {
  3666. res.set_content((*a).second, "text/plain");
  3667. res.status = StatusCode::OK_200;
  3668. } else {
  3669. res.status = StatusCode::BadRequest_400;
  3670. }
  3671. });
  3672. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3673. auto se = detail::scope_exit([&] {
  3674. svr.stop();
  3675. thread.join();
  3676. ASSERT_FALSE(svr.is_running());
  3677. });
  3678. svr.wait_until_ready();
  3679. {
  3680. Client cli(HOST, PORT);
  3681. cli.set_path_encode(false);
  3682. auto res = cli.Get("/foo?a=explicitly+encoded");
  3683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3684. EXPECT_EQ(StatusCode::OK_200, res->status);
  3685. // This expects it back with a space, as the `+` won't have been
  3686. // url-encoded, and server-side the params get decoded turning `+`
  3687. // into spaces.
  3688. EXPECT_EQ("explicitly encoded", res->body);
  3689. }
  3690. }
  3691. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3692. // When path encoding is disabled the client must transmit the supplied
  3693. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3694. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3695. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3696. // than a space (0x20). Assert on the raw wire target to catch this.
  3697. Server svr;
  3698. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3699. svr.Get("/foo", [&](const Request &req, Response &res) {
  3700. EXPECT_EQ(expected_target, req.target);
  3701. res.status = StatusCode::OK_200;
  3702. });
  3703. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3704. auto se = detail::scope_exit([&] {
  3705. svr.stop();
  3706. thread.join();
  3707. ASSERT_FALSE(svr.is_running());
  3708. });
  3709. svr.wait_until_ready();
  3710. {
  3711. Client cli(HOST, PORT);
  3712. cli.set_path_encode(false);
  3713. auto res = cli.Get(expected_target.c_str());
  3714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3715. EXPECT_EQ(StatusCode::OK_200, res->status);
  3716. }
  3717. }
  3718. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3719. // `open_stream()` used to skip the path encoding that the buffered send
  3720. // path applies, so the same `path` produced different bytes in the request
  3721. // line depending on which API was used. Assert the two agree.
  3722. Server svr;
  3723. std::string target;
  3724. svr.Get(".*", [&](const Request &req, Response &res) {
  3725. target = req.target;
  3726. res.status = StatusCode::OK_200;
  3727. });
  3728. auto port = svr.bind_to_any_port(HOST);
  3729. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3730. auto se = detail::scope_exit([&] {
  3731. svr.stop();
  3732. thread.join();
  3733. ASSERT_FALSE(svr.is_running());
  3734. });
  3735. svr.wait_until_ready();
  3736. struct {
  3737. const char *path;
  3738. const char *expected;
  3739. } cases[] = {
  3740. {"/a b?x=1", "/a%20b?x=1"},
  3741. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3742. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3743. };
  3744. for (const auto &c : cases) {
  3745. Client cli(HOST, port);
  3746. target.clear();
  3747. auto res = cli.Get(c.path);
  3748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3749. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3750. auto buffered_target = target;
  3751. target.clear();
  3752. auto handle = cli.open_stream("GET", c.path);
  3753. EXPECT_TRUE(handle.is_valid())
  3754. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3755. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3756. }
  3757. }
  3758. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3759. // The `set_path_encode(false)` contract — transmit the supplied target
  3760. // verbatim — must hold for the streaming API too.
  3761. Server svr;
  3762. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3763. std::string target;
  3764. svr.Get("/foo", [&](const Request &req, Response &res) {
  3765. target = req.target;
  3766. res.status = StatusCode::OK_200;
  3767. });
  3768. auto port = svr.bind_to_any_port(HOST);
  3769. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3770. auto se = detail::scope_exit([&] {
  3771. svr.stop();
  3772. thread.join();
  3773. ASSERT_FALSE(svr.is_running());
  3774. });
  3775. svr.wait_until_ready();
  3776. {
  3777. Client cli(HOST, port);
  3778. cli.set_path_encode(false);
  3779. auto handle = cli.open_stream("GET", expected_target);
  3780. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3781. EXPECT_EQ(expected_target, target);
  3782. }
  3783. }
  3784. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3785. // With path encoding enabled a CR/LF in the target is percent-encoded
  3786. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3787. // write_request_line still backstops `set_path_encode(false)`, which is
  3788. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3789. Server svr;
  3790. // Captured before routing: the decoded path contains a newline, which a
  3791. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3792. std::string target;
  3793. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3794. target = req.target;
  3795. res.status = StatusCode::OK_200;
  3796. return Server::HandlerResponse::Handled;
  3797. });
  3798. auto port = svr.bind_to_any_port(HOST);
  3799. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3800. auto se = detail::scope_exit([&] {
  3801. svr.stop();
  3802. thread.join();
  3803. ASSERT_FALSE(svr.is_running());
  3804. });
  3805. svr.wait_until_ready();
  3806. {
  3807. Client cli(HOST, port);
  3808. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3809. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3810. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3811. }
  3812. }
  3813. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3814. // Every control character is percent-encoded, not just CR/LF, so the target
  3815. // passes the request-target check in write_request_line.
  3816. Server svr;
  3817. std::string target;
  3818. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3819. target = req.target;
  3820. res.status = StatusCode::OK_200;
  3821. return Server::HandlerResponse::Handled;
  3822. });
  3823. auto port = svr.bind_to_any_port(HOST);
  3824. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3825. auto se = detail::scope_exit([&] {
  3826. svr.stop();
  3827. thread.join();
  3828. ASSERT_FALSE(svr.is_running());
  3829. });
  3830. svr.wait_until_ready();
  3831. {
  3832. Client cli(HOST, port);
  3833. auto res = cli.Get("/a\tb\x1b\x7f");
  3834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3835. EXPECT_EQ("/a%09b%1B%7F", target);
  3836. }
  3837. }
  3838. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3839. // Nothing may reach the wire: a raw CR/LF target would split the request
  3840. // line and inject headers.
  3841. Server svr;
  3842. // Pre-routing so that "not called" means nothing reached the server at all,
  3843. // rather than merely failing to match a handler pattern.
  3844. auto handler_called = false;
  3845. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3846. handler_called = true;
  3847. res.status = StatusCode::OK_200;
  3848. return Server::HandlerResponse::Handled;
  3849. });
  3850. auto port = svr.bind_to_any_port(HOST);
  3851. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3852. auto se = detail::scope_exit([&] {
  3853. svr.stop();
  3854. thread.join();
  3855. ASSERT_FALSE(svr.is_running());
  3856. });
  3857. svr.wait_until_ready();
  3858. {
  3859. Client cli(HOST, port);
  3860. cli.set_path_encode(false);
  3861. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3862. EXPECT_FALSE(handle.is_valid());
  3863. EXPECT_EQ(Error::Write, handle.error);
  3864. EXPECT_FALSE(handler_called);
  3865. }
  3866. }
  3867. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3868. // Which of the two branches runs is decided by whether the query component
  3869. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3870. // an empty query and must still fall back to building one from
  3871. // `req.params`, while a non-empty query must win over `req.params`.
  3872. Server svr;
  3873. std::string target;
  3874. svr.Get("/foo", [&](const Request &req, Response &res) {
  3875. target = req.target;
  3876. res.status = StatusCode::OK_200;
  3877. });
  3878. auto port = svr.bind_to_any_port(HOST);
  3879. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3880. auto se = detail::scope_exit([&] {
  3881. svr.stop();
  3882. thread.join();
  3883. ASSERT_FALSE(svr.is_running());
  3884. });
  3885. svr.wait_until_ready();
  3886. {
  3887. // Trailing `?` -> empty query component -> `req.params` is used.
  3888. Client cli(HOST, port);
  3889. Request req;
  3890. req.method = "GET";
  3891. req.path = "/foo?";
  3892. req.params.emplace("a", "1");
  3893. target.clear();
  3894. auto res = cli.send(req);
  3895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3896. EXPECT_EQ("/foo?a=1", target);
  3897. }
  3898. {
  3899. // Non-empty query in `req.path` -> `req.params` is not appended.
  3900. Client cli(HOST, port);
  3901. Request req;
  3902. req.method = "GET";
  3903. req.path = "/foo?b=2";
  3904. req.params.emplace("a", "1");
  3905. target.clear();
  3906. auto res = cli.send(req);
  3907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3908. EXPECT_EQ("/foo?b=2", target);
  3909. }
  3910. }
  3911. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3912. Server svr;
  3913. svr.Get("/", [](const Request &req, Response &) {
  3914. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3915. });
  3916. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3917. auto se = detail::scope_exit([&] {
  3918. svr.stop();
  3919. thread.join();
  3920. ASSERT_FALSE(svr.is_running());
  3921. });
  3922. svr.wait_until_ready();
  3923. {
  3924. Client cli(HOST, PORT);
  3925. cli.set_path_encode(false);
  3926. auto res = cli.Get("/?something=%0A");
  3927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3928. EXPECT_EQ(StatusCode::OK_200, res->status);
  3929. }
  3930. }
  3931. TEST(BindServerTest, BindDualStack) {
  3932. Server svr;
  3933. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3934. res.set_content("Hello World!", "text/plain");
  3935. });
  3936. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3937. auto se = detail::scope_exit([&] {
  3938. svr.stop();
  3939. thread.join();
  3940. ASSERT_FALSE(svr.is_running());
  3941. });
  3942. svr.wait_until_ready();
  3943. {
  3944. Client cli("127.0.0.1", PORT);
  3945. auto res = cli.Get("/1");
  3946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3947. EXPECT_EQ(StatusCode::OK_200, res->status);
  3948. EXPECT_EQ("Hello World!", res->body);
  3949. }
  3950. {
  3951. Client cli("::1", PORT);
  3952. auto res = cli.Get("/1");
  3953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3954. EXPECT_EQ(StatusCode::OK_200, res->status);
  3955. EXPECT_EQ("Hello World!", res->body);
  3956. }
  3957. }
  3958. TEST(BindServerTest, BindAndListenSeparately) {
  3959. Server svr;
  3960. int port = svr.bind_to_any_port("0.0.0.0");
  3961. ASSERT_TRUE(svr.is_valid());
  3962. ASSERT_TRUE(port > 0);
  3963. svr.stop();
  3964. }
  3965. // Reports whether anything is still listening on a loopback port. A plain
  3966. // connect() is used instead of a Client request because a socket left bound by
  3967. // mistake accepts the connection into its backlog and never answers, which
  3968. // would hang the test instead of failing it.
  3969. static bool is_loopback_port_accepting(int port) {
  3970. sockaddr_in addr{};
  3971. addr.sin_family = AF_INET;
  3972. addr.sin_port = htons(static_cast<uint16_t>(port));
  3973. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3974. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3975. EXPECT_NE(sock, INVALID_SOCKET);
  3976. if (sock == INVALID_SOCKET) { return false; }
  3977. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3978. static_cast<socklen_t>(sizeof(addr)));
  3979. detail::close_socket(sock);
  3980. return ret == 0;
  3981. }
  3982. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3983. Server svr;
  3984. auto port = svr.bind_to_any_port("127.0.0.1");
  3985. ASSERT_TRUE(port > 0);
  3986. svr.stop();
  3987. // bind_to_any_port() already called listen(2), so until stop() closed the
  3988. // descriptor the port kept accepting connections into the backlog. ASSERT
  3989. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3990. // below blocks forever in the accept loop.
  3991. ASSERT_FALSE(is_loopback_port_accepting(port));
  3992. // Nothing is left to accept on, so listen_after_bind() must report failure
  3993. // instead of returning success without ever serving.
  3994. EXPECT_FALSE(svr.listen_after_bind());
  3995. // The failed listen marks the server decommissioned, so a waiter returns
  3996. // instead of spinning forever.
  3997. svr.wait_until_ready();
  3998. }
  3999. #ifdef CPPHTTPLIB_SSL_ENABLED
  4000. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4001. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4002. CLIENT_CA_CERT_DIR);
  4003. int port = svr.bind_to_any_port("0.0.0.0");
  4004. ASSERT_TRUE(svr.is_valid());
  4005. ASSERT_TRUE(port > 0);
  4006. svr.stop();
  4007. }
  4008. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4009. // or a rejected CustomRoute() registration would not stop the server binding.
  4010. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4011. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4012. CLIENT_CA_CERT_DIR);
  4013. ASSERT_TRUE(svr.is_valid());
  4014. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4015. EXPECT_FALSE(svr.is_valid());
  4016. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4017. }
  4018. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4019. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4020. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4021. int port = svr.bind_to_any_port("0.0.0.0");
  4022. ASSERT_TRUE(svr.is_valid());
  4023. ASSERT_TRUE(port > 0);
  4024. svr.stop();
  4025. }
  4026. TEST(BindServerTest, UpdateCertsPem) {
  4027. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4028. int port = svr.bind_to_any_port("0.0.0.0");
  4029. ASSERT_TRUE(svr.is_valid());
  4030. ASSERT_TRUE(port > 0);
  4031. // Read PEM files
  4032. std::string cert_pem, key_pem, ca_pem;
  4033. read_file(SERVER_CERT_FILE, cert_pem);
  4034. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4035. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4036. // Update server certificates using PEM API
  4037. ASSERT_TRUE(
  4038. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4039. ASSERT_TRUE(svr.is_valid());
  4040. svr.stop();
  4041. }
  4042. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4043. // Start server with client CA (enables client auth)
  4044. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4045. ASSERT_TRUE(svr.is_valid());
  4046. bool handler_called = false;
  4047. svr.Get("/test", [&](const Request &req, Response &res) {
  4048. handler_called = true;
  4049. // Verify client certificate is present
  4050. auto cert = req.peer_cert();
  4051. EXPECT_TRUE(static_cast<bool>(cert));
  4052. res.set_content("ok", "text/plain");
  4053. });
  4054. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4055. auto se = detail::scope_exit([&] {
  4056. svr.stop();
  4057. t.join();
  4058. ASSERT_FALSE(svr.is_running());
  4059. });
  4060. svr.wait_until_ready();
  4061. // Read PEM files
  4062. std::string cert_pem, key_pem, ca_pem;
  4063. read_file(SERVER_CERT_FILE, cert_pem);
  4064. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4065. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4066. // Update server certificates and client CA using PEM API while server running
  4067. ASSERT_TRUE(
  4068. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4069. // Connect with client certificate
  4070. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4071. cli.enable_server_certificate_verification(false);
  4072. cli.set_connection_timeout(30);
  4073. auto res = cli.Get("/test");
  4074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4075. ASSERT_EQ(StatusCode::OK_200, res->status);
  4076. ASSERT_TRUE(handler_called);
  4077. EXPECT_EQ("ok", res->body);
  4078. }
  4079. // Puts a CA that did not sign the client's certificate in the old one's place.
  4080. static bool replace_client_ca(SSLServer &svr) {
  4081. std::string cert_pem, key_pem, ca_pem;
  4082. read_file(SERVER_CERT_FILE, cert_pem);
  4083. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4084. read_file(SERVER_CERT2_FILE, ca_pem);
  4085. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4086. ca_pem.c_str());
  4087. }
  4088. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4089. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4090. ASSERT_TRUE(svr.is_valid());
  4091. svr.Get("/test", [](const Request &, Response &res) {
  4092. res.set_content("ok", "text/plain");
  4093. });
  4094. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4095. auto se = detail::scope_exit([&] {
  4096. svr.stop();
  4097. t.join();
  4098. ASSERT_FALSE(svr.is_running());
  4099. });
  4100. svr.wait_until_ready();
  4101. auto get = [] {
  4102. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4103. cli.enable_server_certificate_verification(false);
  4104. return cli.Get("/test");
  4105. };
  4106. ASSERT_TRUE(get());
  4107. ASSERT_TRUE(replace_client_ca(svr));
  4108. EXPECT_FALSE(get());
  4109. }
  4110. TEST(SSLClientServerTest, VerifyCallbackKeepsClientCertificateRequired) {
  4111. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4112. ASSERT_TRUE(svr.is_valid());
  4113. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4114. return v.preverify_ok;
  4115. });
  4116. svr.Get("/test", [](const Request &, Response &res) {
  4117. res.set_content("ok", "text/plain");
  4118. });
  4119. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4120. auto se = detail::scope_exit([&] {
  4121. svr.stop();
  4122. t.join();
  4123. ASSERT_FALSE(svr.is_running());
  4124. });
  4125. svr.wait_until_ready();
  4126. SSLClient without_cert(HOST, PORT);
  4127. without_cert.enable_server_certificate_verification(false);
  4128. EXPECT_FALSE(without_cert.Get("/test"));
  4129. SSLClient with_cert(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4130. with_cert.enable_server_certificate_verification(false);
  4131. auto res = with_cert.Get("/test");
  4132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4133. EXPECT_EQ("ok", res->body);
  4134. }
  4135. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4136. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4137. ASSERT_TRUE(svr.is_valid());
  4138. tls::set_verify_callback(svr.tls_context(),
  4139. [](const tls::VerifyContext &) -> bool {
  4140. throw std::runtime_error("verify");
  4141. });
  4142. svr.Get("/test", [](const Request &, Response &res) {
  4143. res.set_content("ok", "text/plain");
  4144. });
  4145. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4146. auto se = detail::scope_exit([&] {
  4147. svr.stop();
  4148. t.join();
  4149. ASSERT_FALSE(svr.is_running());
  4150. });
  4151. svr.wait_until_ready();
  4152. auto get = [] {
  4153. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4154. cli.enable_server_certificate_verification(false);
  4155. return cli.Get("/test");
  4156. };
  4157. EXPECT_FALSE(get());
  4158. // The handshake is over, so an update does not wait for it.
  4159. std::string cert_pem, key_pem;
  4160. read_file(SERVER_CERT_FILE, cert_pem);
  4161. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4162. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4163. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4164. return v.preverify_ok;
  4165. });
  4166. auto res = get();
  4167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4168. EXPECT_EQ("ok", res->body);
  4169. }
  4170. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4171. // Sends each request over a new connection with a client certificate,
  4172. // resuming the session of the one before when there is one.
  4173. class ResumingClient {
  4174. public:
  4175. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4176. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4177. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4178. SSL_FILETYPE_PEM);
  4179. }
  4180. ~ResumingClient() {
  4181. SSL_SESSION_free(session_);
  4182. SSL_CTX_free(ctx_);
  4183. }
  4184. // Tells whether the request was answered.
  4185. bool get() {
  4186. auto error = Error::Success;
  4187. auto sock = detail::create_client_socket(
  4188. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4189. /*connection_timeout_sec=*/5, 0,
  4190. /*read_timeout_sec=*/5, 0,
  4191. /*write_timeout_sec=*/5, 0, std::string(), error);
  4192. if (sock == INVALID_SOCKET) { return false; }
  4193. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4194. auto ssl = SSL_new(ctx_);
  4195. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4196. SSL_set_fd(ssl, static_cast<int>(sock));
  4197. if (session_) { SSL_set_session(ssl, session_); }
  4198. if (SSL_connect(ssl) != 1) { return false; }
  4199. reused_ = SSL_session_reused(ssl) == 1;
  4200. // Reading the response also takes in a TLS 1.3 session ticket.
  4201. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4202. "Connection: close\r\n\r\n";
  4203. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4204. std::string res;
  4205. char buf[256];
  4206. int n;
  4207. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4208. res.append(buf, static_cast<size_t>(n));
  4209. }
  4210. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4211. SSL_shutdown(ssl);
  4212. SSL_SESSION_free(session_);
  4213. session_ = SSL_get1_session(ssl);
  4214. return res.find("200 OK") != std::string::npos;
  4215. }
  4216. // Whether the last connection resumed a session
  4217. bool reused() const { return reused_; }
  4218. private:
  4219. SSL_CTX *ctx_;
  4220. SSL_SESSION *session_ = nullptr;
  4221. bool reused_ = false;
  4222. };
  4223. // A client that resumes its session gets through, but not once the client CA
  4224. // has changed, as a resumed session does not show the certificate again.
  4225. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4226. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4227. ASSERT_TRUE(svr.is_valid());
  4228. svr.Get("/test", [](const Request &, Response &res) {
  4229. res.set_content("ok", "text/plain");
  4230. });
  4231. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4232. auto se = detail::scope_exit([&] {
  4233. svr.stop();
  4234. t.join();
  4235. ASSERT_FALSE(svr.is_running());
  4236. });
  4237. svr.wait_until_ready();
  4238. ResumingClient cli;
  4239. ASSERT_TRUE(cli.get());
  4240. ASSERT_TRUE(cli.get());
  4241. EXPECT_TRUE(cli.reused());
  4242. ASSERT_TRUE(replace_client_ca(svr));
  4243. EXPECT_FALSE(cli.get());
  4244. }
  4245. // A resumed session does not show the certificate again, so the server does
  4246. // not resume one with a verify callback to run on it.
  4247. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4248. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4249. ASSERT_TRUE(svr.is_valid());
  4250. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4251. return v.preverify_ok;
  4252. });
  4253. svr.Get("/test", [](const Request &, Response &res) {
  4254. res.set_content("ok", "text/plain");
  4255. });
  4256. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4257. auto se = detail::scope_exit([&] {
  4258. svr.stop();
  4259. t.join();
  4260. ASSERT_FALSE(svr.is_running());
  4261. });
  4262. svr.wait_until_ready();
  4263. ResumingClient cli;
  4264. ASSERT_TRUE(cli.get());
  4265. ASSERT_TRUE(cli.get());
  4266. EXPECT_FALSE(cli.reused());
  4267. }
  4268. #endif
  4269. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4270. // wolfSSL shares its session cache between contexts, so a resumed session
  4271. // could carry a client certificate checked against another server's CA, or
  4272. // against a client CA since replaced.
  4273. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4274. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4275. ASSERT_TRUE(svr.is_valid());
  4276. // Trusts a CA that did not sign the client's certificate.
  4277. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4278. ASSERT_TRUE(other.is_valid());
  4279. for (auto s : {&svr, &other}) {
  4280. s->Get("/test", [](const Request &, Response &res) {
  4281. res.set_content("ok", "text/plain");
  4282. });
  4283. }
  4284. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4285. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4286. auto se = detail::scope_exit([&] {
  4287. other.stop();
  4288. svr.stop();
  4289. t2.join();
  4290. t.join();
  4291. });
  4292. svr.wait_until_ready();
  4293. other.wait_until_ready();
  4294. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4295. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4296. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4297. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4298. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4299. ASSERT_EQ(WOLFSSL_SUCCESS,
  4300. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4301. WOLFSSL_FILETYPE_PEM));
  4302. WOLFSSL_SESSION *session = nullptr;
  4303. auto session_se = detail::scope_exit([&] {
  4304. if (session) { wolfSSL_SESSION_free(session); }
  4305. });
  4306. // A request over a new connection, resuming `session` when there is one and
  4307. // keeping the connection's own in its place. Tells whether it was answered.
  4308. auto get = [&](int port) {
  4309. auto error = Error::Success;
  4310. auto sock = detail::create_client_socket(
  4311. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4312. /*connection_timeout_sec=*/5, 0,
  4313. /*read_timeout_sec=*/5, 0,
  4314. /*write_timeout_sec=*/5, 0, std::string(), error);
  4315. if (sock == INVALID_SOCKET) { return false; }
  4316. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4317. auto ssl = wolfSSL_new(ctx);
  4318. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4319. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4320. if (session) { wolfSSL_set_session(ssl, session); }
  4321. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4322. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4323. "Connection: close\r\n\r\n";
  4324. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4325. std::string res;
  4326. char buf[256];
  4327. int n;
  4328. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4329. res.append(buf, static_cast<size_t>(n));
  4330. }
  4331. wolfSSL_shutdown(ssl);
  4332. if (session) { wolfSSL_SESSION_free(session); }
  4333. session = wolfSSL_get1_session(ssl);
  4334. return res.find("200 OK") != std::string::npos;
  4335. };
  4336. ASSERT_TRUE(get(PORT));
  4337. EXPECT_FALSE(get(PORT + 1));
  4338. ASSERT_TRUE(get(PORT));
  4339. ASSERT_TRUE(replace_client_ca(svr));
  4340. EXPECT_FALSE(get(PORT));
  4341. }
  4342. #endif
  4343. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4344. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4345. ASSERT_TRUE(svr.is_valid());
  4346. svr.Get("/test", [](const Request &, Response &res) {
  4347. res.set_content("ok", "text/plain");
  4348. });
  4349. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4350. auto se = detail::scope_exit([&] {
  4351. svr.stop();
  4352. t.join();
  4353. ASSERT_FALSE(svr.is_running());
  4354. });
  4355. svr.wait_until_ready();
  4356. // A connection that sends no ClientHello keeps its handshake in progress,
  4357. // once the server has had a moment to start it.
  4358. auto error = Error::Success;
  4359. auto sock = detail::create_client_socket(
  4360. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4361. /*connection_timeout_sec=*/5, 0,
  4362. /*read_timeout_sec=*/5, 0,
  4363. /*write_timeout_sec=*/5, 0, std::string(), error);
  4364. ASSERT_NE(INVALID_SOCKET, sock);
  4365. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4366. std::string cert_pem, key_pem;
  4367. read_file(SERVER_CERT_FILE, cert_pem);
  4368. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4369. auto update = std::async(std::launch::async, [&]() {
  4370. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4371. });
  4372. EXPECT_EQ(std::future_status::timeout,
  4373. update.wait_for(std::chrono::milliseconds(200)));
  4374. detail::close_socket(sock);
  4375. EXPECT_TRUE(update.get());
  4376. SSLClient cli(HOST, PORT);
  4377. cli.enable_server_certificate_verification(false);
  4378. auto res = cli.Get("/test");
  4379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4380. EXPECT_EQ(StatusCode::OK_200, res->status);
  4381. }
  4382. #endif
  4383. TEST(ErrorHandlerTest, ContentLength) {
  4384. Server svr;
  4385. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4386. res.status = StatusCode::OK_200;
  4387. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4388. "text/html"); // <= Content-Length still 13
  4389. });
  4390. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4391. res.set_content("Hello World!\n", "text/plain");
  4392. res.status = 524;
  4393. });
  4394. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4395. auto se = detail::scope_exit([&] {
  4396. svr.stop();
  4397. thread.join();
  4398. ASSERT_FALSE(svr.is_running());
  4399. });
  4400. svr.wait_until_ready();
  4401. {
  4402. Client cli(HOST, PORT);
  4403. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4405. EXPECT_EQ(StatusCode::OK_200, res->status);
  4406. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4407. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4408. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4409. }
  4410. }
  4411. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4412. TEST(ExceptionTest, WithoutExceptionHandler) {
  4413. Server svr;
  4414. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4415. throw std::runtime_error("exception...");
  4416. });
  4417. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4418. throw std::runtime_error("exception\r\n...");
  4419. });
  4420. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4421. auto se = detail::scope_exit([&] {
  4422. svr.stop();
  4423. listen_thread.join();
  4424. ASSERT_FALSE(svr.is_running());
  4425. });
  4426. svr.wait_until_ready();
  4427. Client cli("localhost", PORT);
  4428. {
  4429. auto res = cli.Get("/exception");
  4430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4431. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4432. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4433. }
  4434. {
  4435. auto res = cli.Get("/unknown");
  4436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4437. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4438. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4439. }
  4440. }
  4441. TEST(ExceptionTest, WithExceptionHandler) {
  4442. Server svr;
  4443. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4444. std::exception_ptr ep) {
  4445. EXPECT_FALSE(ep == nullptr);
  4446. try {
  4447. std::rethrow_exception(ep);
  4448. } catch (std::exception &e) {
  4449. EXPECT_EQ("abc", std::string(e.what()));
  4450. } catch (...) {}
  4451. res.status = StatusCode::InternalServerError_500;
  4452. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4453. "text/html"); // <= Content-Length still 13 at this point
  4454. });
  4455. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4456. res.set_content("Hello World!\n", "text/plain");
  4457. throw std::runtime_error("abc");
  4458. });
  4459. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4460. auto se = detail::scope_exit([&] {
  4461. svr.stop();
  4462. thread.join();
  4463. ASSERT_FALSE(svr.is_running());
  4464. });
  4465. svr.wait_until_ready();
  4466. for (size_t i = 0; i < 10; i++) {
  4467. Client cli(HOST, PORT);
  4468. for (size_t j = 0; j < 100; j++) {
  4469. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4471. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4472. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4473. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4474. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4475. }
  4476. cli.set_keep_alive(true);
  4477. for (size_t j = 0; j < 100; j++) {
  4478. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4480. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4481. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4482. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4483. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4484. }
  4485. }
  4486. }
  4487. TEST(ExceptionTest, AndErrorHandler) {
  4488. Server svr;
  4489. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4490. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4491. });
  4492. svr.set_exception_handler(
  4493. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4494. EXPECT_FALSE(ep == nullptr);
  4495. try {
  4496. std::rethrow_exception(ep);
  4497. } catch (std::exception &e) {
  4498. res.set_content(e.what(), "text/html");
  4499. } catch (...) {}
  4500. res.status = StatusCode::InternalServerError_500;
  4501. });
  4502. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4503. throw std::runtime_error("EXCEPTION");
  4504. });
  4505. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4506. res.set_content("ERROR", "text/html");
  4507. res.status = StatusCode::InternalServerError_500;
  4508. });
  4509. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4510. auto se = detail::scope_exit([&] {
  4511. svr.stop();
  4512. thread.join();
  4513. ASSERT_FALSE(svr.is_running());
  4514. });
  4515. svr.wait_until_ready();
  4516. Client cli(HOST, PORT);
  4517. {
  4518. auto res = cli.Get("/exception");
  4519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4520. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4521. EXPECT_EQ("EXCEPTION", res->body);
  4522. }
  4523. {
  4524. auto res = cli.Get("/error");
  4525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4526. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4527. EXPECT_EQ("ERROR", res->body);
  4528. }
  4529. {
  4530. auto res = cli.Get("/invalid");
  4531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4532. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4533. EXPECT_EQ("NOT_FOUND", res->body);
  4534. }
  4535. }
  4536. #endif
  4537. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4538. // process_request() wraps only routing() in a try/catch, so an exception from
  4539. // any other user callback used to unwind into the task queue - which does not
  4540. // catch - and terminate the process. Each test below runs the server on a
  4541. // single worker thread: a guard that catches the exception but still loses the
  4542. // thread would otherwise be hidden by a spare worker serving the follow-up
  4543. // request. Note that a regression here aborts the whole test binary rather
  4544. // than failing one test.
  4545. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4546. Server svr;
  4547. svr.new_task_queue = [] { return new ThreadPool(1); };
  4548. std::atomic<int> reported{0};
  4549. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4550. if (err == Error::UserCallbackException) { reported++; }
  4551. });
  4552. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4553. res.set_content_provider(
  4554. 1024, "text/plain",
  4555. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4556. sink.write("hello", 5);
  4557. throw std::runtime_error("from the content provider");
  4558. });
  4559. });
  4560. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4561. res.set_content("ok", "text/plain");
  4562. });
  4563. auto port = svr.bind_to_any_port(HOST);
  4564. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4565. auto se = detail::scope_exit([&] {
  4566. svr.stop();
  4567. listen_thread.join();
  4568. ASSERT_FALSE(svr.is_running());
  4569. });
  4570. svr.wait_until_ready();
  4571. {
  4572. Client cli(HOST, port);
  4573. cli.set_read_timeout(5, 0);
  4574. EXPECT_FALSE(cli.Get("/throw"));
  4575. }
  4576. EXPECT_TRUE(svr.is_running());
  4577. EXPECT_EQ(1, reported.load());
  4578. // A request on a fresh connection is still served.
  4579. {
  4580. Client cli(HOST, port);
  4581. auto res = cli.Get("/ok");
  4582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4583. EXPECT_EQ(StatusCode::OK_200, res->status);
  4584. EXPECT_EQ("ok", res->body);
  4585. }
  4586. }
  4587. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4588. Server svr;
  4589. svr.new_task_queue = [] { return new ThreadPool(1); };
  4590. std::atomic<bool> should_throw{true};
  4591. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4592. res.set_content("hi", "text/plain");
  4593. });
  4594. svr.set_post_routing_handler(
  4595. [&](const Request & /*req*/, Response & /*res*/) {
  4596. if (should_throw) {
  4597. throw std::runtime_error("from the post-routing handler");
  4598. }
  4599. });
  4600. auto port = svr.bind_to_any_port(HOST);
  4601. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4602. auto se = detail::scope_exit([&] {
  4603. svr.stop();
  4604. listen_thread.join();
  4605. ASSERT_FALSE(svr.is_running());
  4606. });
  4607. svr.wait_until_ready();
  4608. {
  4609. Client cli(HOST, port);
  4610. cli.set_read_timeout(5, 0);
  4611. EXPECT_FALSE(cli.Get("/hi"));
  4612. }
  4613. EXPECT_TRUE(svr.is_running());
  4614. should_throw = false;
  4615. {
  4616. Client cli(HOST, port);
  4617. auto res = cli.Get("/hi");
  4618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4619. EXPECT_EQ(StatusCode::OK_200, res->status);
  4620. EXPECT_EQ("hi", res->body);
  4621. }
  4622. }
  4623. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4624. // The guard reports the caught exception through the error logger, which is
  4625. // a user callback too. A logger that throws has to be contained as well, or
  4626. // the process would terminate from inside the catch.
  4627. Server svr;
  4628. svr.new_task_queue = [] { return new ThreadPool(1); };
  4629. std::atomic<int> reported{0};
  4630. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4631. if (err == Error::UserCallbackException) {
  4632. reported++;
  4633. throw std::runtime_error("from the error logger");
  4634. }
  4635. });
  4636. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4637. res.set_content_provider(
  4638. 1024, "text/plain",
  4639. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4640. sink.write("hello", 5);
  4641. throw std::runtime_error("from the content provider");
  4642. });
  4643. });
  4644. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4645. res.set_content("ok", "text/plain");
  4646. });
  4647. auto port = svr.bind_to_any_port(HOST);
  4648. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4649. auto se = detail::scope_exit([&] {
  4650. svr.stop();
  4651. listen_thread.join();
  4652. ASSERT_FALSE(svr.is_running());
  4653. });
  4654. svr.wait_until_ready();
  4655. {
  4656. Client cli(HOST, port);
  4657. cli.set_read_timeout(5, 0);
  4658. EXPECT_FALSE(cli.Get("/throw"));
  4659. }
  4660. EXPECT_TRUE(svr.is_running());
  4661. EXPECT_EQ(1, reported.load());
  4662. {
  4663. Client cli(HOST, port);
  4664. auto res = cli.Get("/ok");
  4665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4666. EXPECT_EQ(StatusCode::OK_200, res->status);
  4667. EXPECT_EQ("ok", res->body);
  4668. }
  4669. }
  4670. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4671. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4672. // so the exception unwinds through the ws::WebSocket object on its way to
  4673. // the guard. None of the HTTP cases above cross that.
  4674. Server svr;
  4675. svr.new_task_queue = [] { return new ThreadPool(1); };
  4676. std::atomic<int> reported{0};
  4677. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4678. if (err == Error::UserCallbackException) { reported++; }
  4679. });
  4680. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4681. throw std::runtime_error("from the WebSocket handler");
  4682. });
  4683. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4684. res.set_content("ok", "text/plain");
  4685. });
  4686. auto port = svr.bind_to_any_port(HOST);
  4687. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4688. auto se = detail::scope_exit([&] {
  4689. svr.stop();
  4690. listen_thread.join();
  4691. ASSERT_FALSE(svr.is_running());
  4692. });
  4693. svr.wait_until_ready();
  4694. {
  4695. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4696. "/ws");
  4697. auto res = client.connect();
  4698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4699. // The server dropped the connection instead of dying.
  4700. std::string msg;
  4701. EXPECT_FALSE(client.read(msg));
  4702. client.close();
  4703. }
  4704. EXPECT_TRUE(svr.is_running());
  4705. EXPECT_EQ(1, reported.load());
  4706. {
  4707. Client cli(HOST, port);
  4708. auto res = cli.Get("/ok");
  4709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4710. EXPECT_EQ(StatusCode::OK_200, res->status);
  4711. EXPECT_EQ("ok", res->body);
  4712. }
  4713. }
  4714. #ifdef CPPHTTPLIB_SSL_ENABLED
  4715. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4716. // SSLServer::process_and_close_socket() is a separate overload with its own
  4717. // guard, so it is exercised on its own.
  4718. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4719. ASSERT_TRUE(svr.is_valid());
  4720. svr.new_task_queue = [] { return new ThreadPool(1); };
  4721. std::atomic<int> reported{0};
  4722. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4723. if (err == Error::UserCallbackException) { reported++; }
  4724. });
  4725. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4726. res.set_content_provider(
  4727. 1024, "text/plain",
  4728. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4729. sink.write("hello", 5);
  4730. throw std::runtime_error("from the content provider");
  4731. });
  4732. });
  4733. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4734. res.set_content("ok", "text/plain");
  4735. });
  4736. auto port = svr.bind_to_any_port(HOST);
  4737. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4738. auto se = detail::scope_exit([&] {
  4739. svr.stop();
  4740. listen_thread.join();
  4741. ASSERT_FALSE(svr.is_running());
  4742. });
  4743. svr.wait_until_ready();
  4744. {
  4745. SSLClient cli(HOST, port);
  4746. cli.enable_server_certificate_verification(false);
  4747. cli.set_read_timeout(5, 0);
  4748. EXPECT_FALSE(cli.Get("/throw"));
  4749. }
  4750. EXPECT_TRUE(svr.is_running());
  4751. EXPECT_EQ(1, reported.load());
  4752. {
  4753. SSLClient cli(HOST, port);
  4754. cli.enable_server_certificate_verification(false);
  4755. auto res = cli.Get("/ok");
  4756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4757. EXPECT_EQ(StatusCode::OK_200, res->status);
  4758. EXPECT_EQ("ok", res->body);
  4759. }
  4760. }
  4761. #endif
  4762. #endif
  4763. TEST(NoContentTest, ContentLength) {
  4764. Server svr;
  4765. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4766. res.status = StatusCode::NoContent_204;
  4767. });
  4768. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4769. auto se = detail::scope_exit([&] {
  4770. svr.stop();
  4771. thread.join();
  4772. ASSERT_FALSE(svr.is_running());
  4773. });
  4774. svr.wait_until_ready();
  4775. {
  4776. Client cli(HOST, PORT);
  4777. auto res = cli.Get("/hi");
  4778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4779. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4780. // RFC 9110 8.6: none in a 204 response
  4781. EXPECT_FALSE(res->has_header("Content-Length"));
  4782. }
  4783. }
  4784. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4785. Server svr;
  4786. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4787. res.set_header("Content-Length", "5");
  4788. res.set_content("hello world", "text/plain");
  4789. });
  4790. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4791. // A body that reads as the last chunk, were it taken as chunked
  4792. res.set_header("Transfer-Encoding", "chunked");
  4793. res.set_content("0\r\n\r\n", "text/plain");
  4794. });
  4795. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4796. res.set_header("Content-Length", "2");
  4797. res.set_content_provider(5, "text/plain",
  4798. [](size_t offset, size_t length, DataSink &sink) {
  4799. sink.write(&"hello"[offset], length);
  4800. return true;
  4801. });
  4802. });
  4803. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4804. res.set_header("Content-Length", "1234");
  4805. });
  4806. thread t = thread([&] { svr.listen(HOST, PORT); });
  4807. auto se = detail::scope_exit([&] {
  4808. svr.stop();
  4809. t.join();
  4810. ASSERT_FALSE(svr.is_running());
  4811. });
  4812. svr.wait_until_ready();
  4813. Client cli(HOST, PORT);
  4814. cli.set_read_timeout(1, 0);
  4815. auto expect_body = [&](const Result &res, const std::string &body) {
  4816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4817. EXPECT_EQ(body, res->body);
  4818. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4819. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4820. };
  4821. Headers identity{{"Accept-Encoding", ""}};
  4822. expect_body(cli.Get("/body", identity), "hello world");
  4823. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4824. expect_body(cli.Get("/body",
  4825. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4826. "he");
  4827. expect_body(cli.Get("/provider", identity), "hello");
  4828. expect_body(cli.Get("/empty", identity), "");
  4829. // A HEAD response may give the length of the body a GET would get.
  4830. auto res = cli.Head("/empty");
  4831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4832. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4833. }
  4834. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4835. Server svr;
  4836. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4837. res.set_content("short", "text/plain");
  4838. });
  4839. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4840. res.body += " with a footer";
  4841. res.set_header("Transfer-Encoding", "chunked");
  4842. });
  4843. thread t = thread([&] { svr.listen(HOST, PORT); });
  4844. auto se = detail::scope_exit([&] {
  4845. svr.stop();
  4846. t.join();
  4847. ASSERT_FALSE(svr.is_running());
  4848. });
  4849. svr.wait_until_ready();
  4850. Client cli(HOST, PORT);
  4851. cli.set_read_timeout(1, 0);
  4852. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4854. EXPECT_EQ("short with a footer", res->body);
  4855. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4856. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4857. }
  4858. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4859. Server svr;
  4860. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4861. res.set_header("Content-Length", "3");
  4862. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  4863. sink.write("abc", 3);
  4864. sink.done();
  4865. return true;
  4866. });
  4867. });
  4868. thread t = thread([&] { svr.listen(HOST, PORT); });
  4869. auto se = detail::scope_exit([&] {
  4870. svr.stop();
  4871. t.join();
  4872. ASSERT_FALSE(svr.is_running());
  4873. });
  4874. svr.wait_until_ready();
  4875. Client cli(HOST, PORT);
  4876. cli.set_keep_alive(true);
  4877. auto res = cli.Get("/");
  4878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4879. EXPECT_EQ("abc", res->body);
  4880. EXPECT_FALSE(res->has_header("Content-Length"));
  4881. EXPECT_EQ("close", res->get_header_value("Connection"));
  4882. EXPECT_FALSE(res->has_header("Keep-Alive"));
  4883. // No body to delimit
  4884. auto head = cli.Head("/");
  4885. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  4886. EXPECT_FALSE(head->has_header("Connection"));
  4887. }
  4888. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4889. #ifdef CPPHTTPLIB_SSL_ENABLED
  4890. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4891. ASSERT_TRUE(svr.is_valid());
  4892. #else
  4893. Server svr;
  4894. #endif
  4895. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4896. if (req.path == "/routing_handler") {
  4897. res.set_header("PRE_ROUTING", "on");
  4898. res.set_content("Routing Handler", "text/plain");
  4899. return httplib::Server::HandlerResponse::Handled;
  4900. }
  4901. return httplib::Server::HandlerResponse::Unhandled;
  4902. });
  4903. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4904. res.set_content("Error", "text/html");
  4905. });
  4906. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4907. if (req.path == "/routing_handler") {
  4908. res.set_header("POST_ROUTING", "on");
  4909. }
  4910. });
  4911. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4912. res.set_content("Hello World!\n", "text/plain");
  4913. });
  4914. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4915. auto se = detail::scope_exit([&] {
  4916. svr.stop();
  4917. thread.join();
  4918. ASSERT_FALSE(svr.is_running());
  4919. });
  4920. svr.wait_until_ready();
  4921. {
  4922. #ifdef CPPHTTPLIB_SSL_ENABLED
  4923. SSLClient cli(HOST, PORT);
  4924. cli.enable_server_certificate_verification(false);
  4925. #else
  4926. Client cli(HOST, PORT);
  4927. #endif
  4928. auto res = cli.Get("/routing_handler");
  4929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4930. EXPECT_EQ(StatusCode::OK_200, res->status);
  4931. EXPECT_EQ("Routing Handler", res->body);
  4932. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4933. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4934. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4935. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4936. }
  4937. {
  4938. #ifdef CPPHTTPLIB_SSL_ENABLED
  4939. SSLClient cli(HOST, PORT);
  4940. cli.enable_server_certificate_verification(false);
  4941. #else
  4942. Client cli(HOST, PORT);
  4943. #endif
  4944. auto res = cli.Get("/hi");
  4945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4946. EXPECT_EQ(StatusCode::OK_200, res->status);
  4947. EXPECT_EQ("Hello World!\n", res->body);
  4948. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4949. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4950. }
  4951. {
  4952. #ifdef CPPHTTPLIB_SSL_ENABLED
  4953. SSLClient cli(HOST, PORT);
  4954. cli.enable_server_certificate_verification(false);
  4955. #else
  4956. Client cli(HOST, PORT);
  4957. #endif
  4958. auto res = cli.Get("/aaa");
  4959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4960. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4961. EXPECT_EQ("Error", res->body);
  4962. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4963. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4964. }
  4965. }
  4966. TEST(RequestHandlerTest, PreRequestHandler) {
  4967. auto route_path = "/user/:user";
  4968. Server svr;
  4969. svr.Get("/hi", [](const Request &, Response &res) {
  4970. res.set_content("hi", "text/plain");
  4971. });
  4972. svr.Get(route_path, [](const Request &req, Response &res) {
  4973. res.set_content(req.path_params.at("user"), "text/plain");
  4974. });
  4975. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4976. if (req.matched_route == route_path) {
  4977. auto user = req.path_params.at("user");
  4978. if (user != "john") {
  4979. res.status = StatusCode::Forbidden_403;
  4980. res.set_content("error", "text/html");
  4981. return Server::HandlerResponse::Handled;
  4982. }
  4983. }
  4984. return Server::HandlerResponse::Unhandled;
  4985. });
  4986. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4987. auto se = detail::scope_exit([&] {
  4988. svr.stop();
  4989. thread.join();
  4990. ASSERT_FALSE(svr.is_running());
  4991. });
  4992. svr.wait_until_ready();
  4993. Client cli(HOST, PORT);
  4994. {
  4995. auto res = cli.Get("/hi");
  4996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4997. EXPECT_EQ(StatusCode::OK_200, res->status);
  4998. EXPECT_EQ("hi", res->body);
  4999. }
  5000. {
  5001. auto res = cli.Get("/user/john");
  5002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5003. EXPECT_EQ(StatusCode::OK_200, res->status);
  5004. EXPECT_EQ("john", res->body);
  5005. }
  5006. {
  5007. auto res = cli.Get("/user/invalid-user");
  5008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5009. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5010. EXPECT_EQ("error", res->body);
  5011. }
  5012. }
  5013. // The pre-request handler must run before the request body is read, so a
  5014. // rejected request never forces the server to buffer a (potentially large)
  5015. // body. Here the posted body is larger than the payload limit: if the body
  5016. // were read first the server would answer 413, but because the pre-request
  5017. // handler runs first it answers 403 and the body is never read.
  5018. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5019. Server svr;
  5020. svr.set_payload_max_length(8);
  5021. auto handler_ran = false;
  5022. svr.Post("/reject", [&](const Request &req, Response &res) {
  5023. handler_ran = true;
  5024. res.set_content(req.body, "text/plain");
  5025. });
  5026. svr.Post("/accept", [](const Request &req, Response &res) {
  5027. res.set_content(req.body, "text/plain");
  5028. });
  5029. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5030. if (req.matched_route == "/reject") {
  5031. res.status = StatusCode::Forbidden_403;
  5032. res.set_content("denied", "text/plain");
  5033. return Server::HandlerResponse::Handled;
  5034. }
  5035. return Server::HandlerResponse::Unhandled;
  5036. });
  5037. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5038. auto se = detail::scope_exit([&] {
  5039. svr.stop();
  5040. thread.join();
  5041. ASSERT_FALSE(svr.is_running());
  5042. });
  5043. svr.wait_until_ready();
  5044. Client cli(HOST, PORT);
  5045. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5046. // rejects with 403 before the body is read, so 413 is never reached.
  5047. {
  5048. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5050. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5051. EXPECT_EQ("denied", res->body);
  5052. EXPECT_FALSE(handler_ran);
  5053. }
  5054. // An approved route still reads the body and enforces the payload limit.
  5055. {
  5056. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5058. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5059. }
  5060. }
  5061. TEST(UserDataTest, BasicOperations) {
  5062. httplib::UserData ud;
  5063. // Initially empty
  5064. EXPECT_FALSE(ud.has("key"));
  5065. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5066. // set and get
  5067. ud.set("key", 42);
  5068. EXPECT_TRUE(ud.has("key"));
  5069. auto *p = ud.get<int>("key");
  5070. ASSERT_NE(nullptr, p);
  5071. EXPECT_EQ(42, *p);
  5072. // Type mismatch → nullptr
  5073. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5074. // Overwrite with different type
  5075. ud.set("key", std::string("hello"));
  5076. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5077. auto *s = ud.get<std::string>("key");
  5078. ASSERT_NE(nullptr, s);
  5079. EXPECT_EQ("hello", *s);
  5080. // erase
  5081. ud.erase("key");
  5082. EXPECT_FALSE(ud.has("key"));
  5083. // clear
  5084. ud.set("a", 1);
  5085. ud.set("b", 2);
  5086. ud.clear();
  5087. EXPECT_FALSE(ud.has("a"));
  5088. EXPECT_FALSE(ud.has("b"));
  5089. }
  5090. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5091. struct AuthCtx {
  5092. std::string user_id;
  5093. };
  5094. Server svr;
  5095. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5096. res.user_data.set("auth", AuthCtx{"alice"});
  5097. return Server::HandlerResponse::Unhandled;
  5098. });
  5099. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5100. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5101. ASSERT_NE(nullptr, ctx);
  5102. res.set_content("Hello " + ctx->user_id, "text/plain");
  5103. });
  5104. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5105. auto se = detail::scope_exit([&] {
  5106. svr.stop();
  5107. thread.join();
  5108. ASSERT_FALSE(svr.is_running());
  5109. });
  5110. svr.wait_until_ready();
  5111. Client cli(HOST, PORT);
  5112. auto res = cli.Get("/me");
  5113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5114. EXPECT_EQ(StatusCode::OK_200, res->status);
  5115. EXPECT_EQ("Hello alice", res->body);
  5116. }
  5117. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5118. struct RoleCtx {
  5119. std::string role;
  5120. };
  5121. Server svr;
  5122. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5123. res.user_data.set("role", RoleCtx{"admin"});
  5124. return Server::HandlerResponse::Unhandled;
  5125. });
  5126. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5127. auto *ctx = res.user_data.get<RoleCtx>("role");
  5128. ASSERT_NE(nullptr, ctx);
  5129. res.set_content(ctx->role, "text/plain");
  5130. });
  5131. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5132. auto se = detail::scope_exit([&] {
  5133. svr.stop();
  5134. thread.join();
  5135. ASSERT_FALSE(svr.is_running());
  5136. });
  5137. svr.wait_until_ready();
  5138. Client cli(HOST, PORT);
  5139. auto res = cli.Get("/role");
  5140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5141. EXPECT_EQ(StatusCode::OK_200, res->status);
  5142. EXPECT_EQ("admin", res->body);
  5143. }
  5144. TEST(InvalidFormatTest, StatusCode) {
  5145. Server svr;
  5146. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5147. res.set_content("Hello World!\n", "text/plain");
  5148. res.status = 9999; // Status should be a three-digit code...
  5149. });
  5150. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5151. auto se = detail::scope_exit([&] {
  5152. svr.stop();
  5153. thread.join();
  5154. ASSERT_FALSE(svr.is_running());
  5155. });
  5156. svr.wait_until_ready();
  5157. {
  5158. Client cli(HOST, PORT);
  5159. auto res = cli.Get("/hi");
  5160. ASSERT_FALSE(res);
  5161. }
  5162. }
  5163. TEST(URLFragmentTest, WithFragment) {
  5164. Server svr;
  5165. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5166. EXPECT_TRUE(req.target == "/hi");
  5167. });
  5168. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5169. auto se = detail::scope_exit([&] {
  5170. svr.stop();
  5171. thread.join();
  5172. ASSERT_FALSE(svr.is_running());
  5173. });
  5174. svr.wait_until_ready();
  5175. {
  5176. Client cli(HOST, PORT);
  5177. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5178. EXPECT_TRUE(res);
  5179. EXPECT_EQ(StatusCode::OK_200, res->status);
  5180. res = cli.Get("/hi%23key1=val1=key2=val2");
  5181. EXPECT_TRUE(res);
  5182. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5183. }
  5184. }
  5185. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5186. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5187. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5188. Server svr;
  5189. std::vector<std::string> targets;
  5190. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5191. targets.push_back(req.target);
  5192. });
  5193. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5194. auto se = detail::scope_exit([&] {
  5195. svr.stop();
  5196. thread.join();
  5197. ASSERT_FALSE(svr.is_running());
  5198. });
  5199. svr.wait_until_ready();
  5200. Client cli(HOST, PORT);
  5201. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5202. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5203. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5204. // A '?' after the '#' belongs to the fragment, not to the query.
  5205. Request req;
  5206. req.method = "GET";
  5207. req.path = "/hi#f?x=1";
  5208. req.params.emplace("a", "1");
  5209. Response res;
  5210. auto error = Error::Success;
  5211. EXPECT_TRUE(cli.send(req, res, error));
  5212. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5213. "/hi?a=1"}),
  5214. targets);
  5215. }
  5216. TEST(HeaderWriter, SetHeaderWriter) {
  5217. Server svr;
  5218. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5219. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5220. return detail::write_headers(strm, hdrs);
  5221. });
  5222. svr.Get("/hi", [](const Request &req, Response &res) {
  5223. auto it = req.headers.find("CustomClientHeader");
  5224. EXPECT_TRUE(it != req.headers.end());
  5225. EXPECT_EQ(it->second, "CustomClientValue");
  5226. res.set_content("Hello World!\n", "text/plain");
  5227. });
  5228. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5229. auto se = detail::scope_exit([&] {
  5230. svr.stop();
  5231. thread.join();
  5232. ASSERT_FALSE(svr.is_running());
  5233. });
  5234. svr.wait_until_ready();
  5235. {
  5236. Client cli(HOST, PORT);
  5237. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5238. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5239. return detail::write_headers(strm, hdrs);
  5240. });
  5241. auto res = cli.Get("/hi");
  5242. EXPECT_TRUE(res);
  5243. EXPECT_EQ(StatusCode::OK_200, res->status);
  5244. auto it = res->headers.find("CustomServerHeader");
  5245. EXPECT_TRUE(it != res->headers.end());
  5246. EXPECT_EQ(it->second, "CustomServerValue");
  5247. }
  5248. }
  5249. class ServerTest : public ::testing::Test {
  5250. protected:
  5251. ServerTest()
  5252. : cli_(HOST, PORT)
  5253. #ifdef CPPHTTPLIB_SSL_ENABLED
  5254. ,
  5255. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5256. #endif
  5257. {
  5258. #ifdef CPPHTTPLIB_SSL_ENABLED
  5259. cli_.enable_server_certificate_verification(false);
  5260. #endif
  5261. // Allow LARGE_DATA (100MB) responses
  5262. cli_.set_payload_max_length(200 * 1024 * 1024);
  5263. }
  5264. virtual void SetUp() {
  5265. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5266. svr_.set_payload_max_length(200 * 1024 * 1024);
  5267. svr_.set_mount_point("/", "./www");
  5268. svr_.set_mount_point("/mount", "./www2");
  5269. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5270. svr_.Get("/hi",
  5271. [&](const Request & /*req*/, Response &res) {
  5272. res.set_content("Hello World!", "text/plain");
  5273. })
  5274. .Get("/file_content",
  5275. [&](const Request & /*req*/, Response &res) {
  5276. res.set_file_content("./www/dir/test.html");
  5277. })
  5278. .Get("/file_content_with_content_type",
  5279. [&](const Request & /*req*/, Response &res) {
  5280. res.set_file_content("./www/file", "text/plain");
  5281. })
  5282. .Get("/invalid_file_content",
  5283. [&](const Request & /*req*/, Response &res) {
  5284. res.set_file_content("./www/dir/invalid_file_path");
  5285. })
  5286. .Get("/http_response_splitting",
  5287. [&](const Request & /*req*/, Response &res) {
  5288. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5289. EXPECT_EQ(0U, res.headers.size());
  5290. EXPECT_FALSE(res.has_header("a"));
  5291. res.set_header("a", "1\nSet-Cookie: a=1");
  5292. EXPECT_EQ(0U, res.headers.size());
  5293. EXPECT_FALSE(res.has_header("a"));
  5294. res.set_header("a", "1\rSet-Cookie: a=1");
  5295. EXPECT_EQ(0U, res.headers.size());
  5296. EXPECT_FALSE(res.has_header("a"));
  5297. res.set_header("a\r\nb", "0");
  5298. EXPECT_EQ(0U, res.headers.size());
  5299. EXPECT_FALSE(res.has_header("a"));
  5300. res.set_header("a\rb", "0");
  5301. EXPECT_EQ(0U, res.headers.size());
  5302. EXPECT_FALSE(res.has_header("a"));
  5303. res.set_header("a\nb", "0");
  5304. EXPECT_EQ(0U, res.headers.size());
  5305. EXPECT_FALSE(res.has_header("a"));
  5306. res.set_redirect("1\r\nSet-Cookie: a=1");
  5307. EXPECT_EQ(0U, res.headers.size());
  5308. EXPECT_FALSE(res.has_header("Location"));
  5309. })
  5310. .Get("/slow",
  5311. [&](const Request & /*req*/, Response &res) {
  5312. std::this_thread::sleep_for(std::chrono::seconds(4));
  5313. res.set_content("slow", "text/plain");
  5314. })
  5315. #if 0
  5316. .Post("/slowpost",
  5317. [&](const Request & /*req*/, Response &res) {
  5318. std::this_thread::sleep_for(std::chrono::seconds(2));
  5319. res.set_content("slow", "text/plain");
  5320. })
  5321. #endif
  5322. .Get("/remote_addr",
  5323. [&](const Request &req, Response &res) {
  5324. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5325. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5326. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5327. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5328. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5329. #endif
  5330. res.set_content(req.remote_addr, "text/plain");
  5331. })
  5332. .Get("/local_addr",
  5333. [&](const Request &req, Response &res) {
  5334. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5335. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5336. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5337. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5338. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5339. #endif
  5340. auto local_addr = req.local_addr;
  5341. auto local_port = std::to_string(req.local_port);
  5342. res.set_content(local_addr.append(":").append(local_port),
  5343. "text/plain");
  5344. })
  5345. .Get("/endwith%",
  5346. [&](const Request & /*req*/, Response &res) {
  5347. res.set_content("Hello World!", "text/plain");
  5348. })
  5349. .Get("/a\\+\\+b",
  5350. [&](const Request &req, Response &res) {
  5351. ASSERT_TRUE(req.has_param("a +b"));
  5352. auto val = req.get_param_value("a +b");
  5353. res.set_content(val, "text/plain");
  5354. })
  5355. .Get("/", [&](const Request & /*req*/,
  5356. Response &res) { res.set_redirect("/hi"); })
  5357. .Post("/1",
  5358. [](const Request & /*req*/, Response &res) {
  5359. res.set_redirect("/2", StatusCode::SeeOther_303);
  5360. })
  5361. .Get("/2",
  5362. [](const Request & /*req*/, Response &res) {
  5363. res.set_content("redirected.", "text/plain");
  5364. res.status = StatusCode::OK_200;
  5365. })
  5366. .Post("/person",
  5367. [&](const Request &req, Response &res) {
  5368. if (req.has_param("name") && req.has_param("note")) {
  5369. persons_[req.get_param_value("name")] =
  5370. req.get_param_value("note");
  5371. } else {
  5372. res.status = StatusCode::BadRequest_400;
  5373. }
  5374. })
  5375. .Put("/person",
  5376. [&](const Request &req, Response &res) {
  5377. if (req.has_param("name") && req.has_param("note")) {
  5378. persons_[req.get_param_value("name")] =
  5379. req.get_param_value("note");
  5380. } else {
  5381. res.status = StatusCode::BadRequest_400;
  5382. }
  5383. })
  5384. .Get("/person/(.*)",
  5385. [&](const Request &req, Response &res) {
  5386. string name = req.matches[1];
  5387. if (persons_.find(name) != persons_.end()) {
  5388. auto note = persons_[name];
  5389. res.set_content(note, "text/plain");
  5390. } else {
  5391. res.status = StatusCode::NotFound_404;
  5392. }
  5393. })
  5394. .Delete("/person",
  5395. [&](const Request &req, Response &res) {
  5396. if (req.has_param("name")) {
  5397. string name = req.get_param_value("name");
  5398. if (persons_.find(name) != persons_.end()) {
  5399. persons_.erase(name);
  5400. res.set_content("DELETED", "text/plain");
  5401. } else {
  5402. res.status = StatusCode::NotFound_404;
  5403. }
  5404. } else {
  5405. res.status = StatusCode::BadRequest_400;
  5406. }
  5407. })
  5408. .Post("/x-www-form-urlencoded-json",
  5409. [&](const Request &req, Response &res) {
  5410. auto json = req.get_param_value("json");
  5411. ASSERT_EQ(JSON_DATA, json);
  5412. res.set_content(json, "appliation/json");
  5413. res.status = StatusCode::OK_200;
  5414. })
  5415. .Get("/streamed-chunked",
  5416. [&](const Request & /*req*/, Response &res) {
  5417. res.set_chunked_content_provider(
  5418. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5419. sink.os << "123";
  5420. sink.os << "456";
  5421. sink.os << "789";
  5422. sink.done();
  5423. return true;
  5424. });
  5425. })
  5426. .Get("/streamed-chunked-with-prohibited-trailer",
  5427. [&](const Request & /*req*/, Response &res) {
  5428. auto i = new int(0);
  5429. // Declare both a prohibited trailer (Content-Length) and an
  5430. // allowed one
  5431. res.set_header("Trailer", "Content-Length, X-Allowed");
  5432. res.set_chunked_content_provider(
  5433. "text/plain",
  5434. [i](size_t /*offset*/, DataSink &sink) {
  5435. switch (*i) {
  5436. case 0: sink.os << "123"; break;
  5437. case 1: sink.os << "456"; break;
  5438. case 2: sink.os << "789"; break;
  5439. case 3: {
  5440. sink.done_with_trailer(
  5441. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5442. } break;
  5443. }
  5444. (*i)++;
  5445. return true;
  5446. },
  5447. [i](bool success) {
  5448. EXPECT_TRUE(success);
  5449. delete i;
  5450. });
  5451. })
  5452. .Get("/streamed-chunked2",
  5453. [&](const Request & /*req*/, Response &res) {
  5454. auto i = new int(0);
  5455. res.set_chunked_content_provider(
  5456. "text/plain",
  5457. [i](size_t /*offset*/, DataSink &sink) {
  5458. switch (*i) {
  5459. case 0: sink.os << "123"; break;
  5460. case 1: sink.os << "456"; break;
  5461. case 2: sink.os << "789"; break;
  5462. case 3: sink.done(); break;
  5463. }
  5464. (*i)++;
  5465. return true;
  5466. },
  5467. [i](bool success) {
  5468. EXPECT_TRUE(success);
  5469. delete i;
  5470. });
  5471. })
  5472. .Get("/streamed-chunked-with-trailer",
  5473. [&](const Request & /*req*/, Response &res) {
  5474. auto i = new int(0);
  5475. res.set_header("Trailer", "Dummy1, Dummy2");
  5476. res.set_chunked_content_provider(
  5477. "text/plain",
  5478. [i](size_t /*offset*/, DataSink &sink) {
  5479. switch (*i) {
  5480. case 0: sink.os << "123"; break;
  5481. case 1: sink.os << "456"; break;
  5482. case 2: sink.os << "789"; break;
  5483. case 3: {
  5484. sink.done_with_trailer(
  5485. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5486. } break;
  5487. }
  5488. (*i)++;
  5489. return true;
  5490. },
  5491. [i](bool success) {
  5492. EXPECT_TRUE(success);
  5493. delete i;
  5494. });
  5495. })
  5496. .Get("/streamed",
  5497. [&](const Request & /*req*/, Response &res) {
  5498. res.set_content_provider(
  5499. 6, "text/plain",
  5500. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5501. sink.os << (offset < 3 ? "a" : "b");
  5502. return true;
  5503. });
  5504. })
  5505. .Get("/streamed-without-length",
  5506. [&](const Request & /*req*/, Response &res) {
  5507. auto data = new std::string("abcdefg");
  5508. res.set_content_provider(
  5509. "text/plain",
  5510. [data](size_t offset, DataSink &sink) {
  5511. if (offset < data->size()) {
  5512. sink.os << data->substr(offset);
  5513. }
  5514. sink.done();
  5515. return true;
  5516. },
  5517. [data](bool success) {
  5518. EXPECT_TRUE(success);
  5519. delete data;
  5520. });
  5521. })
  5522. .Get("/streamed-with-range",
  5523. [&](const Request &req, Response &res) {
  5524. auto data = new std::string("abcdefg");
  5525. // An explicit status keeps the server from picking the 206 it
  5526. // would otherwise choose for a ranged request, so the response
  5527. // is not a partial representation.
  5528. auto status = req.get_param_value("status");
  5529. if (status == "200") {
  5530. res.status = StatusCode::OK_200;
  5531. } else if (status == "403") {
  5532. res.status = StatusCode::Forbidden_403;
  5533. }
  5534. res.set_content_provider(
  5535. data->size(), "text/plain",
  5536. [data](size_t offset, size_t length, DataSink &sink) {
  5537. size_t DATA_CHUNK_SIZE = 4;
  5538. const auto &d = *data;
  5539. auto out_len =
  5540. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5541. auto ret =
  5542. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5543. EXPECT_TRUE(ret);
  5544. return true;
  5545. },
  5546. [data, &req](bool success) {
  5547. EXPECT_EQ(success, !req.has_param("error"));
  5548. delete data;
  5549. });
  5550. })
  5551. .Get("/streamed-cancel",
  5552. [&](const Request & /*req*/, Response &res) {
  5553. res.set_content_provider(
  5554. size_t(-1), "text/plain",
  5555. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5556. sink.os << "data_chunk";
  5557. return true;
  5558. });
  5559. })
  5560. .Get("/regex-with-delimiter",
  5561. [&](const Request &req, Response & /*res*/) {
  5562. ASSERT_TRUE(req.has_param("key"));
  5563. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5564. })
  5565. .Get("/with-range",
  5566. [&](const Request & /*req*/, Response &res) {
  5567. res.set_content("abcdefg", "text/plain");
  5568. })
  5569. .Get("/test-start-time",
  5570. [&](const Request &req, Response & /*res*/) {
  5571. EXPECT_NE(req.start_time_,
  5572. std::chrono::steady_clock::time_point::min());
  5573. })
  5574. .Get("/with-range-customized-response",
  5575. [&](const Request & /*req*/, Response &res) {
  5576. res.status = StatusCode::BadRequest_400;
  5577. res.set_content(JSON_DATA, "application/json");
  5578. })
  5579. .Post("/chunked",
  5580. [&](const Request &req, Response & /*res*/) {
  5581. EXPECT_EQ(req.body, "dechunked post body");
  5582. })
  5583. .Post("/large-chunked",
  5584. [&](const Request &req, Response & /*res*/) {
  5585. std::string expected(6 * 30 * 1024u, 'a');
  5586. EXPECT_EQ(req.body, expected);
  5587. })
  5588. .Post("/multipart",
  5589. [&](const Request &req, Response & /*res*/) {
  5590. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5591. req.form.get_field_count("text2") +
  5592. req.form.get_field_count("file3") +
  5593. req.form.get_field_count("file4"));
  5594. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5595. req.form.get_file_count("file2"));
  5596. ASSERT_TRUE(!req.form.has_file("???"));
  5597. ASSERT_TRUE(!req.form.has_field("???"));
  5598. ASSERT_TRUE(req.body.empty());
  5599. {
  5600. const auto &text = req.form.get_field("text1");
  5601. EXPECT_EQ("text default", text);
  5602. }
  5603. {
  5604. const auto &text = req.form.get_field("text2");
  5605. EXPECT_EQ("aωb", text);
  5606. }
  5607. {
  5608. const auto &file = req.form.get_file("file1");
  5609. EXPECT_EQ("hello.txt", file.filename);
  5610. EXPECT_EQ("text/plain", file.content_type);
  5611. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5612. }
  5613. {
  5614. const auto &file = req.form.get_file("file2");
  5615. EXPECT_EQ("world.json", file.filename);
  5616. EXPECT_EQ("application/json", file.content_type);
  5617. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5618. }
  5619. {
  5620. const auto &text = req.form.get_field("file3");
  5621. EXPECT_EQ(0u, text.size());
  5622. }
  5623. {
  5624. const auto &text = req.form.get_field("file4");
  5625. EXPECT_EQ(0u, text.size());
  5626. }
  5627. })
  5628. .Post("/multipart/multi_file_values",
  5629. [&](const Request &req, Response & /*res*/) {
  5630. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5631. req.form.get_field_count("multi_text1"));
  5632. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5633. ASSERT_TRUE(!req.form.has_file("???"));
  5634. ASSERT_TRUE(!req.form.has_field("???"));
  5635. ASSERT_TRUE(req.body.empty());
  5636. {
  5637. const auto &text = req.form.get_field("text");
  5638. EXPECT_EQ("default text", text);
  5639. }
  5640. {
  5641. const auto &text1_values = req.form.get_fields("multi_text1");
  5642. EXPECT_EQ(2u, text1_values.size());
  5643. EXPECT_EQ("aaaaa", text1_values[0]);
  5644. EXPECT_EQ("bbbbb", text1_values[1]);
  5645. }
  5646. {
  5647. const auto &file1_values = req.form.get_files("multi_file1");
  5648. EXPECT_EQ(2u, file1_values.size());
  5649. auto file1 = file1_values[0];
  5650. EXPECT_EQ(file1.filename, "hello.txt");
  5651. EXPECT_EQ(file1.content_type, "text/plain");
  5652. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5653. auto file2 = file1_values[1];
  5654. EXPECT_EQ(file2.filename, "world.json");
  5655. EXPECT_EQ(file2.content_type, "application/json");
  5656. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5657. }
  5658. })
  5659. .Post("/empty",
  5660. [&](const Request &req, Response &res) {
  5661. EXPECT_EQ(req.body, "");
  5662. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5663. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5664. res.set_content("empty", "text/plain");
  5665. })
  5666. .Post("/empty-no-content-type",
  5667. [&](const Request &req, Response &res) {
  5668. EXPECT_EQ(req.body, "");
  5669. EXPECT_FALSE(req.has_header("Content-Type"));
  5670. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5671. res.set_content("empty-no-content-type", "text/plain");
  5672. })
  5673. .Post("/path-only",
  5674. [&](const Request &req, Response &res) {
  5675. EXPECT_EQ(req.body, "");
  5676. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5677. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5678. res.set_content("path-only", "text/plain");
  5679. })
  5680. .Post("/path-headers-only",
  5681. [&](const Request &req, Response &res) {
  5682. EXPECT_EQ(req.body, "");
  5683. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5684. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5685. EXPECT_EQ("world", req.get_header_value("hello"));
  5686. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5687. res.set_content("path-headers-only", "text/plain");
  5688. })
  5689. .Post("/post-large",
  5690. [&](const Request &req, Response &res) {
  5691. EXPECT_EQ(req.body, LARGE_DATA);
  5692. res.set_content(req.body, "text/plain");
  5693. })
  5694. .Post("/post-loopback",
  5695. [&](const Request &, Response &res,
  5696. ContentReader const &content_reader) {
  5697. std::string body;
  5698. content_reader([&](const char *data, size_t data_length) {
  5699. body.append(data, data_length);
  5700. return true;
  5701. });
  5702. res.set_content(body, "text/plain");
  5703. })
  5704. .Put("/put-loopback",
  5705. [&](const Request &, Response &res,
  5706. ContentReader const &content_reader) {
  5707. std::string body;
  5708. content_reader([&](const char *data, size_t data_length) {
  5709. body.append(data, data_length);
  5710. return true;
  5711. });
  5712. res.set_content(body, "text/plain");
  5713. })
  5714. .Patch("/patch-loopback",
  5715. [&](const Request &, Response &res,
  5716. ContentReader const &content_reader) {
  5717. std::string body;
  5718. content_reader([&](const char *data, size_t data_length) {
  5719. body.append(data, data_length);
  5720. return true;
  5721. });
  5722. res.set_content(body, "text/plain");
  5723. })
  5724. .Put("/empty-no-content-type",
  5725. [&](const Request &req, Response &res) {
  5726. EXPECT_EQ(req.body, "");
  5727. EXPECT_FALSE(req.has_header("Content-Type"));
  5728. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5729. res.set_content("empty-no-content-type", "text/plain");
  5730. })
  5731. .Put("/put",
  5732. [&](const Request &req, Response &res) {
  5733. EXPECT_EQ(req.body, "PUT");
  5734. res.set_content(req.body, "text/plain");
  5735. })
  5736. .Put("/put-large",
  5737. [&](const Request &req, Response &res) {
  5738. EXPECT_EQ(req.body, LARGE_DATA);
  5739. res.set_content(req.body, "text/plain");
  5740. })
  5741. .Patch("/patch",
  5742. [&](const Request &req, Response &res) {
  5743. EXPECT_EQ(req.body, "PATCH");
  5744. res.set_content(req.body, "text/plain");
  5745. })
  5746. .Delete("/delete",
  5747. [&](const Request & /*req*/, Response &res) {
  5748. res.set_content("DELETE", "text/plain");
  5749. })
  5750. .Delete("/delete-body",
  5751. [&](const Request &req, Response &res) {
  5752. EXPECT_EQ(req.body, "content");
  5753. res.set_content(req.body, "text/plain");
  5754. })
  5755. .Options(R"(\*)",
  5756. [&](const Request & /*req*/, Response &res) {
  5757. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5758. })
  5759. .CustomRoute("PROPFIND", "/dav/:id",
  5760. [&](const Request &req, Response &res) {
  5761. res.set_header("x-body-size",
  5762. std::to_string(req.body.size()));
  5763. res.set_header("x-matched-route", req.matched_route);
  5764. res.set_header("x-dav-id", req.path_params.at("id"));
  5765. res.status = StatusCode::MultiStatus_207;
  5766. res.set_content(req.body, "application/xml");
  5767. })
  5768. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5769. [&](const Request &req, Response &res) {
  5770. res.set_header("x-dav-match", req.matches[1]);
  5771. res.status = StatusCode::MultiStatus_207;
  5772. })
  5773. .CustomRoute("MKCOL", "/dav-mkcol",
  5774. [&](const Request &req, Response &res) {
  5775. EXPECT_TRUE(req.body.empty());
  5776. res.status = StatusCode::Created_201;
  5777. })
  5778. .CustomRoute(
  5779. "REPORT", "/dav-report",
  5780. [&](const Request & /*req*/, Response &res,
  5781. const ContentReader &content_reader) {
  5782. std::string body;
  5783. content_reader([&](const char *data, size_t data_length) {
  5784. body.append(data, data_length);
  5785. return true;
  5786. });
  5787. res.set_header("x-body-size", std::to_string(body.size()));
  5788. res.status = StatusCode::MultiStatus_207;
  5789. res.set_content(body, "application/xml");
  5790. })
  5791. .Get("/request-target",
  5792. [&](const Request &req, Response & /*res*/) {
  5793. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5794. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5795. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5796. })
  5797. .Get("/long-query-value",
  5798. [&](const Request &req, Response & /*res*/) {
  5799. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5800. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5801. })
  5802. .Get("/too-long-query-value",
  5803. [&](const Request &req, Response & /*res*/) {
  5804. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5805. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5806. })
  5807. .Get("/array-param",
  5808. [&](const Request &req, Response & /*res*/) {
  5809. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5810. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5811. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5812. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5813. })
  5814. .Get("/array-param-values",
  5815. [&](const Request &req, Response & /*res*/) {
  5816. auto values = req.get_param_values("array");
  5817. EXPECT_EQ(3u, values.size());
  5818. EXPECT_EQ("value1", values[0]);
  5819. EXPECT_EQ("value2", values[1]);
  5820. EXPECT_EQ("value3", values[2]);
  5821. auto empty = req.get_param_values("nonexistent");
  5822. EXPECT_TRUE(empty.empty());
  5823. })
  5824. .Post("/validate-no-multiple-headers",
  5825. [&](const Request &req, Response & /*res*/) {
  5826. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5827. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5828. })
  5829. .Post("/content_receiver",
  5830. [&](const Request &req, Response &res,
  5831. const ContentReader &content_reader) {
  5832. if (req.is_multipart_form_data()) {
  5833. std::vector<FormData> items;
  5834. content_reader(
  5835. [&](const FormData &file) {
  5836. items.push_back(file);
  5837. return true;
  5838. },
  5839. [&](const char *data, size_t data_length) {
  5840. items.back().content.append(data, data_length);
  5841. return true;
  5842. });
  5843. EXPECT_EQ(5u, items.size());
  5844. {
  5845. const auto &file = get_file_value(items, "text1");
  5846. EXPECT_TRUE(file.filename.empty());
  5847. EXPECT_EQ("text default", file.content);
  5848. }
  5849. {
  5850. const auto &file = get_file_value(items, "text2");
  5851. EXPECT_TRUE(file.filename.empty());
  5852. EXPECT_EQ("aωb", file.content);
  5853. }
  5854. {
  5855. const auto &file = get_file_value(items, "file1");
  5856. EXPECT_EQ("hello.txt", file.filename);
  5857. EXPECT_EQ("text/plain", file.content_type);
  5858. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5859. }
  5860. {
  5861. const auto &file = get_file_value(items, "file2");
  5862. EXPECT_EQ("world.json", file.filename);
  5863. EXPECT_EQ("application/json", file.content_type);
  5864. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5865. }
  5866. {
  5867. const auto &file = get_file_value(items, "file3");
  5868. EXPECT_TRUE(file.filename.empty());
  5869. EXPECT_EQ("application/octet-stream", file.content_type);
  5870. EXPECT_EQ(0u, file.content.size());
  5871. }
  5872. } else {
  5873. std::string body;
  5874. content_reader([&](const char *data, size_t data_length) {
  5875. EXPECT_EQ(7U, data_length);
  5876. body.append(data, data_length);
  5877. return true;
  5878. });
  5879. EXPECT_EQ(body, "content");
  5880. res.set_content(body, "text/plain");
  5881. }
  5882. })
  5883. .Put("/content_receiver",
  5884. [&](const Request & /*req*/, Response &res,
  5885. const ContentReader &content_reader) {
  5886. std::string body;
  5887. content_reader([&](const char *data, size_t data_length) {
  5888. body.append(data, data_length);
  5889. return true;
  5890. });
  5891. EXPECT_EQ(body, "content");
  5892. res.set_content(body, "text/plain");
  5893. })
  5894. .Patch("/content_receiver",
  5895. [&](const Request & /*req*/, Response &res,
  5896. const ContentReader &content_reader) {
  5897. std::string body;
  5898. content_reader([&](const char *data, size_t data_length) {
  5899. body.append(data, data_length);
  5900. return true;
  5901. });
  5902. EXPECT_EQ(body, "content");
  5903. res.set_content(body, "text/plain");
  5904. })
  5905. .Post("/query-string-and-body",
  5906. [&](const Request &req, Response & /*res*/) {
  5907. ASSERT_TRUE(req.has_param("key"));
  5908. EXPECT_EQ(req.get_param_value("key"), "value");
  5909. EXPECT_EQ(req.body, "content");
  5910. })
  5911. .Get("/last-request",
  5912. [&](const Request &req, Response & /*res*/) {
  5913. EXPECT_EQ("close", req.get_header_value("Connection"));
  5914. })
  5915. .Get(R"(/redirect/(\d+))",
  5916. [&](const Request &req, Response &res) {
  5917. auto num = std::stoi(req.matches[1]) + 1;
  5918. std::string url = "/redirect/" + std::to_string(num);
  5919. res.set_redirect(url);
  5920. })
  5921. .Post("/binary",
  5922. [&](const Request &req, Response &res) {
  5923. EXPECT_EQ(4U, req.body.size());
  5924. EXPECT_EQ("application/octet-stream",
  5925. req.get_header_value("Content-Type"));
  5926. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5927. res.set_content(req.body, "application/octet-stream");
  5928. })
  5929. .Put("/binary",
  5930. [&](const Request &req, Response &res) {
  5931. EXPECT_EQ(4U, req.body.size());
  5932. EXPECT_EQ("application/octet-stream",
  5933. req.get_header_value("Content-Type"));
  5934. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5935. res.set_content(req.body, "application/octet-stream");
  5936. })
  5937. .Patch("/binary",
  5938. [&](const Request &req, Response &res) {
  5939. EXPECT_EQ(4U, req.body.size());
  5940. EXPECT_EQ("application/octet-stream",
  5941. req.get_header_value("Content-Type"));
  5942. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5943. res.set_content(req.body, "application/octet-stream");
  5944. })
  5945. .Delete("/binary",
  5946. [&](const Request &req, Response &res) {
  5947. EXPECT_EQ(4U, req.body.size());
  5948. EXPECT_EQ("application/octet-stream",
  5949. req.get_header_value("Content-Type"));
  5950. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5951. res.set_content(req.body, "application/octet-stream");
  5952. })
  5953. .Get("/issue1772",
  5954. [&](const Request & /*req*/, Response &res) {
  5955. res.status = 401;
  5956. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5957. })
  5958. .Delete("/issue609",
  5959. [](const httplib::Request &, httplib::Response &res,
  5960. const httplib::ContentReader &) {
  5961. res.set_content("ok", "text/plain");
  5962. })
  5963. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5964. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5965. .Get("/compress",
  5966. [&](const Request & /*req*/, Response &res) {
  5967. res.set_content(
  5968. "12345678901234567890123456789012345678901234567890123456789"
  5969. "01234567890123456789012345678901234567890",
  5970. "text/plain");
  5971. })
  5972. .Get("/compress-with-charset",
  5973. [&](const Request & /*req*/, Response &res) {
  5974. res.set_content(
  5975. "12345678901234567890123456789012345678901234567890123456789"
  5976. "01234567890123456789012345678901234567890",
  5977. "application/json; charset=utf-8");
  5978. })
  5979. .Get("/nocompress",
  5980. [&](const Request & /*req*/, Response &res) {
  5981. res.set_content(
  5982. "12345678901234567890123456789012345678901234567890123456789"
  5983. "01234567890123456789012345678901234567890",
  5984. "application/octet-stream");
  5985. })
  5986. .Post("/compress-multipart",
  5987. [&](const Request &req, Response & /*res*/) {
  5988. EXPECT_EQ(2u, req.form.fields.size());
  5989. ASSERT_TRUE(!req.form.has_field("???"));
  5990. {
  5991. const auto &text = req.form.get_field("key1");
  5992. EXPECT_EQ("test", text);
  5993. }
  5994. {
  5995. const auto &text = req.form.get_field("key2");
  5996. EXPECT_EQ("--abcdefg123", text);
  5997. }
  5998. })
  5999. #endif
  6000. ;
  6001. persons_["john"] = "programmer";
  6002. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6003. svr_.wait_until_ready();
  6004. }
  6005. virtual void TearDown() {
  6006. svr_.stop();
  6007. if (!request_threads_.empty()) {
  6008. std::this_thread::sleep_for(std::chrono::seconds(1));
  6009. for (auto &t : request_threads_) {
  6010. t.join();
  6011. }
  6012. }
  6013. t_.join();
  6014. }
  6015. map<string, string> persons_;
  6016. #ifdef CPPHTTPLIB_SSL_ENABLED
  6017. SSLClient cli_;
  6018. SSLServer svr_;
  6019. #else
  6020. Client cli_;
  6021. Server svr_;
  6022. #endif
  6023. thread t_;
  6024. std::vector<thread> request_threads_;
  6025. };
  6026. TEST_F(ServerTest, GetMethod200) {
  6027. auto res = cli_.Get("/hi");
  6028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6029. EXPECT_EQ("HTTP/1.1", res->version);
  6030. EXPECT_EQ(StatusCode::OK_200, res->status);
  6031. EXPECT_EQ("OK", res->reason);
  6032. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6033. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6034. EXPECT_EQ("Hello World!", res->body);
  6035. }
  6036. TEST_F(ServerTest, GetEmptyFile) {
  6037. auto res = cli_.Get("/empty_file");
  6038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6039. EXPECT_EQ(StatusCode::OK_200, res->status);
  6040. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6041. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6042. EXPECT_EQ("", res->body);
  6043. }
  6044. TEST_F(ServerTest, GetFileContent) {
  6045. auto res = cli_.Get("/file_content");
  6046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6047. EXPECT_EQ(StatusCode::OK_200, res->status);
  6048. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6049. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6050. EXPECT_EQ("test.html", res->body);
  6051. }
  6052. TEST_F(ServerTest, GetFileContentWithRange) {
  6053. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6055. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6056. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6057. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6058. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6059. EXPECT_EQ("est", res->body);
  6060. }
  6061. TEST_F(ServerTest, GetFileContentWithContentType) {
  6062. auto res = cli_.Get("/file_content_with_content_type");
  6063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6064. EXPECT_EQ(StatusCode::OK_200, res->status);
  6065. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6066. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6067. EXPECT_EQ("file\n", res->body);
  6068. }
  6069. TEST_F(ServerTest, GetInvalidFileContent) {
  6070. auto res = cli_.Get("/invalid_file_content");
  6071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6072. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6073. }
  6074. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6075. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6077. EXPECT_EQ("HTTP/1.1", res->version);
  6078. EXPECT_EQ(StatusCode::OK_200, res->status);
  6079. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6080. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6081. EXPECT_EQ("Hello World!", res->body);
  6082. }
  6083. TEST_F(ServerTest, GetMethod302) {
  6084. auto res = cli_.Get("/");
  6085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6086. EXPECT_EQ(StatusCode::Found_302, res->status);
  6087. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6088. }
  6089. TEST_F(ServerTest, GetMethod302Redirect) {
  6090. cli_.set_follow_location(true);
  6091. auto res = cli_.Get("/");
  6092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6093. EXPECT_EQ(StatusCode::OK_200, res->status);
  6094. EXPECT_EQ("Hello World!", res->body);
  6095. EXPECT_EQ("/hi", res->location);
  6096. }
  6097. TEST_F(ServerTest, GetMethod404) {
  6098. auto res = cli_.Get("/invalid");
  6099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6100. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6101. }
  6102. TEST_F(ServerTest, HeadMethod200) {
  6103. auto res = cli_.Head("/hi");
  6104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6105. EXPECT_EQ(StatusCode::OK_200, res->status);
  6106. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6107. EXPECT_TRUE(res->body.empty());
  6108. }
  6109. TEST_F(ServerTest, HeadMethod200Static) {
  6110. auto res = cli_.Head("/mount/dir/index.html");
  6111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6112. EXPECT_EQ(StatusCode::OK_200, res->status);
  6113. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6114. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6115. EXPECT_TRUE(res->body.empty());
  6116. }
  6117. TEST_F(ServerTest, HeadMethod404) {
  6118. auto res = cli_.Head("/invalid");
  6119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6120. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6121. EXPECT_TRUE(res->body.empty());
  6122. }
  6123. TEST_F(ServerTest, GetMethodPersonJohn) {
  6124. auto res = cli_.Get("/person/john");
  6125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6126. EXPECT_EQ(StatusCode::OK_200, res->status);
  6127. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6128. EXPECT_EQ("programmer", res->body);
  6129. }
  6130. TEST_F(ServerTest, PostMethod1) {
  6131. auto res = cli_.Get("/person/john1");
  6132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6133. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6134. res = cli_.Post("/person", "name=john1&note=coder",
  6135. "application/x-www-form-urlencoded");
  6136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6137. ASSERT_EQ(StatusCode::OK_200, res->status);
  6138. res = cli_.Get("/person/john1");
  6139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6140. ASSERT_EQ(StatusCode::OK_200, res->status);
  6141. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6142. ASSERT_EQ("coder", res->body);
  6143. }
  6144. TEST_F(ServerTest, PostMethod2) {
  6145. auto res = cli_.Get("/person/john2");
  6146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6147. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6148. Params params;
  6149. params.emplace("name", "john2");
  6150. params.emplace("note", "coder");
  6151. res = cli_.Post("/person", params);
  6152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6153. ASSERT_EQ(StatusCode::OK_200, res->status);
  6154. res = cli_.Get("/person/john2");
  6155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6156. ASSERT_EQ(StatusCode::OK_200, res->status);
  6157. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6158. ASSERT_EQ("coder", res->body);
  6159. }
  6160. TEST_F(ServerTest, PutMethod3) {
  6161. auto res = cli_.Get("/person/john3");
  6162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6163. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6164. Params params;
  6165. params.emplace("name", "john3");
  6166. params.emplace("note", "coder");
  6167. res = cli_.Put("/person", params);
  6168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6169. ASSERT_EQ(StatusCode::OK_200, res->status);
  6170. res = cli_.Get("/person/john3");
  6171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6172. ASSERT_EQ(StatusCode::OK_200, res->status);
  6173. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6174. ASSERT_EQ("coder", res->body);
  6175. }
  6176. TEST_F(ServerTest, DeleteMethod1) {
  6177. auto res = cli_.Get("/person/john4");
  6178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6179. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6180. Params params;
  6181. params.emplace("name", "john4");
  6182. params.emplace("note", "coder");
  6183. res = cli_.Post("/person", params);
  6184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6185. ASSERT_EQ(StatusCode::OK_200, res->status);
  6186. res = cli_.Get("/person/john4");
  6187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6188. ASSERT_EQ(StatusCode::OK_200, res->status);
  6189. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6190. ASSERT_EQ("coder", res->body);
  6191. Params delete_params;
  6192. delete_params.emplace("name", "john4");
  6193. res = cli_.Delete("/person", delete_params);
  6194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6195. ASSERT_EQ(StatusCode::OK_200, res->status);
  6196. ASSERT_EQ("DELETED", res->body);
  6197. res = cli_.Get("/person/john4");
  6198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6199. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6200. }
  6201. TEST_F(ServerTest, DeleteMethod2) {
  6202. auto res = cli_.Get("/person/john5");
  6203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6204. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6205. Params params;
  6206. params.emplace("name", "john5");
  6207. params.emplace("note", "developer");
  6208. res = cli_.Post("/person", params);
  6209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6210. ASSERT_EQ(StatusCode::OK_200, res->status);
  6211. res = cli_.Get("/person/john5");
  6212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6213. ASSERT_EQ(StatusCode::OK_200, res->status);
  6214. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6215. ASSERT_EQ("developer", res->body);
  6216. Params delete_params;
  6217. delete_params.emplace("name", "john5");
  6218. Headers headers;
  6219. headers.emplace("Custom-Header", "test-value");
  6220. res = cli_.Delete("/person", headers, delete_params);
  6221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6222. ASSERT_EQ(StatusCode::OK_200, res->status);
  6223. ASSERT_EQ("DELETED", res->body);
  6224. res = cli_.Get("/person/john5");
  6225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6226. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6227. }
  6228. TEST_F(ServerTest, DeleteMethod3) {
  6229. auto res = cli_.Get("/person/john6");
  6230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6231. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6232. Params params;
  6233. params.emplace("name", "john6");
  6234. params.emplace("note", "tester");
  6235. res = cli_.Post("/person", params);
  6236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6237. ASSERT_EQ(StatusCode::OK_200, res->status);
  6238. res = cli_.Get("/person/john6");
  6239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6240. ASSERT_EQ(StatusCode::OK_200, res->status);
  6241. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6242. ASSERT_EQ("tester", res->body);
  6243. Params delete_params;
  6244. delete_params.emplace("name", "john6");
  6245. Headers headers;
  6246. headers.emplace("Custom-Header", "test-value");
  6247. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6249. ASSERT_EQ(StatusCode::OK_200, res->status);
  6250. ASSERT_EQ("DELETED", res->body);
  6251. res = cli_.Get("/person/john6");
  6252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6253. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6254. }
  6255. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6256. Params params;
  6257. params.emplace("json", JSON_DATA);
  6258. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6260. ASSERT_EQ(StatusCode::OK_200, res->status);
  6261. ASSERT_EQ(JSON_DATA, res->body);
  6262. }
  6263. TEST_F(ServerTest, PostEmptyContent) {
  6264. auto res = cli_.Post("/empty", "", "text/plain");
  6265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6266. ASSERT_EQ(StatusCode::OK_200, res->status);
  6267. ASSERT_EQ("empty", res->body);
  6268. }
  6269. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6270. auto res = cli_.Post("/empty-no-content-type");
  6271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6272. ASSERT_EQ(StatusCode::OK_200, res->status);
  6273. ASSERT_EQ("empty-no-content-type", res->body);
  6274. }
  6275. TEST_F(ServerTest, PostPathOnly) {
  6276. auto res = cli_.Post("/path-only");
  6277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6278. ASSERT_EQ(StatusCode::OK_200, res->status);
  6279. ASSERT_EQ("path-only", res->body);
  6280. }
  6281. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6282. auto res = cli_.Post("/path-headers-only",
  6283. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6285. ASSERT_EQ(StatusCode::OK_200, res->status);
  6286. ASSERT_EQ("path-headers-only", res->body);
  6287. }
  6288. TEST_F(ServerTest, PostLarge) {
  6289. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6291. ASSERT_EQ(StatusCode::OK_200, res->status);
  6292. EXPECT_EQ(LARGE_DATA, res->body);
  6293. }
  6294. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6295. auto res = cli_.Put("/empty-no-content-type");
  6296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6297. ASSERT_EQ(StatusCode::OK_200, res->status);
  6298. ASSERT_EQ("empty-no-content-type", res->body);
  6299. }
  6300. TEST_F(ServerTest, GetMethodDir) {
  6301. auto res = cli_.Get("/dir/");
  6302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6303. EXPECT_EQ(StatusCode::OK_200, res->status);
  6304. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6305. auto body = R"(<html>
  6306. <head>
  6307. </head>
  6308. <body>
  6309. <a href="/dir/test.html">Test</a>
  6310. <a href="/hi">hi</a>
  6311. </body>
  6312. </html>
  6313. )";
  6314. EXPECT_EQ(body, res->body);
  6315. }
  6316. TEST_F(ServerTest, GetMethodDirTest) {
  6317. auto res = cli_.Get("/dir/test.html");
  6318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6319. EXPECT_EQ(StatusCode::OK_200, res->status);
  6320. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6321. EXPECT_EQ("test.html", res->body);
  6322. }
  6323. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6324. auto res = cli_.Get("/dir/../dir/test.html");
  6325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6326. EXPECT_EQ(StatusCode::OK_200, res->status);
  6327. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6328. EXPECT_EQ("test.html", res->body);
  6329. }
  6330. TEST_F(ServerTest, GetMethodInvalidPath) {
  6331. auto res = cli_.Get("/dir/../test.html");
  6332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6333. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6334. }
  6335. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6336. auto res = cli_.Get("/../www/dir/test.html");
  6337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6338. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6339. }
  6340. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6341. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6343. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6344. }
  6345. TEST_F(ServerTest, GetMethodDirMountTest) {
  6346. auto res = cli_.Get("/mount/dir/test.html");
  6347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6348. EXPECT_EQ(StatusCode::OK_200, res->status);
  6349. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6350. EXPECT_EQ("test.html", res->body);
  6351. }
  6352. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6353. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6355. EXPECT_EQ(StatusCode::OK_200, res->status);
  6356. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6357. EXPECT_EQ("test.html", res->body);
  6358. }
  6359. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6360. auto res = cli_.Get("/mount/dir/../test.html");
  6361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6362. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6363. }
  6364. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6365. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6367. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6368. }
  6369. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6370. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6372. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6373. }
  6374. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6375. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6377. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6378. }
  6379. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6380. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6382. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6383. }
  6384. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6385. auto res = cli_.Get("/mount/dir");
  6386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6387. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6388. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6389. }
  6390. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6391. auto res = cli_.Get("//dir");
  6392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6393. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6394. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6395. }
  6396. TEST_F(ServerTest, PostMethod303) {
  6397. auto res = cli_.Post("/1", "body", "text/plain");
  6398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6399. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6400. EXPECT_EQ("/2", res->get_header_value("Location"));
  6401. }
  6402. TEST_F(ServerTest, PostMethod303Redirect) {
  6403. cli_.set_follow_location(true);
  6404. auto res = cli_.Post("/1", "body", "text/plain");
  6405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6406. EXPECT_EQ(StatusCode::OK_200, res->status);
  6407. EXPECT_EQ("redirected.", res->body);
  6408. EXPECT_EQ("/2", res->location);
  6409. }
  6410. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6411. auto res = cli_.Get("/dir/test.abcde");
  6412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6413. EXPECT_EQ(StatusCode::OK_200, res->status);
  6414. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6415. EXPECT_EQ("abcde", res->body);
  6416. }
  6417. TEST_F(ServerTest, StaticFileRange) {
  6418. auto res =
  6419. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6421. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6422. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6423. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6424. EXPECT_EQ(true, res->has_header("Content-Range"));
  6425. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6426. EXPECT_EQ(std::string("cd"), res->body);
  6427. }
  6428. TEST_F(ServerTest, StaticFileRanges) {
  6429. auto res = cli_.Get("/dir/test.abcde",
  6430. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6432. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6433. EXPECT_TRUE(
  6434. res->get_header_value("Content-Type")
  6435. .find(
  6436. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6437. 0);
  6438. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6439. }
  6440. TEST_F(ServerTest, StaticFileRangeHead) {
  6441. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6443. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6444. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6445. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6446. EXPECT_EQ(true, res->has_header("Content-Range"));
  6447. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6448. }
  6449. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6450. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6452. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6453. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6454. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6455. EXPECT_EQ(true, res->has_header("Content-Range"));
  6456. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6457. res->get_header_value("Content-Range"));
  6458. EXPECT_EQ("LAST\n", res->body);
  6459. }
  6460. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6461. auto res =
  6462. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6464. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6465. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6466. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6467. EXPECT_EQ(true, res->has_header("Content-Range"));
  6468. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6469. }
  6470. TEST_F(ServerTest, StaticFileBigFile) {
  6471. auto res = cli_.Get("/dir/1MB.txt");
  6472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6473. EXPECT_EQ(StatusCode::OK_200, res->status);
  6474. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6475. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6476. }
  6477. TEST_F(ServerTest, InvalidBaseDirMount) {
  6478. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6479. }
  6480. TEST_F(ServerTest, Binary) {
  6481. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6482. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6483. "application/octet-stream");
  6484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6485. ASSERT_EQ(StatusCode::OK_200, res->status);
  6486. ASSERT_EQ(4U, res->body.size());
  6487. res = cli_.Put("/binary", binary.data(), binary.size(),
  6488. "application/octet-stream");
  6489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6490. ASSERT_EQ(StatusCode::OK_200, res->status);
  6491. ASSERT_EQ(4U, res->body.size());
  6492. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6493. "application/octet-stream");
  6494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6495. ASSERT_EQ(StatusCode::OK_200, res->status);
  6496. ASSERT_EQ(4U, res->body.size());
  6497. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6498. "application/octet-stream");
  6499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6500. ASSERT_EQ(StatusCode::OK_200, res->status);
  6501. ASSERT_EQ(4U, res->body.size());
  6502. }
  6503. TEST_F(ServerTest, BinaryString) {
  6504. auto binary = std::string("\x00\x01\x02\x03", 4);
  6505. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6507. ASSERT_EQ(StatusCode::OK_200, res->status);
  6508. ASSERT_EQ(4U, res->body.size());
  6509. res = cli_.Put("/binary", binary, "application/octet-stream");
  6510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6511. ASSERT_EQ(StatusCode::OK_200, res->status);
  6512. ASSERT_EQ(4U, res->body.size());
  6513. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6515. ASSERT_EQ(StatusCode::OK_200, res->status);
  6516. ASSERT_EQ(4U, res->body.size());
  6517. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6519. ASSERT_EQ(StatusCode::OK_200, res->status);
  6520. ASSERT_EQ(4U, res->body.size());
  6521. }
  6522. TEST_F(ServerTest, EmptyRequest) {
  6523. auto res = cli_.Get("");
  6524. ASSERT_TRUE(!res);
  6525. EXPECT_EQ(Error::Connection, res.error());
  6526. }
  6527. TEST_F(ServerTest, LongRequest) {
  6528. std::string request;
  6529. for (size_t i = 0; i < 545; i++) {
  6530. request += "/TooLongRequest";
  6531. }
  6532. request += "OK";
  6533. auto res = cli_.Get(request.c_str());
  6534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6535. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6536. }
  6537. TEST_F(ServerTest, TooLongRequest) {
  6538. std::string request;
  6539. for (size_t i = 0; i < 546; i++) {
  6540. request += "/TooLongRequest";
  6541. }
  6542. request += "_NG";
  6543. auto start = std::chrono::high_resolution_clock::now();
  6544. cli_.set_keep_alive(true);
  6545. auto res = cli_.Get(request.c_str());
  6546. auto end = std::chrono::high_resolution_clock::now();
  6547. auto elapsed =
  6548. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6549. .count();
  6550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6551. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6552. EXPECT_LE(elapsed, 1000);
  6553. EXPECT_EQ("close", res->get_header_value("Connection"));
  6554. EXPECT_FALSE(cli_.is_socket_open());
  6555. }
  6556. TEST_F(ServerTest, AlmostTooLongRequest) {
  6557. // test for #2046 - URI length check shouldn't include other content on req
  6558. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6559. // leading /, space, HTTP/1.1)
  6560. std::string request =
  6561. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6562. auto res = cli_.Get(request.c_str());
  6563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6564. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6565. }
  6566. TEST_F(ServerTest, LongHeader) {
  6567. Request req;
  6568. req.method = "GET";
  6569. req.path = "/hi";
  6570. std::string host_and_port;
  6571. host_and_port += HOST;
  6572. host_and_port += ":";
  6573. host_and_port += std::to_string(PORT);
  6574. req.headers.emplace("Host", host_and_port.c_str());
  6575. req.headers.emplace("Accept", "*/*");
  6576. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6577. req.headers.emplace(
  6578. "Header-Name",
  6579. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6580. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6581. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6582. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6583. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6584. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6585. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6586. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6587. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6588. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6589. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6590. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6591. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6592. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6593. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6594. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6595. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6596. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6597. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6598. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6599. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6600. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6601. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6602. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6603. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6604. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6605. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6606. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6607. "@@@@@@@@@@@@@@@@");
  6608. auto res = std::make_shared<Response>();
  6609. auto error = Error::Success;
  6610. auto ret = cli_.send(req, *res, error);
  6611. ASSERT_TRUE(ret);
  6612. EXPECT_EQ(StatusCode::OK_200, res->status);
  6613. }
  6614. TEST_F(ServerTest, LongQueryValue) {
  6615. auto start = std::chrono::high_resolution_clock::now();
  6616. cli_.set_keep_alive(true);
  6617. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6618. auto end = std::chrono::high_resolution_clock::now();
  6619. auto elapsed =
  6620. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6621. .count();
  6622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6623. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6624. EXPECT_LE(elapsed, 1000);
  6625. EXPECT_EQ("close", res->get_header_value("Connection"));
  6626. EXPECT_FALSE(cli_.is_socket_open());
  6627. }
  6628. TEST_F(ServerTest, TooLongQueryValue) {
  6629. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6630. ASSERT_FALSE(res);
  6631. EXPECT_EQ(Error::Read, res.error());
  6632. }
  6633. TEST_F(ServerTest, TooLongHeader) {
  6634. Request req;
  6635. req.method = "GET";
  6636. req.path = "/hi";
  6637. std::string host_and_port;
  6638. host_and_port += HOST;
  6639. host_and_port += ":";
  6640. host_and_port += std::to_string(PORT);
  6641. req.headers.emplace("Host", host_and_port.c_str());
  6642. req.headers.emplace("Accept", "*/*");
  6643. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6644. req.headers.emplace(
  6645. "Header-Name",
  6646. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6647. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6648. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6649. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6650. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6651. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6652. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6653. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6654. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6655. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6656. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6657. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6658. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6659. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6660. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6661. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6662. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6663. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6664. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6665. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6666. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6667. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6668. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6669. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6670. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6671. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6672. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6673. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6674. "@@@@@@@@@@@@@@@@@");
  6675. auto res = std::make_shared<Response>();
  6676. auto error = Error::Success;
  6677. auto ret = cli_.send(req, *res, error);
  6678. ASSERT_TRUE(ret);
  6679. EXPECT_EQ(StatusCode::OK_200, res->status);
  6680. }
  6681. TEST_F(ServerTest, HeaderCountAtLimit) {
  6682. // Test with headers just under the 100 limit
  6683. httplib::Headers headers;
  6684. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6685. // This should keep us just under the 100 header limit
  6686. for (int i = 0; i < 95; i++) {
  6687. std::string name = "X-Test-Header-" + std::to_string(i);
  6688. std::string value = "value" + std::to_string(i);
  6689. headers.emplace(name, value);
  6690. }
  6691. // This should work fine as we're under the limit
  6692. auto res = cli_.Get("/hi", headers);
  6693. EXPECT_TRUE(res);
  6694. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6695. }
  6696. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6697. // Test with many headers to exceed the 100 limit
  6698. httplib::Headers headers;
  6699. // Add 150 headers to definitely exceed the 100 limit
  6700. for (int i = 0; i < 150; i++) {
  6701. std::string name = "X-Test-Header-" + std::to_string(i);
  6702. std::string value = "value" + std::to_string(i);
  6703. headers.emplace(name, value);
  6704. }
  6705. // This should fail due to exceeding header count limit
  6706. cli_.set_keep_alive(true);
  6707. auto res = cli_.Get("/hi", headers);
  6708. // The server should respond with 400 Bad Request
  6709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6710. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6711. EXPECT_EQ("close", res->get_header_value("Connection"));
  6712. EXPECT_FALSE(cli_.is_socket_open());
  6713. }
  6714. TEST_F(ServerTest, PercentEncoding) {
  6715. auto res = cli_.Get("/e%6edwith%");
  6716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6717. EXPECT_EQ(StatusCode::OK_200, res->status);
  6718. }
  6719. TEST_F(ServerTest, PercentEncodingUnicode) {
  6720. auto res = cli_.Get("/e%u006edwith%");
  6721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6722. EXPECT_EQ(StatusCode::OK_200, res->status);
  6723. }
  6724. TEST_F(ServerTest, InvalidPercentEncoding) {
  6725. auto res = cli_.Get("/%endwith%");
  6726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6727. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6728. }
  6729. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6730. auto res = cli_.Get("/%uendwith%");
  6731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6732. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6733. }
  6734. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6735. auto res = cli_.Get("/hello?aaa=bbb%");
  6736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6737. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6738. }
  6739. TEST_F(ServerTest, PlusSignEncoding) {
  6740. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6742. EXPECT_EQ(StatusCode::OK_200, res->status);
  6743. EXPECT_EQ("a +b", res->body);
  6744. }
  6745. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6746. // This test simulates a potential DoS attack using many headers
  6747. // to verify our security fix prevents memory exhaustion
  6748. httplib::Headers attack_headers;
  6749. // Attempt to add many headers like an attacker would (200 headers to far
  6750. // exceed limit)
  6751. for (int i = 0; i < 200; i++) {
  6752. std::string name = "X-Attack-Header-" + std::to_string(i);
  6753. std::string value = "attack_payload_" + std::to_string(i);
  6754. attack_headers.emplace(name, value);
  6755. }
  6756. // Try to POST with excessive headers
  6757. cli_.set_keep_alive(true);
  6758. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6759. // Should either fail or return 400 Bad Request due to security limit
  6760. if (res) {
  6761. // If we get a response, it should be 400 Bad Request
  6762. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6763. EXPECT_EQ("close", res->get_header_value("Connection"));
  6764. }
  6765. EXPECT_FALSE(cli_.is_socket_open());
  6766. }
  6767. TEST_F(ServerTest, MultipartFormData) {
  6768. UploadFormDataItems items = {
  6769. {"text1", "text default", "", ""},
  6770. {"text2", "aωb", "", ""},
  6771. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6772. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6773. {"file3", "", "", "application/octet-stream"},
  6774. {"file4", "", "", " application/json tmp-string "}};
  6775. auto res = cli_.Post("/multipart", items);
  6776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6777. EXPECT_EQ(StatusCode::OK_200, res->status);
  6778. }
  6779. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6780. UploadFormDataItems items = {
  6781. {"text", "default text", "", ""},
  6782. {"multi_text1", "aaaaa", "", ""},
  6783. {"multi_text1", "bbbbb", "", ""},
  6784. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6785. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6786. "application/json"},
  6787. };
  6788. auto res = cli_.Post("/multipart/multi_file_values", items);
  6789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6790. EXPECT_EQ(StatusCode::OK_200, res->status);
  6791. }
  6792. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6793. auto res = cli_.Get("/hi");
  6794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6795. EXPECT_EQ(StatusCode::OK_200, res->status);
  6796. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6797. EXPECT_EQ("Hello World!", res->body);
  6798. }
  6799. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6800. Request req;
  6801. req.method = "POST";
  6802. req.path = "/chunked";
  6803. std::string host_and_port;
  6804. host_and_port += HOST;
  6805. host_and_port += ":";
  6806. host_and_port += std::to_string(PORT);
  6807. req.headers.emplace("Host", host_and_port.c_str());
  6808. req.headers.emplace("Accept", "*/*");
  6809. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6810. req.headers.emplace("Content-Type", "text/plain");
  6811. req.headers.emplace("Content-Length", "0");
  6812. req.headers.emplace(
  6813. "Transfer-Encoding",
  6814. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6815. // Client does not chunk, so make a chunked body manually.
  6816. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6817. auto res = std::make_shared<Response>();
  6818. auto error = Error::Success;
  6819. auto ret = cli_.send(req, *res, error);
  6820. ASSERT_TRUE(ret);
  6821. EXPECT_EQ(StatusCode::OK_200, res->status);
  6822. }
  6823. template <typename ClientT>
  6824. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6825. int expected_status) {
  6826. Request req;
  6827. req.method = "POST";
  6828. req.path = "/chunked";
  6829. std::string host_and_port;
  6830. host_and_port += HOST;
  6831. host_and_port += ":";
  6832. host_and_port += std::to_string(PORT);
  6833. req.headers.emplace("Host", host_and_port.c_str());
  6834. req.headers.emplace("Content-Length", "0");
  6835. req.headers.emplace("Transfer-Encoding", "chunked");
  6836. req.body = body;
  6837. auto res = std::make_shared<Response>();
  6838. auto error = Error::Success;
  6839. ASSERT_TRUE(cli.send(req, *res, error));
  6840. EXPECT_EQ(expected_status, res->status);
  6841. }
  6842. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6843. // rather than treat them as valid lengths.
  6844. template <typename ClientT>
  6845. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6846. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6847. }
  6848. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6849. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6850. }
  6851. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6852. expect_chunked_body_rejected(
  6853. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6854. }
  6855. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6856. // chunk-size line carries no CR, LF or other control character ahead of its
  6857. // terminator. Such a line must be refused rather than read as extension text.
  6858. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6859. expect_chunked_body_rejected(
  6860. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6861. }
  6862. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6863. expect_chunked_body_rejected(
  6864. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6865. }
  6866. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6867. expect_chunked_body_rejected(
  6868. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6869. }
  6870. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6871. // The literal stays split: a hex escape consumes every hex digit that
  6872. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6873. expect_chunked_body_rejected(
  6874. cli_, "4;a\x01"
  6875. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6876. }
  6877. TEST_F(ServerTest, AcceptsChunkExtension) {
  6878. expect_chunked_body_status(cli_,
  6879. "4;name=value\r\ndech\r\n"
  6880. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6881. "0;last\r\n\r\n",
  6882. StatusCode::OK_200);
  6883. }
  6884. TEST_F(ServerTest, GetStreamed2) {
  6885. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6887. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6888. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6889. EXPECT_EQ(true, res->has_header("Content-Range"));
  6890. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6891. EXPECT_EQ(std::string("ab"), res->body);
  6892. }
  6893. TEST_F(ServerTest, GetStreamed) {
  6894. auto res = cli_.Get("/streamed");
  6895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6896. EXPECT_EQ(StatusCode::OK_200, res->status);
  6897. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6898. EXPECT_EQ(std::string("aaabbb"), res->body);
  6899. }
  6900. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6901. auto res = cli_.Get("/streamed-without-length",
  6902. Headers{make_range_header({{0, -1}})});
  6903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6904. EXPECT_EQ(StatusCode::OK_200, res->status);
  6905. EXPECT_EQ(false, res->has_header("Content-Length"));
  6906. EXPECT_EQ(false, res->has_header("Content-Range"));
  6907. EXPECT_EQ(std::string("abcdefg"), res->body);
  6908. }
  6909. TEST_F(ServerTest, GetStreamedWithRange1) {
  6910. auto res =
  6911. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6913. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6914. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6915. EXPECT_EQ(true, res->has_header("Content-Range"));
  6916. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6917. EXPECT_EQ(std::string("def"), res->body);
  6918. }
  6919. TEST_F(ServerTest, GetStreamedWithRange2) {
  6920. auto res =
  6921. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6923. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6924. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6925. EXPECT_EQ(true, res->has_header("Content-Range"));
  6926. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6927. EXPECT_EQ(std::string("bcdefg"), res->body);
  6928. }
  6929. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6930. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6932. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6933. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6934. EXPECT_EQ(true, res->has_header("Content-Range"));
  6935. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6936. EXPECT_EQ(std::string("efg"), res->body);
  6937. }
  6938. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6939. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6940. // the entire representation.
  6941. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6942. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6944. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6945. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6946. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6947. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6948. }
  6949. }
  6950. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6951. auto res =
  6952. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6954. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6955. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6956. EXPECT_EQ(false, res->has_header("Content-Range"));
  6957. EXPECT_EQ(0U, res->body.size());
  6958. }
  6959. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6960. // Only a 206 is served as a partial representation. Under any other status
  6961. // `apply_ranges()` reported the full content length, so the body must match
  6962. // that header, and the content provider must never be asked for an offset
  6963. // outside the representation.
  6964. auto check = [&](int status, const char *range) {
  6965. auto path =
  6966. std::string("/streamed-with-range?status=") + std::to_string(status);
  6967. auto ctx = path + " Range: " + range;
  6968. auto res = cli_.Get(path, Headers{{"Range", range}});
  6969. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6970. EXPECT_EQ(status, res->status) << ctx;
  6971. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6972. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6973. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6974. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6975. };
  6976. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6977. check(403, "bytes=3-5");
  6978. // The offset is far past the representation.
  6979. check(403, "bytes=100000-100200");
  6980. // `first_pos` is still -1 here, and the bounds asserts in
  6981. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6982. check(403, "bytes=-3");
  6983. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6984. // multipart branch would have written one that is empty.
  6985. check(403, "bytes=1-2, 4-5");
  6986. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6987. // covers the whole representation.
  6988. check(200, "bytes=3-5");
  6989. check(200, "bytes=1-2, 4-5");
  6990. }
  6991. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6992. auto res =
  6993. cli_.Get("/streamed-with-range",
  6994. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6995. "92233720368547758079223372036854775807"}});
  6996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6997. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6998. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6999. EXPECT_EQ(false, res->has_header("Content-Range"));
  7000. EXPECT_EQ(0U, res->body.size());
  7001. }
  7002. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7003. auto res = cli_.Get(
  7004. "/with-range",
  7005. Headers{{"Range",
  7006. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7007. {"Accept-Encoding", ""}});
  7008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7009. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7010. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7011. EXPECT_EQ(true, res->has_header("Content-Range"));
  7012. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7013. EXPECT_EQ(std::string("abcdefg"), res->body);
  7014. }
  7015. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7016. auto res = cli_.Get("/with-range", Headers{
  7017. {"Range", "bytes=0-"},
  7018. {"Accept-Encoding", ""},
  7019. });
  7020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7021. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7022. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7023. EXPECT_EQ(true, res->has_header("Content-Range"));
  7024. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7025. EXPECT_EQ(std::string("abcdefg"), res->body);
  7026. }
  7027. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7028. auto res = cli_.Get("/streamed-with-range",
  7029. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7031. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7032. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7033. EXPECT_EQ(false, res->has_header("Content-Range"));
  7034. EXPECT_EQ(267U, res->body.size());
  7035. // Check that both range contents are present
  7036. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7037. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7038. // Check that Content-Range headers are present for both ranges
  7039. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7040. std::string::npos);
  7041. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7042. std::string::npos);
  7043. }
  7044. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7045. Ranges ranges;
  7046. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7047. ranges.emplace_back(0, -1);
  7048. }
  7049. auto res = cli_.Get("/streamed-with-range?error",
  7050. Headers{{make_range_header(ranges)}});
  7051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7052. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7053. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7054. EXPECT_EQ(false, res->has_header("Content-Range"));
  7055. EXPECT_EQ(0U, res->body.size());
  7056. }
  7057. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7058. auto res = cli_.Get("/streamed-with-range",
  7059. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7061. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7062. EXPECT_EQ(5U, res->body.size());
  7063. // Check that overlapping ranges are coalesced into a single range
  7064. EXPECT_EQ("bcdef", res->body);
  7065. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7066. // Should be single range, not multipart
  7067. EXPECT_TRUE(res->has_header("Content-Range"));
  7068. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7069. }
  7070. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7071. auto res = cli_.Get("/streamed-with-range",
  7072. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7074. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7075. EXPECT_EQ(268U, res->body.size());
  7076. // Check that both range contents are present
  7077. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7078. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7079. // Check that Content-Range headers are present for both ranges
  7080. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7081. std::string::npos);
  7082. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7083. std::string::npos);
  7084. }
  7085. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7086. auto res = cli_.Get("/streamed-with-range",
  7087. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7089. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7090. EXPECT_EQ(269U, res->body.size());
  7091. // Check that both duplicate range contents are present
  7092. size_t first_abc = res->body.find("abc\r\n");
  7093. EXPECT_TRUE(first_abc != std::string::npos);
  7094. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7095. EXPECT_TRUE(second_abc != std::string::npos);
  7096. // Check that Content-Range headers are present for both ranges
  7097. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7098. EXPECT_TRUE(first_range != std::string::npos);
  7099. size_t second_range =
  7100. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7101. EXPECT_TRUE(second_range != std::string::npos);
  7102. }
  7103. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7104. auto res =
  7105. cli_.Get("/streamed-with-range?error",
  7106. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7108. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7109. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7110. EXPECT_EQ(false, res->has_header("Content-Range"));
  7111. EXPECT_EQ(0U, res->body.size());
  7112. }
  7113. TEST_F(ServerTest, GetStreamedEndless) {
  7114. uint64_t offset = 0;
  7115. auto res = cli_.Get("/streamed-cancel",
  7116. [&](const char * /*data*/, uint64_t data_length) {
  7117. if (offset < 100) {
  7118. offset += data_length;
  7119. return true;
  7120. }
  7121. return false;
  7122. });
  7123. ASSERT_TRUE(!res);
  7124. EXPECT_EQ(Error::Canceled, res.error());
  7125. }
  7126. TEST_F(ServerTest, ClientStop) {
  7127. std::atomic_size_t count{4};
  7128. std::vector<std::thread> threads;
  7129. for (auto i = count.load(); i != 0; --i) {
  7130. threads.emplace_back([&]() {
  7131. auto res = cli_.Get("/streamed-cancel",
  7132. [&](const char *, uint64_t) { return true; });
  7133. --count;
  7134. ASSERT_TRUE(!res);
  7135. EXPECT_TRUE(res.error() == Error::Canceled ||
  7136. res.error() == Error::Read || res.error() == Error::Write);
  7137. });
  7138. }
  7139. std::this_thread::sleep_for(std::chrono::seconds(2));
  7140. while (count != 0) {
  7141. cli_.stop();
  7142. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7143. }
  7144. for (auto &t : threads) {
  7145. t.join();
  7146. }
  7147. }
  7148. TEST_F(ServerTest, GetWithRange1) {
  7149. auto res = cli_.Get("/with-range", Headers{
  7150. make_range_header({{3, 5}}),
  7151. {"Accept-Encoding", ""},
  7152. });
  7153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7154. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7155. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7156. EXPECT_EQ(true, res->has_header("Content-Range"));
  7157. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7158. EXPECT_EQ(std::string("def"), res->body);
  7159. }
  7160. TEST_F(ServerTest, GetWithRange2) {
  7161. auto res = cli_.Get("/with-range", Headers{
  7162. make_range_header({{1, -1}}),
  7163. {"Accept-Encoding", ""},
  7164. });
  7165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7166. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7167. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7168. EXPECT_EQ(true, res->has_header("Content-Range"));
  7169. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7170. EXPECT_EQ(std::string("bcdefg"), res->body);
  7171. }
  7172. TEST_F(ServerTest, GetWithRange3) {
  7173. auto res = cli_.Get("/with-range", Headers{
  7174. make_range_header({{0, 0}}),
  7175. {"Accept-Encoding", ""},
  7176. });
  7177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7178. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7179. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7180. EXPECT_EQ(true, res->has_header("Content-Range"));
  7181. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7182. EXPECT_EQ(std::string("a"), res->body);
  7183. }
  7184. TEST_F(ServerTest, GetWithRange4) {
  7185. auto res = cli_.Get("/with-range", Headers{
  7186. make_range_header({{-1, 2}}),
  7187. {"Accept-Encoding", ""},
  7188. });
  7189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7190. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7191. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7192. EXPECT_EQ(true, res->has_header("Content-Range"));
  7193. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7194. EXPECT_EQ(std::string("fg"), res->body);
  7195. }
  7196. TEST_F(ServerTest, GetWithRange5) {
  7197. auto res = cli_.Get("/with-range", Headers{
  7198. make_range_header({{0, 5}}),
  7199. {"Accept-Encoding", ""},
  7200. });
  7201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7202. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7203. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7204. EXPECT_EQ(true, res->has_header("Content-Range"));
  7205. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7206. EXPECT_EQ(std::string("abcdef"), res->body);
  7207. }
  7208. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7209. auto res =
  7210. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7212. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7213. }
  7214. TEST_F(ServerTest, GetWithRangeMultipart) {
  7215. auto res =
  7216. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7218. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7219. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7220. EXPECT_EQ(false, res->has_header("Content-Range"));
  7221. EXPECT_EQ(267U, res->body.size());
  7222. }
  7223. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7224. auto res = cli_.Get("/with-range",
  7225. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7227. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7228. }
  7229. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7230. auto res = cli_.Get("/with-range-customized-response",
  7231. Headers{{make_range_header({{1, 2}})}});
  7232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7233. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7234. EXPECT_EQ(true, res->has_header("Content-Length"));
  7235. EXPECT_EQ(false, res->has_header("Content-Range"));
  7236. EXPECT_EQ(JSON_DATA, res->body);
  7237. }
  7238. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7239. auto res = cli_.Get("/with-range-customized-response",
  7240. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7242. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7243. EXPECT_EQ(true, res->has_header("Content-Length"));
  7244. EXPECT_EQ(false, res->has_header("Content-Range"));
  7245. EXPECT_EQ(JSON_DATA, res->body);
  7246. }
  7247. TEST_F(ServerTest, Issue1772) {
  7248. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7250. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7251. }
  7252. TEST_F(ServerTest, Issue609) {
  7253. auto res = cli_.Delete("/issue609");
  7254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7255. EXPECT_EQ(StatusCode::OK_200, res->status);
  7256. EXPECT_EQ(std::string("ok"), res->body);
  7257. }
  7258. TEST_F(ServerTest, GetStreamedChunked) {
  7259. auto res = cli_.Get("/streamed-chunked");
  7260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7261. EXPECT_EQ(StatusCode::OK_200, res->status);
  7262. EXPECT_EQ(std::string("123456789"), res->body);
  7263. }
  7264. TEST_F(ServerTest, GetStreamedChunked2) {
  7265. auto res = cli_.Get("/streamed-chunked2");
  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, GetStreamedChunkedWithTrailer) {
  7271. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7273. EXPECT_EQ(StatusCode::OK_200, res->status);
  7274. EXPECT_EQ(std::string("123456789"), res->body);
  7275. EXPECT_TRUE(res->has_header("Trailer"));
  7276. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7277. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7278. // Trailers are now stored separately from headers (security fix)
  7279. EXPECT_EQ(2U, res->trailers.size());
  7280. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7281. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7282. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7283. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7284. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7285. // Verify trailers are NOT in headers (security verification)
  7286. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7287. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7288. }
  7289. TEST_F(ServerTest, LargeChunkedPost) {
  7290. Request req;
  7291. req.method = "POST";
  7292. req.path = "/large-chunked";
  7293. std::string host_and_port;
  7294. host_and_port += HOST;
  7295. host_and_port += ":";
  7296. host_and_port += std::to_string(PORT);
  7297. req.headers.emplace("Host", host_and_port.c_str());
  7298. req.headers.emplace("Accept", "*/*");
  7299. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7300. req.headers.emplace("Content-Type", "text/plain");
  7301. req.headers.emplace("Content-Length", "0");
  7302. req.headers.emplace("Transfer-Encoding", "chunked");
  7303. std::string long_string(30 * 1024u, 'a');
  7304. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7305. // Attempt to make a large enough post to exceed OS buffers, to test that
  7306. // the server handles short reads if the full chunk data isn't available.
  7307. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7308. auto res = std::make_shared<Response>();
  7309. auto error = Error::Success;
  7310. auto ret = cli_.send(req, *res, error);
  7311. ASSERT_TRUE(ret);
  7312. EXPECT_EQ(StatusCode::OK_200, res->status);
  7313. }
  7314. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7315. auto res = cli_.Get("/remote_addr");
  7316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7317. EXPECT_EQ(StatusCode::OK_200, res->status);
  7318. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7319. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7320. }
  7321. TEST_F(ServerTest, GetMethodLocalAddr) {
  7322. auto res = cli_.Get("/local_addr");
  7323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7324. EXPECT_EQ(StatusCode::OK_200, res->status);
  7325. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7326. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7327. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7328. }
  7329. TEST_F(ServerTest, HTTPResponseSplitting) {
  7330. auto res = cli_.Get("/http_response_splitting");
  7331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7332. EXPECT_EQ(StatusCode::OK_200, res->status);
  7333. }
  7334. TEST_F(ServerTest, SlowRequest) {
  7335. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7336. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7337. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7338. }
  7339. #if 0
  7340. TEST_F(ServerTest, SlowPost) {
  7341. char buffer[64 * 1024];
  7342. memset(buffer, 0x42, sizeof(buffer));
  7343. auto res = cli_.Post(
  7344. "/slowpost", 64 * 1024 * 1024,
  7345. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7346. auto ret = sink.write(buffer, sizeof(buffer));
  7347. EXPECT_TRUE(ret);
  7348. return true;
  7349. },
  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, SlowPostFail) {
  7355. char buffer[64 * 1024];
  7356. memset(buffer, 0x42, sizeof(buffer));
  7357. cli_.set_write_timeout(std::chrono::seconds(0));
  7358. auto res = cli_.Post(
  7359. "/slowpost", 64 * 1024 * 1024,
  7360. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7361. sink.write(buffer, sizeof(buffer));
  7362. return true;
  7363. },
  7364. "text/plain");
  7365. ASSERT_TRUE(!res);
  7366. EXPECT_EQ(Error::Write, res.error());
  7367. }
  7368. #endif
  7369. TEST_F(ServerTest, Put) {
  7370. auto res = cli_.Put("/put", "PUT", "text/plain");
  7371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7372. EXPECT_EQ(StatusCode::OK_200, res->status);
  7373. EXPECT_EQ("PUT", res->body);
  7374. }
  7375. TEST_F(ServerTest, PutWithContentProvider) {
  7376. auto res = cli_.Put(
  7377. "/put", 3,
  7378. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7379. sink.os << "PUT";
  7380. return true;
  7381. },
  7382. "text/plain");
  7383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7384. EXPECT_EQ(StatusCode::OK_200, res->status);
  7385. EXPECT_EQ("PUT", res->body);
  7386. }
  7387. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7388. auto res = cli_.Post(
  7389. "/post", 42,
  7390. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7391. return false;
  7392. },
  7393. "text/plain");
  7394. ASSERT_TRUE(!res);
  7395. EXPECT_EQ(Error::Canceled, res.error());
  7396. }
  7397. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7398. auto res = cli_.Put(
  7399. "/put",
  7400. [](size_t /*offset*/, DataSink &sink) {
  7401. sink.os << "PUT";
  7402. sink.done();
  7403. return true;
  7404. },
  7405. "text/plain");
  7406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7407. EXPECT_EQ(StatusCode::OK_200, res->status);
  7408. EXPECT_EQ("PUT", res->body);
  7409. }
  7410. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7411. auto res = cli_.Post(
  7412. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7413. "text/plain");
  7414. ASSERT_TRUE(!res);
  7415. EXPECT_EQ(Error::Canceled, res.error());
  7416. }
  7417. TEST_F(ServerTest, PostLoopBack) {
  7418. std::string body;
  7419. auto res = cli_.Post(
  7420. "/post-loopback", 9,
  7421. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7422. EXPECT_EQ(9u, length);
  7423. sink.write("123", 3);
  7424. sink.write("456", 3);
  7425. sink.write("789", 3);
  7426. return true;
  7427. },
  7428. "text/plain",
  7429. [&body](const char *data, size_t data_length) {
  7430. body.append(data, data_length);
  7431. return true;
  7432. });
  7433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7434. EXPECT_EQ(StatusCode::OK_200, res->status);
  7435. EXPECT_EQ("123456789", body);
  7436. }
  7437. TEST_F(ServerTest, PutLoopBack) {
  7438. std::string body;
  7439. auto res = cli_.Put(
  7440. "/put-loopback", 9,
  7441. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7442. EXPECT_EQ(9u, length);
  7443. sink.write("123", 3);
  7444. sink.write("456", 3);
  7445. sink.write("789", 3);
  7446. return true;
  7447. },
  7448. "text/plain",
  7449. [&body](const char *data, size_t data_length) {
  7450. body.append(data, data_length);
  7451. return true;
  7452. });
  7453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7454. EXPECT_EQ(StatusCode::OK_200, res->status);
  7455. EXPECT_EQ("123456789", body);
  7456. }
  7457. TEST_F(ServerTest, PatchLoopBack) {
  7458. std::string body;
  7459. auto res = cli_.Patch(
  7460. "/patch-loopback", 9,
  7461. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7462. EXPECT_EQ(9u, length);
  7463. sink.write("123", 3);
  7464. sink.write("456", 3);
  7465. sink.write("789", 3);
  7466. return true;
  7467. },
  7468. "text/plain",
  7469. [&body](const char *data, size_t data_length) {
  7470. body.append(data, data_length);
  7471. return true;
  7472. });
  7473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7474. EXPECT_EQ(StatusCode::OK_200, res->status);
  7475. EXPECT_EQ("123456789", body);
  7476. }
  7477. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7478. std::string body;
  7479. auto res = cli_.Post(
  7480. "/post-loopback",
  7481. [](size_t /*offset*/, DataSink &sink) {
  7482. sink.write("123", 3);
  7483. sink.write("456", 3);
  7484. sink.write("789", 3);
  7485. sink.done();
  7486. return true;
  7487. },
  7488. "text/plain",
  7489. [&body](const char *data, size_t data_length) {
  7490. body.append(data, data_length);
  7491. return true;
  7492. });
  7493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7494. EXPECT_EQ(StatusCode::OK_200, res->status);
  7495. EXPECT_EQ("123456789", body);
  7496. }
  7497. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7498. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7499. cli_.set_compress(true);
  7500. auto res = cli_.Put(
  7501. "/put", 3,
  7502. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7503. sink.os << "PUT";
  7504. return true;
  7505. },
  7506. "text/plain");
  7507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7508. EXPECT_EQ(StatusCode::OK_200, res->status);
  7509. EXPECT_EQ("PUT", res->body);
  7510. }
  7511. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7512. cli_.set_compress(true);
  7513. auto res = cli_.Post(
  7514. "/post", 42,
  7515. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7516. return false;
  7517. },
  7518. "text/plain");
  7519. ASSERT_TRUE(!res);
  7520. EXPECT_EQ(Error::Canceled, res.error());
  7521. }
  7522. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7523. cli_.set_compress(true);
  7524. auto res = cli_.Put(
  7525. "/put",
  7526. [](size_t /*offset*/, DataSink &sink) {
  7527. sink.os << "PUT";
  7528. sink.done();
  7529. return true;
  7530. },
  7531. "text/plain");
  7532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7533. EXPECT_EQ(StatusCode::OK_200, res->status);
  7534. EXPECT_EQ("PUT", res->body);
  7535. }
  7536. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7537. cli_.set_compress(true);
  7538. auto res = cli_.Post(
  7539. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7540. "text/plain");
  7541. ASSERT_TRUE(!res);
  7542. EXPECT_EQ(Error::Canceled, res.error());
  7543. }
  7544. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7545. cli_.set_compress(true);
  7546. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7548. EXPECT_EQ(StatusCode::OK_200, res->status);
  7549. EXPECT_EQ(LARGE_DATA, res->body);
  7550. }
  7551. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7552. #ifdef CPPHTTPLIB_SSL_ENABLED
  7553. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7554. Client cli(s.c_str());
  7555. cli.enable_server_certificate_verification(false);
  7556. #else
  7557. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7558. Client cli(s.c_str());
  7559. #endif
  7560. cli.set_compress(true);
  7561. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7563. EXPECT_EQ(StatusCode::OK_200, res->status);
  7564. EXPECT_EQ(LARGE_DATA, res->body);
  7565. // The compressed size should be less than a 10th of the original. May vary
  7566. // depending on the zlib library.
  7567. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7568. static_cast<uint64_t>(10 * 1024 * 1024));
  7569. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7570. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7571. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7572. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7573. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7574. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7575. #endif
  7576. }
  7577. TEST_F(ServerTest, PutContentWithDeflate) {
  7578. cli_.set_compress(false);
  7579. Headers headers;
  7580. headers.emplace("Content-Encoding", "deflate");
  7581. // PUT in deflate format:
  7582. auto res = cli_.Put("/put", headers,
  7583. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7585. EXPECT_EQ(StatusCode::OK_200, res->status);
  7586. EXPECT_EQ("PUT", res->body);
  7587. }
  7588. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7589. Headers headers;
  7590. headers.emplace("Accept-Encoding", "gzip, deflate");
  7591. auto res = cli_.Get("/streamed-chunked", headers);
  7592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7593. EXPECT_EQ(StatusCode::OK_200, res->status);
  7594. EXPECT_EQ(std::string("123456789"), res->body);
  7595. }
  7596. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7597. Headers headers;
  7598. headers.emplace("Accept-Encoding", "gzip, deflate");
  7599. auto res = cli_.Get("/streamed-chunked2", headers);
  7600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7601. EXPECT_EQ(StatusCode::OK_200, res->status);
  7602. EXPECT_EQ(std::string("123456789"), res->body);
  7603. }
  7604. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7605. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7607. EXPECT_EQ(StatusCode::OK_200, res->status);
  7608. }
  7609. TEST(GzipDecompressor, ChunkedDecompression) {
  7610. std::string data;
  7611. for (size_t i = 0; i < 32 * 1024; ++i) {
  7612. data.push_back(static_cast<char>('a' + i % 26));
  7613. }
  7614. std::string compressed_data;
  7615. {
  7616. httplib::detail::gzip_compressor compressor;
  7617. bool result = compressor.compress(
  7618. data.data(), data.size(),
  7619. /*last=*/true,
  7620. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7621. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7622. compressed_data_size);
  7623. return true;
  7624. });
  7625. ASSERT_TRUE(result);
  7626. }
  7627. std::string decompressed_data;
  7628. {
  7629. httplib::detail::gzip_decompressor decompressor;
  7630. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7631. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7632. size_t chunk_size = 130;
  7633. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7634. chunk_begin += chunk_size) {
  7635. size_t current_chunk_size =
  7636. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7637. bool result = decompressor.decompress(
  7638. compressed_data.data() + chunk_begin, current_chunk_size,
  7639. [&](const char *decompressed_data_chunk,
  7640. size_t decompressed_data_chunk_size) {
  7641. decompressed_data.insert(decompressed_data.size(),
  7642. decompressed_data_chunk,
  7643. decompressed_data_chunk_size);
  7644. return true;
  7645. });
  7646. ASSERT_TRUE(result);
  7647. }
  7648. }
  7649. ASSERT_EQ(data, decompressed_data);
  7650. }
  7651. TEST(GzipDecompressor, DeflateDecompression) {
  7652. std::string original_text = "Raw deflate without gzip";
  7653. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7654. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7655. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7656. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7657. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7658. std::string decompressed_data;
  7659. {
  7660. httplib::detail::gzip_decompressor decompressor;
  7661. bool result = decompressor.decompress(
  7662. compressed_data.data(), compressed_data.size(),
  7663. [&](const char *decompressed_data_chunk,
  7664. size_t decompressed_data_chunk_size) {
  7665. decompressed_data.insert(decompressed_data.size(),
  7666. decompressed_data_chunk,
  7667. decompressed_data_chunk_size);
  7668. return true;
  7669. });
  7670. ASSERT_TRUE(result);
  7671. }
  7672. ASSERT_EQ(original_text, decompressed_data);
  7673. }
  7674. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7675. std::string original_text = "Raw deflate without gzip";
  7676. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7677. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7678. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7679. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7680. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7681. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7682. std::string decompressed_data;
  7683. {
  7684. httplib::detail::gzip_decompressor decompressor;
  7685. bool result = decompressor.decompress(
  7686. compressed_data.data(), compressed_data.size(),
  7687. [&](const char *decompressed_data_chunk,
  7688. size_t decompressed_data_chunk_size) {
  7689. decompressed_data.insert(decompressed_data.size(),
  7690. decompressed_data_chunk,
  7691. decompressed_data_chunk_size);
  7692. return true;
  7693. });
  7694. ASSERT_TRUE(result);
  7695. }
  7696. ASSERT_EQ(original_text, decompressed_data);
  7697. }
  7698. #endif
  7699. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7700. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7701. Headers headers;
  7702. headers.emplace("Accept-Encoding", "br");
  7703. auto res = cli_.Get("/streamed-chunked", headers);
  7704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7705. EXPECT_EQ(StatusCode::OK_200, res->status);
  7706. EXPECT_EQ(std::string("123456789"), res->body);
  7707. }
  7708. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7709. Headers headers;
  7710. headers.emplace("Accept-Encoding", "br");
  7711. auto res = cli_.Get("/streamed-chunked2", headers);
  7712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7713. EXPECT_EQ(StatusCode::OK_200, res->status);
  7714. EXPECT_EQ(std::string("123456789"), res->body);
  7715. }
  7716. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7717. cli_.set_compress(true);
  7718. auto res = cli_.Put(
  7719. "/put", 3,
  7720. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7721. sink.os << "PUT";
  7722. return true;
  7723. },
  7724. "text/plain");
  7725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7726. EXPECT_EQ(StatusCode::OK_200, res->status);
  7727. EXPECT_EQ("PUT", res->body);
  7728. }
  7729. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7730. cli_.set_compress(true);
  7731. auto res = cli_.Put(
  7732. "/put",
  7733. [](size_t /*offset*/, DataSink &sink) {
  7734. sink.os << "PUT";
  7735. sink.done();
  7736. return true;
  7737. },
  7738. "text/plain");
  7739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7740. EXPECT_EQ(StatusCode::OK_200, res->status);
  7741. EXPECT_EQ("PUT", res->body);
  7742. }
  7743. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7744. cli_.set_compress(true);
  7745. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7747. EXPECT_EQ(StatusCode::OK_200, res->status);
  7748. EXPECT_EQ(LARGE_DATA, res->body);
  7749. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7750. }
  7751. #endif
  7752. TEST_F(ServerTest, Patch) {
  7753. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7755. EXPECT_EQ(StatusCode::OK_200, res->status);
  7756. EXPECT_EQ("PATCH", res->body);
  7757. }
  7758. TEST_F(ServerTest, Delete) {
  7759. auto res = cli_.Delete("/delete");
  7760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7761. EXPECT_EQ(StatusCode::OK_200, res->status);
  7762. EXPECT_EQ("DELETE", res->body);
  7763. }
  7764. TEST_F(ServerTest, DeleteContentReceiver) {
  7765. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7767. EXPECT_EQ(StatusCode::OK_200, res->status);
  7768. EXPECT_EQ("content", res->body);
  7769. }
  7770. TEST_F(ServerTest, Options) {
  7771. auto res = cli_.Options("*");
  7772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7773. EXPECT_EQ(StatusCode::OK_200, res->status);
  7774. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7775. EXPECT_TRUE(res->body.empty());
  7776. }
  7777. TEST_F(ServerTest, URL) {
  7778. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7780. EXPECT_EQ(StatusCode::OK_200, res->status);
  7781. }
  7782. TEST_F(ServerTest, ArrayParam) {
  7783. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7785. EXPECT_EQ(StatusCode::OK_200, res->status);
  7786. }
  7787. TEST_F(ServerTest, ArrayParamValues) {
  7788. auto res =
  7789. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7791. EXPECT_EQ(StatusCode::OK_200, res->status);
  7792. }
  7793. TEST_F(ServerTest, NoMultipleHeaders) {
  7794. Headers headers = {{"Content-Length", "5"}};
  7795. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7796. "text/plain");
  7797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7798. EXPECT_EQ(StatusCode::OK_200, res->status);
  7799. }
  7800. TEST_F(ServerTest, PostContentReceiver) {
  7801. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7803. ASSERT_EQ(StatusCode::OK_200, res->status);
  7804. ASSERT_EQ("content", res->body);
  7805. }
  7806. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7807. UploadFormDataItems items = {
  7808. {"text1", "text default", "", ""},
  7809. {"text2", "aωb", "", ""},
  7810. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7811. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7812. {"file3", "", "", "application/octet-stream"},
  7813. };
  7814. auto res = cli_.Post("/content_receiver", items);
  7815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7816. EXPECT_EQ(StatusCode::OK_200, res->status);
  7817. }
  7818. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7819. UploadFormDataItems items = {
  7820. {"text1", "text default", "", ""},
  7821. {"text2", "aωb", "", ""},
  7822. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7823. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7824. {"file3", "", "", "application/octet-stream"},
  7825. };
  7826. auto boundary = std::string("+++++");
  7827. std::string body;
  7828. for (const auto &item : items) {
  7829. body += "--" + boundary + "\r\n";
  7830. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7831. if (!item.filename.empty()) {
  7832. body += "; filename=\"" + item.filename + "\"";
  7833. }
  7834. body += "\r\n";
  7835. if (!item.content_type.empty()) {
  7836. body += "Content-Type: " + item.content_type + "\r\n";
  7837. }
  7838. body += "\r\n";
  7839. body += item.content + "\r\n";
  7840. }
  7841. body += "--" + boundary + "--\r\n";
  7842. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7843. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7845. EXPECT_EQ(StatusCode::OK_200, res->status);
  7846. }
  7847. TEST(MultipartFormDataTest, FieldEscaping) {
  7848. Server svr;
  7849. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7850. const ContentReader &content_reader) {
  7851. ASSERT_TRUE(req.is_multipart_form_data());
  7852. std::vector<FormData> received;
  7853. content_reader(
  7854. [&](const FormData &file) {
  7855. received.push_back(file);
  7856. return true;
  7857. },
  7858. [&](const char *data, size_t data_length) {
  7859. received.back().content.append(data, data_length);
  7860. return true;
  7861. });
  7862. // '"', CR and LF in names and filenames are escaped following the
  7863. // WHATWG HTML standard, so each part still parses as a single part
  7864. // with no injected headers. Content types get CR/LF escaped too,
  7865. // while '"' (legal there, e.g. quoted charset) is preserved.
  7866. ASSERT_EQ(4U, received.size());
  7867. EXPECT_EQ("na%22me", received[0].name);
  7868. EXPECT_EQ("quoted name", received[0].content);
  7869. EXPECT_EQ("file", received[1].name);
  7870. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7871. received[1].filename);
  7872. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7873. EXPECT_EQ("injected", received[1].content);
  7874. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7875. EXPECT_EQ("my%22file.txt", received[2].filename);
  7876. EXPECT_EQ("cr lf name", received[2].content);
  7877. EXPECT_EQ("typed", received[3].name);
  7878. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7879. received[3].content_type);
  7880. EXPECT_EQ("typed content", received[3].content);
  7881. });
  7882. auto port = svr.bind_to_any_port("localhost");
  7883. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7884. auto se = detail::scope_exit([&] {
  7885. svr.stop();
  7886. t.join();
  7887. ASSERT_FALSE(svr.is_running());
  7888. });
  7889. svr.wait_until_ready();
  7890. Client cli("localhost", port);
  7891. UploadFormDataItems items = {
  7892. {"na\"me", "quoted name", "", ""},
  7893. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7894. "application/octet-stream"},
  7895. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7896. {"typed", "typed content", "",
  7897. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7898. };
  7899. auto res = cli.Post("/post", items);
  7900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7901. EXPECT_EQ(StatusCode::OK_200, res->status);
  7902. }
  7903. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7904. const UploadFormDataItems items = {
  7905. {"name1", "Content 1", "", ""},
  7906. {"name2", "Content 2", "file2.txt", "text/plain"},
  7907. };
  7908. Server svr;
  7909. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7910. const ContentReader &content_reader) {
  7911. ASSERT_TRUE(req.is_multipart_form_data());
  7912. std::vector<FormData> received;
  7913. content_reader(
  7914. [&](const FormData &file) {
  7915. received.push_back(file);
  7916. return true;
  7917. },
  7918. [&](const char *data, size_t data_length) {
  7919. received.back().content.append(data, data_length);
  7920. return true;
  7921. });
  7922. ASSERT_EQ(2U, received.size());
  7923. EXPECT_EQ("name1", received[0].name);
  7924. EXPECT_EQ("Content 1", received[0].content);
  7925. EXPECT_EQ("name2", received[1].name);
  7926. EXPECT_EQ("Content 2", received[1].content);
  7927. EXPECT_EQ("file2.txt", received[1].filename);
  7928. EXPECT_EQ("text/plain", received[1].content_type);
  7929. });
  7930. auto port = svr.bind_to_any_port("localhost");
  7931. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7932. auto se = detail::scope_exit([&] {
  7933. svr.stop();
  7934. t.join();
  7935. ASSERT_FALSE(svr.is_running());
  7936. });
  7937. svr.wait_until_ready();
  7938. Client cli("localhost", port);
  7939. // Whole-body serialization with a generated boundary
  7940. {
  7941. MultipartFormDataWriter writer;
  7942. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7943. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7944. writer.content_type());
  7945. auto body = writer.serialize(items);
  7946. EXPECT_EQ(body.size(), writer.content_length(items));
  7947. auto res = cli.Post("/post", body, writer.content_type());
  7948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7949. EXPECT_EQ(StatusCode::OK_200, res->status);
  7950. }
  7951. // Per-part framing with a custom boundary via a content provider
  7952. {
  7953. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7954. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7955. MultipartFormDataWriter writer("custom-boundary_123");
  7956. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7957. std::string body;
  7958. for (const auto &item : items) {
  7959. body += writer.item_begin(item);
  7960. body += item.content;
  7961. body += MultipartFormDataWriter::item_end();
  7962. }
  7963. body += writer.finish();
  7964. EXPECT_EQ(body.size(), writer.content_length(items));
  7965. auto res = cli.Post(
  7966. "/post", body.size(),
  7967. [&](size_t offset, size_t length, DataSink &sink) {
  7968. sink.write(body.data() + offset, length);
  7969. return true;
  7970. },
  7971. writer.content_type());
  7972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7973. EXPECT_EQ(StatusCode::OK_200, res->status);
  7974. }
  7975. }
  7976. TEST_F(ServerTest, PostContentReceiverGzip) {
  7977. cli_.set_compress(true);
  7978. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7980. ASSERT_EQ(StatusCode::OK_200, res->status);
  7981. ASSERT_EQ("content", res->body);
  7982. }
  7983. TEST_F(ServerTest, PutContentReceiver) {
  7984. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7986. ASSERT_EQ(StatusCode::OK_200, res->status);
  7987. ASSERT_EQ("content", res->body);
  7988. }
  7989. TEST_F(ServerTest, PatchContentReceiver) {
  7990. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7992. ASSERT_EQ(StatusCode::OK_200, res->status);
  7993. ASSERT_EQ("content", res->body);
  7994. }
  7995. template <typename ClientType>
  7996. void TestWithHeadersAndContentReceiver(
  7997. ClientType &cli,
  7998. std::function<Result(ClientType &, const std::string &, const Headers &,
  7999. const std::string &, const std::string &,
  8000. ContentReceiver, DownloadProgress)>
  8001. request_func) {
  8002. Headers headers;
  8003. headers.emplace("X-Custom-Header", "test-value");
  8004. std::string received_body;
  8005. auto res = request_func(
  8006. cli, "/content_receiver", headers, "content", "application/json",
  8007. [&](const char *data, size_t data_length) {
  8008. received_body.append(data, data_length);
  8009. return true;
  8010. },
  8011. nullptr);
  8012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8013. EXPECT_EQ(StatusCode::OK_200, res->status);
  8014. EXPECT_EQ("content", received_body);
  8015. }
  8016. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8017. #ifdef CPPHTTPLIB_SSL_ENABLED
  8018. using ClientT = SSLClient;
  8019. #else
  8020. using ClientT = Client;
  8021. #endif
  8022. TestWithHeadersAndContentReceiver<ClientT>(
  8023. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8024. const std::string &body, const std::string &content_type,
  8025. ContentReceiver receiver, DownloadProgress progress) {
  8026. return cli.Post(path, headers, body, content_type, receiver, progress);
  8027. });
  8028. }
  8029. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8030. #ifdef CPPHTTPLIB_SSL_ENABLED
  8031. using ClientT = SSLClient;
  8032. #else
  8033. using ClientT = Client;
  8034. #endif
  8035. TestWithHeadersAndContentReceiver<ClientT>(
  8036. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8037. const std::string &body, const std::string &content_type,
  8038. ContentReceiver receiver, DownloadProgress progress) {
  8039. return cli.Put(path, headers, body, content_type, receiver, progress);
  8040. });
  8041. }
  8042. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8043. #ifdef CPPHTTPLIB_SSL_ENABLED
  8044. using ClientT = SSLClient;
  8045. #else
  8046. using ClientT = Client;
  8047. #endif
  8048. TestWithHeadersAndContentReceiver<ClientT>(
  8049. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8050. const std::string &body, const std::string &content_type,
  8051. ContentReceiver receiver, DownloadProgress progress) {
  8052. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8053. });
  8054. }
  8055. template <typename ClientType>
  8056. void TestWithHeadersAndContentReceiverWithProgress(
  8057. ClientType &cli,
  8058. std::function<Result(ClientType &, const std::string &, const Headers &,
  8059. const std::string &, const std::string &,
  8060. ContentReceiver, DownloadProgress)>
  8061. request_func) {
  8062. Headers headers;
  8063. headers.emplace("X-Test-Header", "progress-test");
  8064. std::string received_body;
  8065. auto progress_called = false;
  8066. auto res = request_func(
  8067. cli, "/content_receiver", headers, "content", "text/plain",
  8068. [&](const char *data, size_t data_length) {
  8069. received_body.append(data, data_length);
  8070. return true;
  8071. },
  8072. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8073. progress_called = true;
  8074. return true;
  8075. });
  8076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8077. EXPECT_EQ(StatusCode::OK_200, res->status);
  8078. EXPECT_EQ("content", received_body);
  8079. EXPECT_TRUE(progress_called);
  8080. }
  8081. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8082. #ifdef CPPHTTPLIB_SSL_ENABLED
  8083. using ClientT = SSLClient;
  8084. #else
  8085. using ClientT = Client;
  8086. #endif
  8087. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8088. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8089. const std::string &body, const std::string &content_type,
  8090. ContentReceiver receiver, DownloadProgress progress) {
  8091. return cli.Post(path, headers, body, content_type, receiver, progress);
  8092. });
  8093. }
  8094. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8095. #ifdef CPPHTTPLIB_SSL_ENABLED
  8096. using ClientT = SSLClient;
  8097. #else
  8098. using ClientT = Client;
  8099. #endif
  8100. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8101. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8102. const std::string &body, const std::string &content_type,
  8103. ContentReceiver receiver, DownloadProgress progress) {
  8104. return cli.Put(path, headers, body, content_type, receiver, progress);
  8105. });
  8106. }
  8107. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8108. #ifdef CPPHTTPLIB_SSL_ENABLED
  8109. using ClientT = SSLClient;
  8110. #else
  8111. using ClientT = Client;
  8112. #endif
  8113. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8114. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8115. const std::string &body, const std::string &content_type,
  8116. ContentReceiver receiver, DownloadProgress progress) {
  8117. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8118. });
  8119. }
  8120. template <typename ClientType>
  8121. void TestWithHeadersAndContentReceiverError(
  8122. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8123. const Headers &, const std::string &,
  8124. const std::string &, ContentReceiver)>
  8125. request_func) {
  8126. Headers headers;
  8127. headers.emplace("X-Error-Test", "true");
  8128. std::string received_body;
  8129. auto receiver_failed = false;
  8130. auto res =
  8131. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8132. [&](const char *data, size_t data_length) {
  8133. received_body.append(data, data_length);
  8134. receiver_failed = true;
  8135. return false;
  8136. });
  8137. ASSERT_FALSE(res);
  8138. EXPECT_TRUE(receiver_failed);
  8139. }
  8140. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8141. #ifdef CPPHTTPLIB_SSL_ENABLED
  8142. using ClientT = SSLClient;
  8143. #else
  8144. using ClientT = Client;
  8145. #endif
  8146. TestWithHeadersAndContentReceiverError<ClientT>(
  8147. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8148. const std::string &body, const std::string &content_type,
  8149. ContentReceiver receiver) {
  8150. return cli.Post(path, headers, body, content_type, receiver);
  8151. });
  8152. }
  8153. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8154. #ifdef CPPHTTPLIB_SSL_ENABLED
  8155. using ClientT = SSLClient;
  8156. #else
  8157. using ClientT = Client;
  8158. #endif
  8159. TestWithHeadersAndContentReceiverError<ClientT>(
  8160. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8161. const std::string &body, const std::string &content_type,
  8162. ContentReceiver receiver) {
  8163. return cli.Put(path, headers, body, content_type, receiver);
  8164. });
  8165. }
  8166. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8167. #ifdef CPPHTTPLIB_SSL_ENABLED
  8168. using ClientT = SSLClient;
  8169. #else
  8170. using ClientT = Client;
  8171. #endif
  8172. TestWithHeadersAndContentReceiverError<ClientT>(
  8173. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8174. const std::string &body, const std::string &content_type,
  8175. ContentReceiver receiver) {
  8176. return cli.Patch(path, headers, body, content_type, receiver);
  8177. });
  8178. }
  8179. TEST_F(ServerTest, PostQueryStringAndBody) {
  8180. auto res =
  8181. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8183. ASSERT_EQ(StatusCode::OK_200, res->status);
  8184. }
  8185. TEST_F(ServerTest, HTTP2Magic) {
  8186. Request req;
  8187. req.method = "PRI";
  8188. req.path = "*";
  8189. req.body = "SM";
  8190. auto res = std::make_shared<Response>();
  8191. auto error = Error::Success;
  8192. auto ret = cli_.send(req, *res, error);
  8193. ASSERT_TRUE(ret);
  8194. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8195. }
  8196. TEST_F(ServerTest, KeepAlive) {
  8197. auto res = cli_.Get("/hi");
  8198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8199. EXPECT_EQ(StatusCode::OK_200, res->status);
  8200. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8201. EXPECT_EQ("Hello World!", res->body);
  8202. res = cli_.Get("/hi");
  8203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8204. EXPECT_EQ(StatusCode::OK_200, res->status);
  8205. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8206. EXPECT_EQ("Hello World!", res->body);
  8207. res = cli_.Get("/hi");
  8208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8209. EXPECT_EQ(StatusCode::OK_200, res->status);
  8210. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8211. EXPECT_EQ("Hello World!", res->body);
  8212. res = cli_.Get("/not-exist");
  8213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8214. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8215. res = cli_.Post("/empty", "", "text/plain");
  8216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8217. EXPECT_EQ(StatusCode::OK_200, res->status);
  8218. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8219. EXPECT_EQ("empty", res->body);
  8220. EXPECT_EQ("close", res->get_header_value("Connection"));
  8221. res = cli_.Post(
  8222. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8223. "text/plain");
  8224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8225. EXPECT_EQ(StatusCode::OK_200, res->status);
  8226. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8227. EXPECT_EQ("empty", res->body);
  8228. cli_.set_keep_alive(false);
  8229. res = cli_.Get("/last-request");
  8230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8231. EXPECT_EQ(StatusCode::OK_200, res->status);
  8232. EXPECT_EQ("close", res->get_header_value("Connection"));
  8233. }
  8234. TEST_F(ServerTest, TooManyRedirect) {
  8235. cli_.set_follow_location(true);
  8236. auto res = cli_.Get("/redirect/0");
  8237. ASSERT_TRUE(!res);
  8238. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8239. }
  8240. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8241. Request req;
  8242. req.method = "FOOBAR";
  8243. req.path = "/hi";
  8244. cli_.set_keep_alive(true);
  8245. auto res = cli_.send(req);
  8246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8247. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8248. EXPECT_EQ("close", res->get_header_value("Connection"));
  8249. EXPECT_FALSE(cli_.is_socket_open());
  8250. }
  8251. TEST_F(ServerTest, CustomRouteReadsBody) {
  8252. const std::string xml =
  8253. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8254. Request req;
  8255. req.method = "PROPFIND";
  8256. req.path = "/dav/dir";
  8257. req.set_header("Depth", "1");
  8258. req.body = xml;
  8259. auto res = cli_.send(req);
  8260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8261. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8262. EXPECT_EQ(xml, res->body);
  8263. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8264. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8265. }
  8266. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8267. Request req;
  8268. req.method = "PROPFIND";
  8269. req.path = "/dav/42";
  8270. auto res = cli_.send(req);
  8271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8272. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8273. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8274. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8275. }
  8276. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8277. Request req;
  8278. req.method = "PROPFIND";
  8279. req.path = "/dav-re/123";
  8280. auto res = cli_.send(req);
  8281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8282. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8283. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8284. }
  8285. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8286. Request req;
  8287. req.method = "MKCOL";
  8288. req.path = "/dav-mkcol";
  8289. auto res = cli_.send(req);
  8290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8291. EXPECT_EQ(StatusCode::Created_201, res->status);
  8292. }
  8293. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8294. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8295. Request req;
  8296. req.method = "REPORT";
  8297. req.path = "/dav-report";
  8298. req.body = xml;
  8299. auto res = cli_.send(req);
  8300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8301. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8302. EXPECT_EQ(xml, res->body);
  8303. }
  8304. // A content reader route must fire even when the request carries no body,
  8305. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8306. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8307. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8308. Request req;
  8309. req.method = "REPORT";
  8310. req.path = "/dav-report";
  8311. auto res = cli_.send(req);
  8312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8313. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8314. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8315. }
  8316. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8317. Request req;
  8318. req.method = "PROPFIND";
  8319. req.path = "/not-dav";
  8320. auto res = cli_.send(req);
  8321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8322. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8323. }
  8324. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8325. Request req;
  8326. req.method = "UNLOCK";
  8327. req.path = "/dav/dir";
  8328. cli_.set_keep_alive(true);
  8329. auto res = cli_.send(req);
  8330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8331. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8332. EXPECT_EQ("close", res->get_header_value("Connection"));
  8333. EXPECT_FALSE(cli_.is_socket_open());
  8334. }
  8335. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8336. // The mount point serves this path, but only for GET and HEAD.
  8337. auto get_res = cli_.Get("/dir/index.html");
  8338. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8339. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8340. Request req;
  8341. req.method = "PROPFIND";
  8342. req.path = "/dir/index.html";
  8343. auto res = cli_.send(req);
  8344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8345. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8346. }
  8347. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8348. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8349. cli_.set_keep_alive(true);
  8350. for (auto i = 0; i < 2; i++) {
  8351. Request req;
  8352. req.method = "PROPFIND";
  8353. req.path = "/dav/dir";
  8354. req.body = xml;
  8355. auto res = cli_.send(req);
  8356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8357. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8358. EXPECT_EQ(xml, res->body);
  8359. EXPECT_TRUE(cli_.is_socket_open());
  8360. }
  8361. // A built-in method must still be served on the same connection.
  8362. cli_.set_keep_alive(false);
  8363. auto res = cli_.Get("/hi");
  8364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8365. EXPECT_EQ(StatusCode::OK_200, res->status);
  8366. EXPECT_EQ("close", res->get_header_value("Connection"));
  8367. }
  8368. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8369. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8370. Request req;
  8371. req.method = "PROPFIND";
  8372. req.path = "/dav/dir";
  8373. req.set_header("Expect", "100-continue");
  8374. req.body = xml;
  8375. auto res = cli_.send(req);
  8376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8377. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8378. EXPECT_EQ(xml, res->body);
  8379. }
  8380. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8381. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8382. TEST_F(ServerTest, Gzip) {
  8383. Headers headers;
  8384. headers.emplace("Accept-Encoding", "gzip, deflate");
  8385. auto res = cli_.Get("/compress", headers);
  8386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8387. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8388. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8389. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8390. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8391. "7890123456789012345678901234567890",
  8392. res->body);
  8393. EXPECT_EQ(StatusCode::OK_200, res->status);
  8394. }
  8395. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8396. Headers headers;
  8397. headers.emplace("Accept-Encoding", "gzip, deflate");
  8398. auto res = cli_.Get("/compress-with-charset", headers);
  8399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8400. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8401. EXPECT_EQ("application/json; charset=utf-8",
  8402. res->get_header_value("Content-Type"));
  8403. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8404. "7890123456789012345678901234567890",
  8405. res->body);
  8406. EXPECT_EQ(StatusCode::OK_200, res->status);
  8407. }
  8408. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8409. Headers headers;
  8410. headers.emplace("Accept-Encoding", "");
  8411. auto res = cli_.Get("/compress", headers);
  8412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8413. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8414. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8415. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8416. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8417. "7890123456789012345678901234567890",
  8418. res->body);
  8419. EXPECT_EQ(StatusCode::OK_200, res->status);
  8420. }
  8421. TEST_F(ServerTest, GzipWithContentReceiver) {
  8422. Headers headers;
  8423. headers.emplace("Accept-Encoding", "gzip, deflate");
  8424. std::string body;
  8425. auto res = cli_.Get("/compress", headers,
  8426. [&](const char *data, uint64_t data_length) {
  8427. EXPECT_EQ(100U, data_length);
  8428. body.append(data, data_length);
  8429. return true;
  8430. });
  8431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8432. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8433. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8434. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8435. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8436. "7890123456789012345678901234567890",
  8437. body);
  8438. EXPECT_EQ(StatusCode::OK_200, res->status);
  8439. }
  8440. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8441. Headers headers;
  8442. headers.emplace("Accept-Encoding", "gzip, deflate");
  8443. cli_.set_decompress(false);
  8444. auto res = cli_.Get("/compress", headers);
  8445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8446. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8447. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8448. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8449. EXPECT_EQ(33U, res->body.size());
  8450. EXPECT_EQ(StatusCode::OK_200, res->status);
  8451. }
  8452. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  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, NoGzip) {
  8472. Headers headers;
  8473. headers.emplace("Accept-Encoding", "gzip, deflate");
  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, NoGzipWithContentReceiver) {
  8485. Headers headers;
  8486. headers.emplace("Accept-Encoding", "gzip, deflate");
  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. TEST_F(ServerTest, MultipartFormDataGzip) {
  8504. UploadFormDataItems items = {
  8505. {"key1", "test", "", ""},
  8506. {"key2", "--abcdefg123", "", ""},
  8507. };
  8508. cli_.set_compress(true);
  8509. auto res = cli_.Post("/compress-multipart", items);
  8510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8511. EXPECT_EQ(StatusCode::OK_200, res->status);
  8512. }
  8513. #endif
  8514. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8515. // Static file compression is opt-in, so these run their own server rather than
  8516. // flipping it on for the shared ServerTest fixture, which would silently
  8517. // rewrite what every other static file test is asserting.
  8518. class StaticFileCompressionTest : public ::testing::Test {
  8519. protected:
  8520. void TearDown() override {
  8521. if (t_.joinable()) {
  8522. svr_.stop();
  8523. t_.join();
  8524. }
  8525. }
  8526. int start(const std::function<void(Server &)> &configure = nullptr) {
  8527. // Serves the same tree as a directory of build-time compressed assets
  8528. // would be served: the mount point names the coding the files are already
  8529. // stored in. Registered before "/" so it is the one that matches.
  8530. svr_.set_mount_point("/pre-encoded", "./www",
  8531. {{"Content-Encoding", "gzip"}});
  8532. svr_.set_mount_point("/", "./www");
  8533. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8534. res.set_file_content("./www/dir/index.html", "text/html");
  8535. });
  8536. svr_.Get("/pre-encoded-file-content",
  8537. [](const Request & /*req*/, Response &res) {
  8538. res.set_header("Content-Encoding", "gzip");
  8539. res.set_file_content("./www/dir/index.html", "text/html");
  8540. });
  8541. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8542. res.set_content_provider(
  8543. 6, "text/plain",
  8544. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8545. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8546. return true;
  8547. });
  8548. });
  8549. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8550. res.set_content_provider(
  8551. 1000, "text/plain",
  8552. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8553. if (offset < 100) {
  8554. std::string data(100, 'A');
  8555. sink.write(data.data(), data.size());
  8556. return true;
  8557. }
  8558. std::this_thread::sleep_for(std::chrono::seconds(2));
  8559. std::string data(900, 'B');
  8560. sink.write(data.data(), data.size());
  8561. return true;
  8562. });
  8563. });
  8564. if (configure) { configure(svr_); }
  8565. auto port = svr_.bind_to_any_port(HOST);
  8566. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8567. svr_.wait_until_ready();
  8568. return port;
  8569. }
  8570. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8571. // Every file under ./www except 1MB.txt is smaller than the default
  8572. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8573. // it out of the way.
  8574. static void enable_without_floor(Server &svr) {
  8575. svr.set_static_file_compression(true);
  8576. svr.set_static_file_compression_min_length(0);
  8577. }
  8578. Server svr_;
  8579. std::thread t_;
  8580. };
  8581. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8582. auto port = start();
  8583. Client cli(HOST, port);
  8584. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8586. EXPECT_EQ(StatusCode::OK_200, res->status);
  8587. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8588. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8589. EXPECT_EQ(1048576U, res->body.size());
  8590. }
  8591. TEST_F(StaticFileCompressionTest, MountPoint) {
  8592. auto port = start(enable);
  8593. Client cli(HOST, port);
  8594. cli.set_decompress(false);
  8595. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8597. EXPECT_EQ(StatusCode::OK_200, res->status);
  8598. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8599. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8600. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8601. // The response stays self-delimiting: a length, not a chunked body.
  8602. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8603. EXPECT_EQ(std::to_string(res->body.size()),
  8604. res->get_header_value("Content-Length"));
  8605. EXPECT_LT(res->body.size(), 1048576U);
  8606. EXPECT_FALSE(res->body.empty());
  8607. }
  8608. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8609. auto port = start(enable);
  8610. Client cli(HOST, port);
  8611. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8613. EXPECT_EQ(StatusCode::OK_200, res->status);
  8614. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8615. EXPECT_EQ(1048576U, res->body.size());
  8616. }
  8617. TEST_F(StaticFileCompressionTest, FileContent) {
  8618. auto port = start(enable_without_floor);
  8619. Client cli(HOST, port);
  8620. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8622. EXPECT_EQ(StatusCode::OK_200, res->status);
  8623. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8624. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8625. EXPECT_EQ(104U, res->body.size());
  8626. }
  8627. // A handler that serves an already-encoded file names the coding itself. The
  8628. // file-backed path decided its coding from Accept-Encoding and the content
  8629. // type alone, so it compressed the stored bytes a second time and appended a
  8630. // second Content-Encoding field line.
  8631. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8632. auto port = start(enable_without_floor);
  8633. Client cli(HOST, port);
  8634. cli.set_decompress(false);
  8635. auto res = cli.Get("/pre-encoded-file-content",
  8636. Headers{{"Accept-Encoding", "gzip"}});
  8637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8638. EXPECT_EQ(StatusCode::OK_200, res->status);
  8639. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8640. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8641. // Vary belongs to a coding the server chose, and it chose none here.
  8642. EXPECT_FALSE(res->has_header("Vary"));
  8643. // The file travels exactly as it is stored on disk.
  8644. EXPECT_EQ(104U, res->body.size());
  8645. }
  8646. // The 1MB file clears the default floor, so this one runs the configuration a
  8647. // deployment would actually have.
  8648. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8649. auto port = start(enable);
  8650. Client cli(HOST, port);
  8651. cli.set_decompress(false);
  8652. auto res =
  8653. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8655. EXPECT_EQ(StatusCode::OK_200, res->status);
  8656. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8657. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8658. EXPECT_FALSE(res->has_header("Vary"));
  8659. EXPECT_EQ(1048576U, res->body.size());
  8660. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8661. }
  8662. TEST_F(StaticFileCompressionTest, Head) {
  8663. auto port = start(enable);
  8664. Client cli(HOST, port);
  8665. cli.set_decompress(false);
  8666. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8667. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8668. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8670. EXPECT_EQ(StatusCode::OK_200, res->status);
  8671. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8672. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8673. // HEAD still reports the size a GET would return.
  8674. EXPECT_EQ(get->get_header_value("Content-Length"),
  8675. res->get_header_value("Content-Length"));
  8676. EXPECT_TRUE(res->body.empty());
  8677. }
  8678. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8679. auto port = start(enable);
  8680. Client cli(HOST, port);
  8681. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8682. {"Accept-Encoding", "gzip"}});
  8683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8684. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8685. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8686. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8687. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8688. EXPECT_EQ("cd", res->body);
  8689. }
  8690. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8691. auto port = start(enable);
  8692. Client cli(HOST, port);
  8693. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8695. EXPECT_EQ(StatusCode::OK_200, res->status);
  8696. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8697. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8698. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8699. }
  8700. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8701. auto port = start(enable);
  8702. Client cli(HOST, port);
  8703. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8705. EXPECT_EQ(StatusCode::OK_200, res->status);
  8706. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8707. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8708. EXPECT_TRUE(res->body.empty());
  8709. }
  8710. TEST_F(StaticFileCompressionTest, MinLength) {
  8711. auto port = start(enable);
  8712. Client cli(HOST, port);
  8713. // 104 bytes, well under the default floor. Compressing it would add the
  8714. // gzip header and trailer to a body that already fits in one packet.
  8715. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8717. EXPECT_EQ(StatusCode::OK_200, res->status);
  8718. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8719. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8720. }
  8721. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8722. auto port = start([](Server &svr) {
  8723. svr.set_static_file_compression(true);
  8724. svr.set_static_file_compression_min_length(1);
  8725. });
  8726. Client cli(HOST, port);
  8727. cli.set_decompress(false);
  8728. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8730. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8731. // A 9-byte file comes back larger than it went in, because gzip's header and
  8732. // trailer outweigh anything deflate can save. That is the end of the range
  8733. // the floor exists to keep out.
  8734. EXPECT_GT(res->body.size(), 9U);
  8735. }
  8736. TEST_F(StaticFileCompressionTest, MaxLength) {
  8737. auto port = start([](Server &svr) {
  8738. svr.set_static_file_compression(true);
  8739. svr.set_static_file_compression_min_length(0);
  8740. svr.set_static_file_compression_max_length(1024);
  8741. });
  8742. Client cli(HOST, port);
  8743. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8744. // defines `small` as a macro on Windows.
  8745. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8746. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8747. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8748. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8749. // Under it: compressed.
  8750. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8751. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8752. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8753. }
  8754. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8755. auto port = start(enable_without_floor);
  8756. Client cli(HOST, port);
  8757. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8758. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8759. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8760. auto identity_etag = identity->get_header_value("ETag");
  8761. ASSERT_FALSE(identity_etag.empty());
  8762. auto gzipped =
  8763. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8764. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8765. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8766. auto gzip_etag = gzipped->get_header_value("ETag");
  8767. ASSERT_FALSE(gzip_etag.empty());
  8768. // Two representations, two validators.
  8769. EXPECT_NE(identity_etag, gzip_etag);
  8770. // Each one revalidates against the request that would produce it...
  8771. auto fresh =
  8772. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8773. {"If-None-Match", gzip_etag}});
  8774. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8775. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8776. auto fresh_identity =
  8777. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8778. {"If-None-Match", identity_etag}});
  8779. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8780. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8781. // ...and not against the other representation.
  8782. auto crossed =
  8783. cli.Get("/dir/index.html",
  8784. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8785. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8786. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8787. }
  8788. // The opt-in covers responses the server reads off disk itself. A caller's own
  8789. // known-length provider keeps its Content-Length and, more importantly, keeps
  8790. // delivering incrementally: routing it through a compressor would hold every
  8791. // write back until zlib's window filled.
  8792. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8793. auto port = start(enable);
  8794. Client cli(HOST, port);
  8795. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8797. EXPECT_EQ(StatusCode::OK_200, res->status);
  8798. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8799. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8800. EXPECT_EQ("aaabbb", res->body);
  8801. }
  8802. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8803. auto port = start(enable);
  8804. Client cli(HOST, port);
  8805. cli.set_read_timeout(1, 0);
  8806. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8807. Headers{{"Accept-Encoding", "gzip"}});
  8808. ASSERT_TRUE(handle.is_valid());
  8809. // The provider writes 100 bytes and then stalls for longer than the read
  8810. // timeout. Those first bytes have to arrive anyway: run the response through
  8811. // a compressor and zlib holds them until its window fills, so the read would
  8812. // come back empty instead.
  8813. char buf[256];
  8814. auto n = handle.read(buf, sizeof(buf));
  8815. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8816. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8817. }
  8818. #endif
  8819. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8820. TEST_F(ServerTest, Brotli) {
  8821. Headers headers;
  8822. headers.emplace("Accept-Encoding", "br");
  8823. auto res = cli_.Get("/compress", headers);
  8824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8825. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8826. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8827. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8828. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8829. "7890123456789012345678901234567890",
  8830. res->body);
  8831. EXPECT_EQ(StatusCode::OK_200, res->status);
  8832. }
  8833. #endif
  8834. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8835. TEST_F(ServerTest, Zstd) {
  8836. Headers headers;
  8837. headers.emplace("Accept-Encoding", "zstd");
  8838. auto res = cli_.Get("/compress", headers);
  8839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8840. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8841. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8842. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8843. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8844. "7890123456789012345678901234567890",
  8845. res->body);
  8846. EXPECT_EQ(StatusCode::OK_200, res->status);
  8847. }
  8848. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8849. Headers headers;
  8850. headers.emplace("Accept-Encoding", "");
  8851. auto res = cli_.Get("/compress", headers);
  8852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8853. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8854. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8855. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8856. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8857. "7890123456789012345678901234567890",
  8858. res->body);
  8859. EXPECT_EQ(StatusCode::OK_200, res->status);
  8860. }
  8861. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8862. Headers headers;
  8863. headers.emplace("Accept-Encoding", "zstd");
  8864. std::string body;
  8865. auto res = cli_.Get("/compress", headers,
  8866. [&](const char *data, uint64_t data_length) {
  8867. EXPECT_EQ(100U, data_length);
  8868. body.append(data, data_length);
  8869. return true;
  8870. });
  8871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8872. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8873. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8874. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8875. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8876. "7890123456789012345678901234567890",
  8877. body);
  8878. EXPECT_EQ(StatusCode::OK_200, res->status);
  8879. }
  8880. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8881. Headers headers;
  8882. headers.emplace("Accept-Encoding", "zstd");
  8883. cli_.set_decompress(false);
  8884. auto res = cli_.Get("/compress", headers);
  8885. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8886. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8887. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8888. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8890. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8891. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8892. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8893. EXPECT_EQ(StatusCode::OK_200, res->status);
  8894. ASSERT_EQ(26U, res->body.size());
  8895. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8896. 0);
  8897. }
  8898. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8899. Headers headers;
  8900. headers.emplace("Accept-Encoding", "");
  8901. std::string body;
  8902. auto res = cli_.Get("/compress", headers,
  8903. [&](const char *data, uint64_t data_length) {
  8904. EXPECT_EQ(100U, data_length);
  8905. body.append(data, data_length);
  8906. return true;
  8907. });
  8908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8909. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8910. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8911. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8912. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8913. "7890123456789012345678901234567890",
  8914. body);
  8915. EXPECT_EQ(StatusCode::OK_200, res->status);
  8916. }
  8917. TEST_F(ServerTest, NoZstd) {
  8918. Headers headers;
  8919. headers.emplace("Accept-Encoding", "zstd");
  8920. auto res = cli_.Get("/nocompress", headers);
  8921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8922. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8923. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8924. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8925. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8926. "7890123456789012345678901234567890",
  8927. res->body);
  8928. EXPECT_EQ(StatusCode::OK_200, res->status);
  8929. }
  8930. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8931. Headers headers;
  8932. headers.emplace("Accept-Encoding", "zstd");
  8933. std::string body;
  8934. auto res = cli_.Get("/nocompress", headers,
  8935. [&](const char *data, uint64_t data_length) {
  8936. EXPECT_EQ(100U, data_length);
  8937. body.append(data, data_length);
  8938. return true;
  8939. });
  8940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8941. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8942. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8943. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8944. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8945. "7890123456789012345678901234567890",
  8946. body);
  8947. EXPECT_EQ(StatusCode::OK_200, res->status);
  8948. }
  8949. // TODO: How to enable zstd ??
  8950. TEST_F(ServerTest, MultipartFormDataZstd) {
  8951. UploadFormDataItems items = {
  8952. {"key1", "test", "", ""},
  8953. {"key2", "--abcdefg123", "", ""},
  8954. };
  8955. Headers headers;
  8956. headers.emplace("Accept-Encoding", "zstd");
  8957. cli_.set_compress(true);
  8958. auto res = cli_.Post("/compress-multipart", headers, items);
  8959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8960. EXPECT_EQ(StatusCode::OK_200, res->status);
  8961. }
  8962. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8963. Headers headers;
  8964. headers.emplace("Accept-Encoding", "zstd");
  8965. cli_.set_compress(true);
  8966. auto res = cli_.Put(
  8967. "/put", headers, 3,
  8968. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8969. sink.os << "PUT";
  8970. return true;
  8971. },
  8972. "text/plain");
  8973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8974. EXPECT_EQ(StatusCode::OK_200, res->status);
  8975. EXPECT_EQ("PUT", res->body);
  8976. }
  8977. // Pre-compression logging tests
  8978. TEST_F(ServerTest, PreCompressionLogging) {
  8979. // Test data for compression (matches the actual /compress endpoint content)
  8980. const std::string test_content =
  8981. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8982. "3456789012345678901234567890";
  8983. // Variables to capture logging data
  8984. std::string pre_compression_body;
  8985. std::string pre_compression_content_type;
  8986. std::string pre_compression_content_encoding;
  8987. std::string post_compression_body;
  8988. std::string post_compression_content_type;
  8989. std::string post_compression_content_encoding;
  8990. // Set up pre-compression logger
  8991. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8992. const Response &res) {
  8993. pre_compression_body = res.body;
  8994. pre_compression_content_type = res.get_header_value("Content-Type");
  8995. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8996. });
  8997. // Set up post-compression logger
  8998. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8999. post_compression_body = res.body;
  9000. post_compression_content_type = res.get_header_value("Content-Type");
  9001. post_compression_content_encoding =
  9002. res.get_header_value("Content-Encoding");
  9003. });
  9004. // Test with gzip compression
  9005. Headers headers;
  9006. headers.emplace("Accept-Encoding", "gzip");
  9007. auto res = cli_.Get("/compress", headers);
  9008. // Verify response was compressed
  9009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9010. EXPECT_EQ(StatusCode::OK_200, res->status);
  9011. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9012. // Verify pre-compression logger captured uncompressed content
  9013. EXPECT_EQ(test_content, pre_compression_body);
  9014. EXPECT_EQ("text/plain", pre_compression_content_type);
  9015. EXPECT_TRUE(pre_compression_content_encoding
  9016. .empty()); // No encoding header before compression
  9017. // Verify post-compression logger captured compressed content
  9018. EXPECT_NE(test_content,
  9019. post_compression_body); // Should be different after compression
  9020. EXPECT_EQ("text/plain", post_compression_content_type);
  9021. EXPECT_EQ("gzip", post_compression_content_encoding);
  9022. // Verify compressed content is smaller
  9023. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9024. }
  9025. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9026. const std::string test_content =
  9027. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9028. "3456789012345678901234567890";
  9029. std::string pre_compression_body;
  9030. std::string post_compression_body;
  9031. svr_.set_pre_compression_logger(
  9032. [&](const Request & /*req*/, const Response &res) {
  9033. pre_compression_body = res.body;
  9034. });
  9035. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9036. post_compression_body = res.body;
  9037. });
  9038. Headers headers;
  9039. headers.emplace("Accept-Encoding", "br");
  9040. auto res = cli_.Get("/compress", headers);
  9041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9042. EXPECT_EQ(StatusCode::OK_200, res->status);
  9043. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9044. // Verify pre-compression content is uncompressed
  9045. EXPECT_EQ(test_content, pre_compression_body);
  9046. // Verify post-compression content is compressed
  9047. EXPECT_NE(test_content, post_compression_body);
  9048. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9049. }
  9050. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9051. const std::string test_content =
  9052. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9053. "3456789012345678901234567890";
  9054. std::string pre_compression_body;
  9055. std::string post_compression_body;
  9056. svr_.set_pre_compression_logger(
  9057. [&](const Request & /*req*/, const Response &res) {
  9058. pre_compression_body = res.body;
  9059. });
  9060. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9061. post_compression_body = res.body;
  9062. });
  9063. // Request without compression (use /nocompress endpoint)
  9064. Headers headers;
  9065. auto res = cli_.Get("/nocompress", headers);
  9066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9067. EXPECT_EQ(StatusCode::OK_200, res->status);
  9068. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9069. // Pre-compression logger should not be called when no compression is applied
  9070. EXPECT_TRUE(
  9071. pre_compression_body.empty()); // Pre-compression logger not called
  9072. EXPECT_EQ(
  9073. test_content,
  9074. post_compression_body); // Post-compression logger captures final content
  9075. }
  9076. TEST_F(ServerTest, LoggerSeesContentLength) {
  9077. size_t logged_content_length = 0;
  9078. std::string logged_content_length_header;
  9079. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9080. logged_content_length = res.content_length_;
  9081. logged_content_length_header = res.get_header_value("Content-Length");
  9082. });
  9083. auto res = cli_.Get("/nocompress");
  9084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9085. EXPECT_EQ(StatusCode::OK_200, res->status);
  9086. EXPECT_EQ(res->body.size(), logged_content_length);
  9087. EXPECT_EQ(std::to_string(logged_content_length),
  9088. logged_content_length_header);
  9089. }
  9090. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9091. const std::string test_content =
  9092. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9093. "3456789012345678901234567890";
  9094. std::string pre_compression_body;
  9095. bool pre_logger_called = false;
  9096. // Set only pre-compression logger
  9097. svr_.set_pre_compression_logger(
  9098. [&](const Request & /*req*/, const Response &res) {
  9099. pre_compression_body = res.body;
  9100. pre_logger_called = true;
  9101. });
  9102. Headers headers;
  9103. headers.emplace("Accept-Encoding", "gzip");
  9104. auto res = cli_.Get("/compress", headers);
  9105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9106. EXPECT_EQ(StatusCode::OK_200, res->status);
  9107. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9108. // Verify pre-compression logger was called
  9109. EXPECT_TRUE(pre_logger_called);
  9110. EXPECT_EQ(test_content, pre_compression_body);
  9111. }
  9112. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9113. {
  9114. // Test with Expect: 100-continue header - success case
  9115. // Server returns 100 Continue, client sends body, server returns 200 OK
  9116. Request req;
  9117. req.method = "POST";
  9118. req.path = "/post-large";
  9119. req.set_header("Expect", "100-continue");
  9120. req.body = LARGE_DATA;
  9121. Response res;
  9122. auto error = Error::Success;
  9123. cli_.set_keep_alive(true);
  9124. auto ret = cli_.send(req, res, error);
  9125. EXPECT_TRUE(ret);
  9126. EXPECT_EQ(StatusCode::OK_200, res.status);
  9127. EXPECT_EQ(LARGE_DATA, res.body);
  9128. }
  9129. {
  9130. // Test with Expect: 100-continue header - error case
  9131. // Client should not send the body when server returns an error
  9132. Request req;
  9133. req.method = "POST";
  9134. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9135. req.set_header("Expect", "100-continue");
  9136. req.body = LARGE_DATA;
  9137. Response res;
  9138. auto error = Error::Success;
  9139. auto start = std::chrono::high_resolution_clock::now();
  9140. cli_.set_keep_alive(true);
  9141. auto ret = cli_.send(req, res, error);
  9142. auto end = std::chrono::high_resolution_clock::now();
  9143. auto elapsed =
  9144. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9145. .count();
  9146. // With Expect: 100-continue, request completes successfully but with error
  9147. EXPECT_TRUE(ret);
  9148. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9149. EXPECT_EQ("close", res.get_header_value("Connection"));
  9150. EXPECT_FALSE(cli_.is_socket_open());
  9151. EXPECT_LE(elapsed, 2000);
  9152. }
  9153. {
  9154. // Send an extra GET request to ensure error recovery without hanging
  9155. Request req;
  9156. req.method = "GET";
  9157. req.path = "/hi";
  9158. auto start = std::chrono::high_resolution_clock::now();
  9159. auto res = cli_.send(req);
  9160. auto end = std::chrono::high_resolution_clock::now();
  9161. auto elapsed =
  9162. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9163. .count();
  9164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9165. EXPECT_EQ(StatusCode::OK_200, res->status);
  9166. EXPECT_EQ("Hello World!", res->body);
  9167. EXPECT_LE(elapsed, 500);
  9168. }
  9169. }
  9170. TEST(ZstdDecompressor, ChunkedDecompression) {
  9171. std::string data;
  9172. for (size_t i = 0; i < 32 * 1024; ++i) {
  9173. data.push_back(static_cast<char>('a' + i % 26));
  9174. }
  9175. std::string compressed_data;
  9176. {
  9177. httplib::detail::zstd_compressor compressor;
  9178. bool result = compressor.compress(
  9179. data.data(), data.size(),
  9180. /*last=*/true,
  9181. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9182. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9183. compressed_data_size);
  9184. return true;
  9185. });
  9186. ASSERT_TRUE(result);
  9187. }
  9188. std::string decompressed_data;
  9189. {
  9190. httplib::detail::zstd_decompressor decompressor;
  9191. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9192. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9193. size_t chunk_size = 130;
  9194. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9195. chunk_begin += chunk_size) {
  9196. size_t current_chunk_size =
  9197. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9198. bool result = decompressor.decompress(
  9199. compressed_data.data() + chunk_begin, current_chunk_size,
  9200. [&](const char *decompressed_data_chunk,
  9201. size_t decompressed_data_chunk_size) {
  9202. decompressed_data.insert(decompressed_data.size(),
  9203. decompressed_data_chunk,
  9204. decompressed_data_chunk_size);
  9205. return true;
  9206. });
  9207. ASSERT_TRUE(result);
  9208. }
  9209. }
  9210. ASSERT_EQ(data, decompressed_data);
  9211. }
  9212. TEST(ZstdDecompressor, Decompress) {
  9213. std::string original_text = "Compressed with ZSTD";
  9214. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9215. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9216. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9217. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9218. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9219. std::string decompressed_data;
  9220. {
  9221. httplib::detail::zstd_decompressor decompressor;
  9222. bool result = decompressor.decompress(
  9223. compressed_data.data(), compressed_data.size(),
  9224. [&](const char *decompressed_data_chunk,
  9225. size_t decompressed_data_chunk_size) {
  9226. decompressed_data.insert(decompressed_data.size(),
  9227. decompressed_data_chunk,
  9228. decompressed_data_chunk_size);
  9229. return true;
  9230. });
  9231. ASSERT_TRUE(result);
  9232. }
  9233. ASSERT_EQ(original_text, decompressed_data);
  9234. }
  9235. #endif
  9236. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9237. // separate chunks so that the server sees each part in its own read(). Used to
  9238. // place a read boundary at a specific offset of a request body.
  9239. static bool send_request_in_parts(time_t read_timeout_sec,
  9240. const std::vector<std::string> &parts,
  9241. std::string *resp = nullptr,
  9242. int port = PORT) {
  9243. auto error = Error::Success;
  9244. auto client_sock = detail::create_client_socket(
  9245. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9246. /*connection_timeout_sec=*/5, 0,
  9247. /*read_timeout_sec=*/5, 0,
  9248. /*write_timeout_sec=*/5, 0, std::string(), error);
  9249. if (client_sock == INVALID_SOCKET) { return false; }
  9250. auto ret = detail::process_client_socket(
  9251. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9252. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9253. for (size_t i = 0; i < parts.size(); i++) {
  9254. const auto &part = parts[i];
  9255. if (part.size() !=
  9256. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9257. return false;
  9258. }
  9259. if (i + 1 < parts.size()) {
  9260. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9261. }
  9262. }
  9263. char buf[512];
  9264. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9265. while (line_reader.getline()) {
  9266. if (resp) { *resp += line_reader.ptr(); }
  9267. }
  9268. return true;
  9269. });
  9270. detail::close_socket(client_sock);
  9271. return ret;
  9272. }
  9273. // Sends a raw request to a server listening at HOST:PORT.
  9274. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9275. std::string *resp = nullptr, int port = PORT) {
  9276. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9277. }
  9278. #ifdef CPPHTTPLIB_SSL_ENABLED
  9279. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9280. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9281. ASSERT_TRUE(svr.is_valid());
  9282. svr.set_read_timeout(1, 0);
  9283. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9284. auto se = detail::scope_exit([&] {
  9285. svr.stop();
  9286. t.join();
  9287. ASSERT_FALSE(svr.is_running());
  9288. });
  9289. svr.wait_until_ready();
  9290. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9291. // keeps each wait well within the read timeout. The server gives up a
  9292. // second in, so the bytes sent after that fail.
  9293. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9294. parts.resize(26, std::string(1, '\0'));
  9295. EXPECT_FALSE(send_request_in_parts(5, parts));
  9296. }
  9297. #endif
  9298. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9299. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9300. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9301. const std::vector<std::string> &parts,
  9302. std::string *resp = nullptr,
  9303. int port = PORT) {
  9304. auto error = Error::Success;
  9305. auto sock = detail::create_client_socket(
  9306. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9307. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9308. /*write_timeout_sec=*/5, 0, std::string(), error);
  9309. if (sock == INVALID_SOCKET) { return false; }
  9310. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9311. auto ctx = SSL_CTX_new(TLS_client_method());
  9312. auto ssl = SSL_new(ctx);
  9313. auto ssl_se = detail::scope_exit([&] {
  9314. SSL_free(ssl);
  9315. SSL_CTX_free(ctx);
  9316. });
  9317. SSL_set_fd(ssl, static_cast<int>(sock));
  9318. if (SSL_connect(ssl) != 1) { return false; }
  9319. for (size_t i = 0; i < parts.size(); i++) {
  9320. const auto &part = parts[i];
  9321. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9322. static_cast<int>(part.size())) {
  9323. return false;
  9324. }
  9325. if (i + 1 < parts.size()) {
  9326. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9327. }
  9328. }
  9329. char buf[512];
  9330. int n;
  9331. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9332. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9333. }
  9334. return true;
  9335. }
  9336. #endif
  9337. // The request line, then a header value a byte at a time.
  9338. static std::vector<std::string> slow_request_head_parts() {
  9339. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9340. parts.resize(26, "a");
  9341. parts.emplace_back("\r\n\r\n");
  9342. return parts;
  9343. }
  9344. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9345. // within the one-second read timeout. The server gives up a second in, before
  9346. // the head is complete.
  9347. static void
  9348. expect_slow_request_head_dropped(Server &svr,
  9349. const std::function<std::string()> &send) {
  9350. std::atomic<bool> handled(false);
  9351. svr.Get("/", [&](const Request &, Response &res) {
  9352. handled = true;
  9353. res.set_content("ok", "text/plain");
  9354. });
  9355. svr.set_read_timeout(1, 0);
  9356. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9357. auto se = detail::scope_exit([&] {
  9358. svr.stop();
  9359. t.join();
  9360. ASSERT_FALSE(svr.is_running());
  9361. });
  9362. svr.wait_until_ready();
  9363. auto resp = send();
  9364. EXPECT_FALSE(handled);
  9365. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9366. }
  9367. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9368. Server svr;
  9369. expect_slow_request_head_dropped(svr, [] {
  9370. std::string resp;
  9371. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9372. return resp;
  9373. });
  9374. }
  9375. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9376. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9377. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9378. ASSERT_TRUE(svr.is_valid());
  9379. expect_slow_request_head_dropped(svr, [] {
  9380. std::string resp;
  9381. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9382. return resp;
  9383. });
  9384. }
  9385. #endif
  9386. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9387. Server svr;
  9388. std::string header_value;
  9389. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9390. header_value = req.get_header_value("foo");
  9391. res.set_content("ok", "text/plain");
  9392. });
  9393. thread t = thread([&] { svr.listen(HOST, PORT); });
  9394. auto se = detail::scope_exit([&] {
  9395. svr.stop();
  9396. t.join();
  9397. ASSERT_FALSE(svr.is_running());
  9398. });
  9399. svr.wait_until_ready();
  9400. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9401. // like characters are not treated the same - use vertical tab and escape.
  9402. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9403. "foo: \t \v bar \x1B\t \r\n"
  9404. "Connection: close\r\n"
  9405. "\r\n";
  9406. std::string res;
  9407. ASSERT_TRUE(send_request(5, req, &res));
  9408. EXPECT_EQ(header_value, "");
  9409. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9410. }
  9411. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9412. Server svr;
  9413. std::string received;
  9414. svr.Get("/order", [&](const Request &req, Response &res) {
  9415. received = entries_to_string(req.headers);
  9416. res.set_content("ok", "text/plain");
  9417. });
  9418. auto port = svr.bind_to_any_port(HOST);
  9419. thread t = thread([&] { svr.listen_after_bind(); });
  9420. auto se = detail::scope_exit([&] {
  9421. svr.stop();
  9422. t.join();
  9423. ASSERT_FALSE(svr.is_running());
  9424. });
  9425. svr.wait_until_ready();
  9426. const std::string req = "GET /order HTTP/1.1\r\n"
  9427. "Host: localhost\r\n"
  9428. "X-First: 1\r\n"
  9429. "X-Dup: a\r\n"
  9430. "X-Second: 2\r\n"
  9431. "X-Dup: b\r\n"
  9432. "Connection: close\r\n"
  9433. "\r\n";
  9434. std::string res;
  9435. ASSERT_TRUE(send_request(5, req, &res, port));
  9436. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9437. EXPECT_EQ(
  9438. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9439. received);
  9440. }
  9441. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9442. Server svr;
  9443. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9444. res.set_header("Set-Cookie", "first=1");
  9445. res.set_header("X-Between", "y");
  9446. res.set_header("Set-Cookie", "second=2");
  9447. res.set_content("ok", "text/plain");
  9448. });
  9449. auto port = svr.bind_to_any_port(HOST);
  9450. thread t = thread([&] { svr.listen_after_bind(); });
  9451. auto se = detail::scope_exit([&] {
  9452. svr.stop();
  9453. t.join();
  9454. ASSERT_FALSE(svr.is_running());
  9455. });
  9456. svr.wait_until_ready();
  9457. Client cli(HOST, port);
  9458. auto res = cli.Get("/cookies");
  9459. ASSERT_TRUE(res);
  9460. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9461. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9462. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9463. }
  9464. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9465. Server svr;
  9466. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9467. auto i = new int(0);
  9468. res.set_header("Trailer", "X-Safe, X-Reflected");
  9469. res.set_chunked_content_provider(
  9470. "text/plain",
  9471. [i](size_t /*offset*/, DataSink &sink) {
  9472. if (*i == 0) {
  9473. sink.os << "body";
  9474. } else {
  9475. Headers trailer;
  9476. // A valid trailer that must survive.
  9477. trailer.emplace("X-Safe", "safe");
  9478. // Attacker-controlled value carrying CR/LF (response splitting).
  9479. trailer.emplace("X-Reflected",
  9480. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9481. // Attacker-controlled name carrying CR/LF.
  9482. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9483. sink.done_with_trailer(trailer);
  9484. }
  9485. (*i)++;
  9486. return true;
  9487. },
  9488. [i](bool /*success*/) { delete i; });
  9489. });
  9490. thread t = thread([&] { svr.listen(HOST, PORT); });
  9491. auto se = detail::scope_exit([&] {
  9492. svr.stop();
  9493. t.join();
  9494. ASSERT_FALSE(svr.is_running());
  9495. });
  9496. svr.wait_until_ready();
  9497. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9498. "Host: " + HOST +
  9499. "\r\n"
  9500. "Connection: close\r\n"
  9501. "\r\n";
  9502. std::string res;
  9503. ASSERT_TRUE(send_request(5, req, &res));
  9504. // The injected fields must not appear anywhere in the raw response.
  9505. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9506. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9507. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9508. // Invalid trailers are dropped entirely, matching set_header().
  9509. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9510. // The valid trailer still passes through.
  9511. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9512. }
  9513. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9514. Server svr;
  9515. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9516. // res.headers is a public field an application can populate directly,
  9517. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9518. // A valid header that must survive.
  9519. res.headers.emplace("X-Safe", "safe");
  9520. // Attacker-controlled value carrying CR/LF (response splitting).
  9521. res.headers.emplace("X-Reflected",
  9522. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9523. // Attacker-controlled name carrying CR/LF.
  9524. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9525. res.set_content("body", "text/plain");
  9526. });
  9527. thread t = thread([&] { svr.listen(HOST, PORT); });
  9528. auto se = detail::scope_exit([&] {
  9529. svr.stop();
  9530. t.join();
  9531. ASSERT_FALSE(svr.is_running());
  9532. });
  9533. svr.wait_until_ready();
  9534. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9535. "Host: " + HOST +
  9536. "\r\n"
  9537. "Connection: close\r\n"
  9538. "\r\n";
  9539. std::string res;
  9540. ASSERT_TRUE(send_request(5, req, &res));
  9541. // The injected fields must not appear anywhere in the raw response.
  9542. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9543. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9544. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9545. // Invalid headers are dropped entirely, matching set_header().
  9546. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9547. // The valid header still passes through.
  9548. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9549. }
  9550. // Forward declaration: in split builds split.py strips `inline` and moves the
  9551. // definition into httplib.cc, so detail::write_request_line is not visible from
  9552. // the public httplib.h. Re-declaring it here lets the tests link against the
  9553. // symbol in both header-only and split builds.
  9554. namespace httplib {
  9555. namespace detail {
  9556. ssize_t write_request_line(Stream &strm, const std::string &method,
  9557. const std::string &path);
  9558. } // namespace detail
  9559. } // namespace httplib
  9560. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9561. // A well-formed target is written verbatim.
  9562. {
  9563. detail::BufferStream strm;
  9564. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9565. EXPECT_GT(n, 0);
  9566. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9567. }
  9568. // A target carrying CR/LF, SP or other control octets must be rejected
  9569. // before anything reaches the wire, otherwise it splits the request line and
  9570. // injects a header or a whole request.
  9571. const std::string evil_targets[] = {
  9572. "/a\r\nInjected: pwned",
  9573. "/a\rInjected",
  9574. "/a\nInjected",
  9575. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9576. "/a b",
  9577. "/a\tb",
  9578. "/a\x7f",
  9579. };
  9580. for (const auto &evil : evil_targets) {
  9581. detail::BufferStream strm;
  9582. auto n = detail::write_request_line(strm, "GET", evil);
  9583. EXPECT_LT(n, 0);
  9584. EXPECT_TRUE(strm.get_buffer().empty());
  9585. }
  9586. }
  9587. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9588. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9589. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9590. // target reaches write_request. The client must fail cleanly with
  9591. // Error::Write instead of putting a request-line-less, header-injecting
  9592. // request on the wire.
  9593. Server svr;
  9594. svr.Get("/a", [](const Request &, Response &res) {
  9595. res.set_content("ok", "text/plain");
  9596. });
  9597. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9598. auto se = detail::scope_exit([&] {
  9599. svr.stop();
  9600. thread.join();
  9601. ASSERT_FALSE(svr.is_running());
  9602. });
  9603. svr.wait_until_ready();
  9604. {
  9605. Client cli(HOST, PORT);
  9606. cli.set_path_encode(false);
  9607. // The request is rejected before anything is written, so the connection
  9608. // stays silent and the subsequent response read would otherwise block for
  9609. // the full default read timeout. Shorten it -- the assertion is on the
  9610. // error, not the timeout.
  9611. cli.set_read_timeout(1, 0);
  9612. auto res = cli.Get("/a\r\nInjected: pwned");
  9613. EXPECT_FALSE(res);
  9614. EXPECT_EQ(Error::Write, res.error());
  9615. }
  9616. }
  9617. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9618. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9619. // including extension methods.
  9620. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9621. for (const auto &method : good_methods) {
  9622. detail::BufferStream strm;
  9623. auto n = detail::write_request_line(strm, method, "/");
  9624. EXPECT_GT(n, 0);
  9625. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9626. }
  9627. // A method carrying CR/LF would split the request line and smuggle a whole
  9628. // request ahead of the real one. A space or an empty method corrupts the
  9629. // request line. All must be rejected before anything reaches the wire.
  9630. const std::string evil_methods[] = {
  9631. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9632. "GET\r\nInjected: pwned",
  9633. "GET\r",
  9634. "GET\n",
  9635. "GE T",
  9636. "",
  9637. };
  9638. for (const auto &evil : evil_methods) {
  9639. detail::BufferStream strm;
  9640. auto n = detail::write_request_line(strm, evil, "/");
  9641. EXPECT_LT(n, 0);
  9642. EXPECT_TRUE(strm.get_buffer().empty());
  9643. }
  9644. }
  9645. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9646. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9647. // through Client::send must fail with Error::Write and no request, neither
  9648. // the smuggled one nor the real one, may reach the server.
  9649. Server svr;
  9650. std::atomic<int> request_count(0);
  9651. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9652. request_count++;
  9653. res.status = StatusCode::OK_200;
  9654. return Server::HandlerResponse::Handled;
  9655. });
  9656. auto port = svr.bind_to_any_port(HOST);
  9657. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9658. auto se = detail::scope_exit([&] {
  9659. svr.stop();
  9660. thread.join();
  9661. ASSERT_FALSE(svr.is_running());
  9662. });
  9663. svr.wait_until_ready();
  9664. {
  9665. Client cli(HOST, port);
  9666. const std::string evil_methods[] = {
  9667. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9668. "GE T",
  9669. "",
  9670. };
  9671. for (const auto &evil : evil_methods) {
  9672. Request req;
  9673. req.method = evil;
  9674. req.path = "/";
  9675. auto res = cli.send(req);
  9676. EXPECT_FALSE(res);
  9677. EXPECT_EQ(Error::Write, res.error());
  9678. }
  9679. auto handle =
  9680. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9681. EXPECT_FALSE(handle.is_valid());
  9682. EXPECT_EQ(Error::Write, handle.error);
  9683. // A valid request on the same client still goes through.
  9684. auto res = cli.Get("/");
  9685. ASSERT_TRUE(res);
  9686. EXPECT_EQ(StatusCode::OK_200, res->status);
  9687. }
  9688. EXPECT_EQ(1, request_count.load());
  9689. }
  9690. // Sends a raw request and verifies that there isn't a crash or exception.
  9691. static void test_raw_request(const std::string &req,
  9692. std::string *out = nullptr) {
  9693. Server svr;
  9694. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9695. res.set_content("ok", "text/plain");
  9696. });
  9697. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9698. res.set_content("ok", "text/plain");
  9699. });
  9700. svr.Get("/header_field_value_check",
  9701. [&](const Request & /*req*/, Response &res) {
  9702. res.set_content("ok", "text/plain");
  9703. });
  9704. svr.CustomRoute("PROPFIND", "/dav",
  9705. [&](const Request & /*req*/, Response &res) {
  9706. res.status = StatusCode::MultiStatus_207;
  9707. });
  9708. // Server read timeout must be longer than the client read timeout for the
  9709. // bug to reproduce, probably to force the server to process a request
  9710. // without a trailing blank line.
  9711. const time_t client_read_timeout_sec = 1;
  9712. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9713. bool listen_thread_ok = false;
  9714. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9715. auto se = detail::scope_exit([&] {
  9716. svr.stop();
  9717. t.join();
  9718. ASSERT_FALSE(svr.is_running());
  9719. EXPECT_TRUE(listen_thread_ok);
  9720. });
  9721. svr.wait_until_ready();
  9722. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9723. }
  9724. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9725. // A certain header line causes an exception if the header property is parsed
  9726. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9727. test_raw_request(
  9728. "GET /hi HTTP/1.1\r\n"
  9729. " : "
  9730. " "
  9731. " ");
  9732. }
  9733. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9734. // A certain header line causes an exception if the header property *name* is
  9735. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9736. // greedy matcher and requires backtracking when there are a lot of ":"
  9737. // characters.
  9738. // This occurs with libc++ but not libstdc++.
  9739. test_raw_request(
  9740. "GET /hi HTTP/1.1\r\n"
  9741. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9742. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9743. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9744. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9745. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9746. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9747. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9748. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9749. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9750. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9751. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9752. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9753. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9754. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9755. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9756. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9757. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9758. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9759. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9760. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9761. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9762. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9763. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9764. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9765. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9766. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9767. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9768. "&&&%%%");
  9769. }
  9770. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9771. // Make sure this doesn't crash the server.
  9772. // In a previous version of the header line regex, the "\r" rendered the line
  9773. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9774. // a new position where the leading white space ended and the field value
  9775. // began.
  9776. // The crash occurs with libc++ but not libstdc++.
  9777. test_raw_request("GET /hi HTTP/1.1\r\n"
  9778. "a:" +
  9779. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9780. "\r\n"
  9781. "\r\n");
  9782. }
  9783. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9784. const char *rejected[] = {
  9785. // RFC 9112 §3: one SP between the parts, and nothing else
  9786. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9787. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9788. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9789. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9790. // A request-target has no fragment
  9791. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9792. // An HTTP/1.1 request needs a Host
  9793. "GET /hi HTTP/1.1\r\n\r\n",
  9794. };
  9795. for (auto request : rejected) {
  9796. std::string out;
  9797. test_raw_request(request, &out);
  9798. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9799. }
  9800. std::string out;
  9801. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9802. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9803. }
  9804. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9805. // RFC 9112 §6.1
  9806. const char *requests[] = {
  9807. "PUT /put_hi HTTP/1.1\r\n"
  9808. "Host: localhost\r\n"
  9809. "Content-Length: 0\r\n"
  9810. "Transfer-Encoding: chunked\r\n"
  9811. "\r\n"
  9812. "0\r\n\r\n",
  9813. "PUT /put_hi HTTP/1.0\r\n"
  9814. "Connection: keep-alive\r\n"
  9815. "Transfer-Encoding: chunked\r\n"
  9816. "\r\n"
  9817. "0\r\n\r\n",
  9818. };
  9819. for (auto request : requests) {
  9820. std::string out;
  9821. test_raw_request(request, &out);
  9822. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9823. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9824. }
  9825. }
  9826. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9827. std::string out;
  9828. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9829. "Content-Type: text/plain\r\n"
  9830. "Transfer-Encoding: chunked\r\n"
  9831. "\r\n"
  9832. "nothex\r\n",
  9833. &out);
  9834. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9835. }
  9836. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9837. std::string out;
  9838. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9839. "Content-Type: text/plain\r\n"
  9840. "Transfer-Encoding: chunked\r\n"
  9841. "\r\n"
  9842. "3\r\n"
  9843. "xyz\r\n"
  9844. "NaN\r\n",
  9845. &out);
  9846. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9847. }
  9848. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9849. std::string out;
  9850. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9851. "Content-Type: text/plain\r\n"
  9852. "Transfer-Encoding: chunked\r\n"
  9853. "\r\n"
  9854. // Length is too large for 64 bits.
  9855. "1ffffffffffffffff\r\n"
  9856. "xyz\r\n",
  9857. &out);
  9858. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9859. }
  9860. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9861. test_raw_request("GET /hi HTTP/1.1\r\n"
  9862. "Content-Type: text/plain\r\n\r");
  9863. }
  9864. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9865. std::string out;
  9866. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9867. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9868. }
  9869. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9870. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9871. std::string out;
  9872. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9873. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9874. }
  9875. }
  9876. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9877. std::string out;
  9878. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9879. "Host: localhost\r\n"
  9880. "Connection: close\r\n\r\n",
  9881. &out);
  9882. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9883. }
  9884. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9885. Server svr;
  9886. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9887. EXPECT_TRUE(!req.remote_addr.empty());
  9888. });
  9889. thread t = thread([&] { svr.listen(HOST, PORT); });
  9890. auto se = detail::scope_exit([&] {
  9891. svr.stop();
  9892. t.join();
  9893. ASSERT_FALSE(svr.is_running());
  9894. });
  9895. svr.wait_until_ready();
  9896. // Send an invalid request line to trigger Bad Request
  9897. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9898. std::string out;
  9899. ASSERT_TRUE(send_request(5, bad_req, &out));
  9900. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9901. }
  9902. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9903. // answered right away rather than blocking on a read that waits for EOF.
  9904. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9905. std::string out;
  9906. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9907. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9908. }
  9909. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9910. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9911. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9912. for (const auto *method : methods) {
  9913. Server svr;
  9914. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9915. EXPECT_FALSE(svr.is_valid()) << method;
  9916. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9917. }
  9918. }
  9919. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9920. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9921. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9922. for (const auto *method : methods) {
  9923. Server svr;
  9924. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9925. EXPECT_FALSE(svr.is_valid()) << method;
  9926. }
  9927. }
  9928. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9929. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9930. "COPY", "MOVE", "LOCK",
  9931. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9932. Server svr;
  9933. for (const auto *method : methods) {
  9934. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9935. }
  9936. EXPECT_TRUE(svr.is_valid());
  9937. }
  9938. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9939. Server svr;
  9940. svr.CustomRoute("POST", "/x",
  9941. [](const Request &, Response &, const ContentReader &) {});
  9942. EXPECT_FALSE(svr.is_valid());
  9943. }
  9944. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9945. Server svr;
  9946. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9947. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9948. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9949. EXPECT_FALSE(svr.is_valid());
  9950. }
  9951. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9952. Server svr;
  9953. auto captured = Error::Success;
  9954. svr.set_error_logger(
  9955. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9956. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9957. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9958. }
  9959. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9960. std::string out;
  9961. std::string request(
  9962. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9963. test_raw_request(request, &out);
  9964. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9965. }
  9966. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9967. std::string out;
  9968. std::string request(
  9969. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9970. test_raw_request(request, &out);
  9971. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9972. }
  9973. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9974. std::string out;
  9975. std::string request(
  9976. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9977. test_raw_request(request, &out);
  9978. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9979. }
  9980. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9981. std::string out;
  9982. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9983. "Host: localhost\r\n"
  9984. "Test: \r\n\r\n",
  9985. &out);
  9986. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9987. }
  9988. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9989. Server svr;
  9990. std::string x_custom;
  9991. std::string cookie;
  9992. std::string xff;
  9993. std::string x_unicode;
  9994. std::string x_iis;
  9995. svr.Get("/check", [&](const Request &req, Response &res) {
  9996. x_custom = req.get_header_value("X-Custom");
  9997. cookie = req.get_header_value("Cookie");
  9998. xff = req.get_header_value("X-Forwarded-For");
  9999. x_unicode = req.get_header_value("X-Unicode");
  10000. x_iis = req.get_header_value("X-IIS");
  10001. res.set_content("ok", "text/plain");
  10002. });
  10003. thread t = thread([&] { svr.listen(HOST, PORT); });
  10004. auto se = detail::scope_exit([&] {
  10005. svr.stop();
  10006. t.join();
  10007. ASSERT_FALSE(svr.is_running());
  10008. });
  10009. svr.wait_until_ready();
  10010. const std::string req = "GET /check HTTP/1.1\r\n"
  10011. "Host: localhost\r\n"
  10012. "X-Custom: a%0D%0AInjected: b\r\n"
  10013. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10014. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10015. "X-Unicode: %E3%81%82\r\n"
  10016. "X-IIS: %u00E9\r\n"
  10017. "Connection: close\r\n"
  10018. "\r\n";
  10019. std::string res;
  10020. ASSERT_TRUE(send_request(5, req, &res));
  10021. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10022. // Every value must be returned verbatim (wire form), with no decoding.
  10023. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10024. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10025. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10026. EXPECT_EQ("%E3%81%82", x_unicode);
  10027. EXPECT_EQ("%u00E9", x_iis);
  10028. }
  10029. // Applications that previously relied on automatic percent-decoding can
  10030. // reproduce the old behavior by explicitly calling decode_path_component()
  10031. // or, for RFC 3986 conformance, decode_uri_component().
  10032. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10033. Server svr;
  10034. std::string decoded;
  10035. svr.Get("/check", [&](const Request &req, Response &res) {
  10036. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10037. res.set_content("ok", "text/plain");
  10038. });
  10039. thread t = thread([&] { svr.listen(HOST, PORT); });
  10040. auto se = detail::scope_exit([&] {
  10041. svr.stop();
  10042. t.join();
  10043. ASSERT_FALSE(svr.is_running());
  10044. });
  10045. svr.wait_until_ready();
  10046. const std::string req = "GET /check HTTP/1.1\r\n"
  10047. "Host: localhost\r\n"
  10048. "X-Custom: hello%20world\r\n"
  10049. "Connection: close\r\n"
  10050. "\r\n";
  10051. std::string res;
  10052. ASSERT_TRUE(send_request(5, req, &res));
  10053. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10054. EXPECT_EQ("hello world", decoded);
  10055. }
  10056. // Regression test for #2033. Browsers send Referer values that include
  10057. // percent-encoded characters such as %0A inside the URL. Decoding the
  10058. // header value would either trip the post-decode CR/LF/NUL guard (the
  10059. // original bug, returning 400) or, after that guard was relaxed, silently
  10060. // store a literal LF — both unacceptable. The wire form must round-trip.
  10061. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10062. Server svr;
  10063. std::string referer;
  10064. svr.Get("/check", [&](const Request &req, Response &res) {
  10065. referer = req.get_header_value("Referer");
  10066. res.set_content("ok", "text/plain");
  10067. });
  10068. thread t = thread([&] { svr.listen(HOST, PORT); });
  10069. auto se = detail::scope_exit([&] {
  10070. svr.stop();
  10071. t.join();
  10072. ASSERT_FALSE(svr.is_running());
  10073. });
  10074. svr.wait_until_ready();
  10075. const std::string req = "GET /check HTTP/1.1\r\n"
  10076. "Host: localhost\r\n"
  10077. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10078. "Connection: close\r\n"
  10079. "\r\n";
  10080. std::string res;
  10081. ASSERT_TRUE(send_request(5, req, &res));
  10082. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10083. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10084. }
  10085. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10086. Server svr;
  10087. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10088. res.set_header("Cache-Control", "no-cache");
  10089. res.set_chunked_content_provider(
  10090. "text/event-stream", [](size_t offset, DataSink &sink) {
  10091. std::string s = "data:";
  10092. s += std::to_string(offset);
  10093. s += "\n\n";
  10094. auto ret = sink.write(s.data(), s.size());
  10095. EXPECT_TRUE(ret);
  10096. std::this_thread::sleep_for(std::chrono::seconds(1));
  10097. return true;
  10098. });
  10099. });
  10100. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10101. svr.wait_until_ready();
  10102. Client client(HOST, PORT);
  10103. const Headers headers = {{"Accept", "text/event-stream"}};
  10104. auto get_thread = std::thread([&client, &headers]() {
  10105. auto res = client.Get(
  10106. "/events", headers,
  10107. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10108. });
  10109. auto se = detail::scope_exit([&] {
  10110. svr.stop();
  10111. get_thread.join();
  10112. listen_thread.join();
  10113. ASSERT_FALSE(svr.is_running());
  10114. });
  10115. // Give GET time to get a few messages.
  10116. std::this_thread::sleep_for(std::chrono::seconds(2));
  10117. }
  10118. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10119. httplib::Server svr;
  10120. svr.Post("/hi",
  10121. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10122. res.status = StatusCode::OK_200;
  10123. });
  10124. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10125. svr.wait_until_ready();
  10126. Client cli(HOST, PORT);
  10127. auto res = cli.Post("/hi", "data", "text/plain");
  10128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10129. EXPECT_EQ(StatusCode::OK_200, res->status);
  10130. svr.stop();
  10131. thread.join();
  10132. ASSERT_FALSE(svr.is_running());
  10133. res = cli.Post("/hi", "data", "text/plain");
  10134. ASSERT_FALSE(res);
  10135. }
  10136. TEST(ServerStopTest, ListenFailure) {
  10137. Server svr;
  10138. auto t = thread([&]() {
  10139. auto ret = svr.listen("????", PORT);
  10140. EXPECT_FALSE(ret);
  10141. });
  10142. svr.wait_until_ready();
  10143. svr.stop();
  10144. t.join();
  10145. }
  10146. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10147. TEST(ServerStopTest, Decommision) {
  10148. Server svr;
  10149. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10150. for (int i = 0; i < 4; i++) {
  10151. auto is_even = !(i % 2);
  10152. std::thread t{[&] {
  10153. try {
  10154. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10155. if (is_even) {
  10156. throw std::runtime_error("Some thing that happens to go wrong.");
  10157. }
  10158. svr.listen(HOST, PORT);
  10159. } catch (...) { svr.decommission(); }
  10160. }};
  10161. svr.wait_until_ready();
  10162. // Server is up
  10163. {
  10164. Client cli(HOST, PORT);
  10165. auto res = cli.Get("/hi");
  10166. if (is_even) {
  10167. EXPECT_FALSE(res);
  10168. } else {
  10169. EXPECT_TRUE(res);
  10170. EXPECT_EQ("hi...", res->body);
  10171. }
  10172. }
  10173. svr.stop();
  10174. t.join();
  10175. // Server is down...
  10176. {
  10177. Client cli(HOST, PORT);
  10178. auto res = cli.Get("/hi");
  10179. EXPECT_FALSE(res);
  10180. }
  10181. }
  10182. }
  10183. #endif
  10184. // Helper function for string body upload progress tests
  10185. template <typename SetupHandler, typename ClientCall>
  10186. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10187. ClientCall &&client_call,
  10188. const string &body) {
  10189. Server svr;
  10190. setup_handler(svr);
  10191. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10192. auto se = detail::scope_exit([&] {
  10193. svr.stop();
  10194. t.join();
  10195. });
  10196. svr.wait_until_ready();
  10197. Client cli(HOST, PORT);
  10198. vector<uint64_t> progress_values;
  10199. bool progress_called = false;
  10200. auto res =
  10201. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10202. progress_values.push_back(current);
  10203. progress_called = true;
  10204. return true;
  10205. });
  10206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10207. EXPECT_EQ(200, res->status);
  10208. EXPECT_TRUE(progress_called);
  10209. }
  10210. TEST(UploadProgressTest, PostStringBodyBasic) {
  10211. TestStringBodyUploadProgress(
  10212. [](Server &svr) {
  10213. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10214. res.set_content("received", "text/plain");
  10215. });
  10216. },
  10217. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10218. return cli.Post("/test", body, "text/plain", progress_callback);
  10219. },
  10220. "test data for upload progress");
  10221. }
  10222. TEST(UploadProgressTest, PutStringBodyBasic) {
  10223. TestStringBodyUploadProgress(
  10224. [](Server &svr) {
  10225. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10226. res.set_content("put received", "text/plain");
  10227. });
  10228. },
  10229. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10230. return cli.Put("/test", body, "text/plain", progress_callback);
  10231. },
  10232. "put test data for upload progress");
  10233. }
  10234. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10235. TestStringBodyUploadProgress(
  10236. [](Server &svr) {
  10237. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10238. res.set_content("patch received", "text/plain");
  10239. });
  10240. },
  10241. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10242. return cli.Patch("/test", body, "text/plain", progress_callback);
  10243. },
  10244. "patch test data for upload progress");
  10245. }
  10246. // Helper function for content provider upload progress tests
  10247. template <typename SetupHandler, typename ClientCall>
  10248. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10249. ClientCall &&client_call) {
  10250. Server svr;
  10251. setup_handler(svr);
  10252. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10253. auto se = detail::scope_exit([&] {
  10254. svr.stop();
  10255. t.join();
  10256. });
  10257. svr.wait_until_ready();
  10258. Client cli(HOST, PORT);
  10259. vector<uint64_t> progress_values;
  10260. auto res =
  10261. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10262. progress_values.push_back(current);
  10263. return true;
  10264. });
  10265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10266. EXPECT_EQ(200, res->status);
  10267. EXPECT_FALSE(progress_values.empty());
  10268. }
  10269. TEST(UploadProgressTest, PostContentProviderProgress) {
  10270. TestContentProviderUploadProgress(
  10271. [](Server &svr) {
  10272. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10273. res.set_content("provider received", "text/plain");
  10274. });
  10275. },
  10276. [](Client &cli, UploadProgress progress_callback) {
  10277. return cli.Post(
  10278. "/test", 9,
  10279. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10280. sink.os << "test data";
  10281. return true;
  10282. },
  10283. "text/plain", progress_callback);
  10284. });
  10285. }
  10286. // Helper function for multipart upload progress tests
  10287. template <typename SetupHandler, typename ClientCall>
  10288. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10289. ClientCall &&client_call,
  10290. const string &endpoint) {
  10291. Server svr;
  10292. setup_handler(svr);
  10293. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10294. auto se = detail::scope_exit([&] {
  10295. svr.stop();
  10296. t.join();
  10297. });
  10298. svr.wait_until_ready();
  10299. Client cli(HOST, PORT);
  10300. vector<uint64_t> progress_values;
  10301. UploadFormDataItems items = {
  10302. {"field1", "value1", "", ""},
  10303. {"field2", "longer value for progress tracking test", "", ""},
  10304. {"file1", "file content data for upload progress", "test.txt",
  10305. "text/plain"}};
  10306. auto res = client_call(cli, endpoint, items,
  10307. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10308. progress_values.push_back(current);
  10309. return true;
  10310. });
  10311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10312. EXPECT_EQ(200, res->status);
  10313. EXPECT_FALSE(progress_values.empty());
  10314. }
  10315. TEST(UploadProgressTest, PostMultipartProgress) {
  10316. TestMultipartUploadProgress(
  10317. [](Server &svr) {
  10318. svr.Post("/multipart", [](const Request &req, Response &res) {
  10319. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10320. res.set_content("multipart received", "text/plain");
  10321. });
  10322. },
  10323. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10324. UploadProgress progress_callback) {
  10325. return cli.Post(endpoint, items, progress_callback);
  10326. },
  10327. "/multipart");
  10328. }
  10329. // Helper function for basic download progress tests
  10330. template <typename SetupHandler, typename ClientCall>
  10331. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10332. ClientCall &&client_call, const string &endpoint,
  10333. size_t expected_content_size) {
  10334. Server svr;
  10335. setup_handler(svr);
  10336. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10337. auto se = detail::scope_exit([&] {
  10338. svr.stop();
  10339. t.join();
  10340. });
  10341. svr.wait_until_ready();
  10342. Client cli(HOST, PORT);
  10343. vector<uint64_t> progress_values;
  10344. auto res = client_call(cli, endpoint,
  10345. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10346. progress_values.push_back(current);
  10347. return true;
  10348. });
  10349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10350. EXPECT_EQ(200, res->status);
  10351. EXPECT_FALSE(progress_values.empty());
  10352. EXPECT_EQ(expected_content_size, res->body.size());
  10353. }
  10354. TEST(DownloadProgressTest, GetBasic) {
  10355. TestBasicDownloadProgress(
  10356. [](Server &svr) {
  10357. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10358. string content(1000, 'D');
  10359. res.set_content(content, "text/plain");
  10360. });
  10361. },
  10362. [](Client &cli, const string &endpoint,
  10363. DownloadProgress progress_callback) {
  10364. return cli.Get(endpoint, progress_callback);
  10365. },
  10366. "/download", 1000u);
  10367. }
  10368. // Helper function for content receiver download progress tests
  10369. template <typename SetupHandler, typename ClientCall>
  10370. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10371. ClientCall &&client_call,
  10372. const string &endpoint,
  10373. size_t expected_content_size) {
  10374. Server svr;
  10375. setup_handler(svr);
  10376. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10377. auto se = detail::scope_exit([&] {
  10378. svr.stop();
  10379. t.join();
  10380. });
  10381. svr.wait_until_ready();
  10382. Client cli(HOST, PORT);
  10383. vector<uint64_t> progress_values;
  10384. string received_body;
  10385. auto res = client_call(
  10386. cli, endpoint,
  10387. [&](const char *data, size_t data_length) -> bool {
  10388. received_body.append(data, data_length);
  10389. return true;
  10390. },
  10391. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10392. progress_values.push_back(current);
  10393. return true;
  10394. });
  10395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10396. EXPECT_EQ(200, res->status);
  10397. EXPECT_FALSE(progress_values.empty());
  10398. EXPECT_EQ(expected_content_size, received_body.size());
  10399. EXPECT_TRUE(res->body.empty());
  10400. }
  10401. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10402. TestContentReceiverDownloadProgress(
  10403. [](Server &svr) {
  10404. svr.Get("/download-receiver",
  10405. [](const Request & /*req*/, Response &res) {
  10406. string content(2000, 'R');
  10407. res.set_content(content, "text/plain");
  10408. });
  10409. },
  10410. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10411. DownloadProgress progress_callback) {
  10412. return cli.Get(endpoint, content_receiver, progress_callback);
  10413. },
  10414. "/download-receiver", 2000u);
  10415. }
  10416. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10417. // A provider reaching a pass with nothing to hand over - an empty buffer
  10418. // popped off a queue, say - must not be taken to mean the body is finished.
  10419. // It used to end the loop with the terminating chunk unwritten while the
  10420. // server still considered the response complete, so the peer waited for an
  10421. // end that never arrived.
  10422. Server svr;
  10423. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10424. auto step = std::make_shared<int>(0);
  10425. res.set_chunked_content_provider("text/plain",
  10426. [step](size_t /*offset*/, DataSink &sink) {
  10427. switch ((*step)++) {
  10428. case 0: sink.write("", 0); break;
  10429. case 1: sink.write("hello", 5); break;
  10430. default: sink.done(); break;
  10431. }
  10432. return true;
  10433. });
  10434. });
  10435. auto port = svr.bind_to_any_port(HOST);
  10436. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10437. auto listen_se = detail::scope_exit([&] {
  10438. svr.stop();
  10439. listen_thread.join();
  10440. ASSERT_FALSE(svr.is_running());
  10441. });
  10442. svr.wait_until_ready();
  10443. Client cli(HOST, port);
  10444. // Without the fix the body is never terminated, so bound the wait rather
  10445. // than letting the test hang on the default read timeout.
  10446. cli.set_read_timeout(5, 0);
  10447. auto res = cli.Get("/stream");
  10448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10449. EXPECT_EQ(StatusCode::OK_200, res->status);
  10450. EXPECT_EQ("hello", res->body);
  10451. }
  10452. TEST(StreamingTest, NoContentLengthStreaming) {
  10453. Server svr;
  10454. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10455. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10456. if (offset < 6) {
  10457. sink.os << (offset < 3 ? "a" : "b");
  10458. } else {
  10459. sink.done();
  10460. }
  10461. return true;
  10462. });
  10463. });
  10464. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10465. auto listen_se = detail::scope_exit([&] {
  10466. svr.stop();
  10467. listen_thread.join();
  10468. ASSERT_FALSE(svr.is_running());
  10469. });
  10470. svr.wait_until_ready();
  10471. Client client(HOST, PORT);
  10472. auto get_thread = std::thread([&client]() {
  10473. std::string s;
  10474. auto res =
  10475. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10476. s += std::string(data, len);
  10477. return true;
  10478. });
  10479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10480. EXPECT_EQ(StatusCode::OK_200, res->status);
  10481. EXPECT_EQ("aaabbb", s);
  10482. });
  10483. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10484. // Give GET time to get a few messages.
  10485. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10486. }
  10487. TEST(MountTest, Unmount) {
  10488. Server svr;
  10489. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10490. auto se = detail::scope_exit([&] {
  10491. svr.stop();
  10492. listen_thread.join();
  10493. ASSERT_FALSE(svr.is_running());
  10494. });
  10495. svr.wait_until_ready();
  10496. Client cli("localhost", PORT);
  10497. svr.set_mount_point("/mount2", "./www2");
  10498. auto res = cli.Get("/");
  10499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10500. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10501. res = cli.Get("/mount2/dir/test.html");
  10502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10503. EXPECT_EQ(StatusCode::OK_200, res->status);
  10504. svr.set_mount_point("/", "./www");
  10505. res = cli.Get("/dir/");
  10506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10507. EXPECT_EQ(StatusCode::OK_200, res->status);
  10508. svr.remove_mount_point("/");
  10509. res = cli.Get("/dir/");
  10510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10511. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10512. svr.remove_mount_point("/mount2");
  10513. res = cli.Get("/mount2/dir/test.html");
  10514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10515. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10516. }
  10517. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10518. Server svr;
  10519. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10520. svr.Get("/api/hello", [](const Request &, Response &res) {
  10521. res.set_content("api", "text/plain");
  10522. });
  10523. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10524. auto se = detail::scope_exit([&] {
  10525. svr.stop();
  10526. listen_thread.join();
  10527. ASSERT_FALSE(svr.is_running());
  10528. });
  10529. svr.wait_until_ready();
  10530. Client cli(HOST, PORT);
  10531. auto res = cli.Get("/dir/test.html");
  10532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10533. EXPECT_EQ(StatusCode::OK_200, res->status);
  10534. res = cli.Get("/api/hello");
  10535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10536. EXPECT_EQ(StatusCode::OK_200, res->status);
  10537. EXPECT_EQ("api", res->body);
  10538. }
  10539. TEST(MountTest, PathSegmentBoundary) {
  10540. Server svr;
  10541. svr.set_mount_point("/mount2", "./www2");
  10542. svr.set_mount_point("/", "./www");
  10543. auto port = svr.bind_to_any_port(HOST);
  10544. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10545. auto se = detail::scope_exit([&] {
  10546. svr.stop();
  10547. listen_thread.join();
  10548. ASSERT_FALSE(svr.is_running());
  10549. });
  10550. svr.wait_until_ready();
  10551. Client cli(HOST, port);
  10552. auto res = cli.Get("/mount2/dir/test.html");
  10553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10554. EXPECT_EQ(StatusCode::OK_200, res->status);
  10555. // "/mount2" must not match part-way through a path segment.
  10556. res = cli.Get("/mount2dir/test.html");
  10557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10558. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10559. // A mount point ending in '/' keeps matching every path below it.
  10560. res = cli.Get("/dir/test.html");
  10561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10562. EXPECT_EQ(StatusCode::OK_200, res->status);
  10563. }
  10564. TEST(MountTest, Redicect) {
  10565. Server svr;
  10566. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10567. auto se = detail::scope_exit([&] {
  10568. svr.stop();
  10569. listen_thread.join();
  10570. ASSERT_FALSE(svr.is_running());
  10571. });
  10572. svr.set_mount_point("/", "./www");
  10573. svr.wait_until_ready();
  10574. Client cli("localhost", PORT);
  10575. auto res = cli.Get("/dir/");
  10576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10577. EXPECT_EQ(StatusCode::OK_200, res->status);
  10578. res = cli.Get("/dir");
  10579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10580. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10581. res = cli.Get("/file");
  10582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10583. EXPECT_EQ(StatusCode::OK_200, res->status);
  10584. res = cli.Get("/file/");
  10585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10586. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10587. cli.set_follow_location(true);
  10588. res = cli.Get("/dir");
  10589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10590. EXPECT_EQ(StatusCode::OK_200, res->status);
  10591. }
  10592. TEST(MountTest, MultibytesPathName) {
  10593. Server svr;
  10594. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10595. auto se = detail::scope_exit([&] {
  10596. svr.stop();
  10597. listen_thread.join();
  10598. ASSERT_FALSE(svr.is_running());
  10599. });
  10600. svr.set_mount_point("/", "./www");
  10601. svr.wait_until_ready();
  10602. Client cli("localhost", PORT);
  10603. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10605. EXPECT_EQ(StatusCode::OK_200, res->status);
  10606. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10607. }
  10608. #ifdef _WIN32
  10609. // Issue #2435: mmap::open() must succeed even when another handle holds
  10610. // the file open for writing (e.g. an active log file).
  10611. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10612. const char *path = "mmap_concurrent_writer_test.txt";
  10613. const char *content = "hello";
  10614. {
  10615. std::ofstream f(path, std::ios::binary);
  10616. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10617. }
  10618. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10619. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10620. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10621. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10622. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10623. detail::mmap m(path);
  10624. ASSERT_TRUE(m.is_open());
  10625. EXPECT_EQ(strlen(content), m.size());
  10626. char buf[8];
  10627. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10628. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10629. }
  10630. #endif
  10631. #ifndef _WIN32
  10632. // A directory or a device has no size to serve.
  10633. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10634. const char *path = "./mmap_not_regular_test_dir";
  10635. ASSERT_EQ(0, ::mkdir(path, 0755));
  10636. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10637. for (auto p : {path, "/dev/null"}) {
  10638. detail::mmap m(p);
  10639. EXPECT_FALSE(m.is_open()) << p;
  10640. EXPECT_EQ(0U, m.size()) << p;
  10641. }
  10642. Server svr;
  10643. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10644. res.set_file_content("/dev/null");
  10645. });
  10646. auto port = svr.bind_to_any_port(HOST);
  10647. thread t = thread([&] { svr.listen_after_bind(); });
  10648. auto se = detail::scope_exit([&] {
  10649. svr.stop();
  10650. t.join();
  10651. });
  10652. svr.wait_until_ready();
  10653. auto res = Client(HOST, port).Get("/null");
  10654. ASSERT_TRUE(res);
  10655. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10656. }
  10657. #endif
  10658. #ifdef __linux__
  10659. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10660. TEST(MmapTest, FileIsNotMapped) {
  10661. const char *path = "mmap_not_mapped_test.txt";
  10662. {
  10663. std::ofstream f(path, std::ios::binary);
  10664. f << "hello";
  10665. }
  10666. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10667. detail::mmap m(path);
  10668. ASSERT_TRUE(m.is_open());
  10669. std::ifstream maps("/proc/self/maps");
  10670. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10671. std::istreambuf_iterator<char>());
  10672. EXPECT_EQ(std::string::npos, mappings.find(path));
  10673. }
  10674. #endif
  10675. TEST(KeepAliveTest, ReadTimeout) {
  10676. Server svr;
  10677. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10678. std::this_thread::sleep_for(std::chrono::seconds(2));
  10679. res.set_content("a", "text/plain");
  10680. });
  10681. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10682. res.set_content("b", "text/plain");
  10683. });
  10684. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10685. auto se = detail::scope_exit([&] {
  10686. svr.stop();
  10687. listen_thread.join();
  10688. ASSERT_FALSE(svr.is_running());
  10689. });
  10690. svr.wait_until_ready();
  10691. Client cli("localhost", PORT);
  10692. cli.set_keep_alive(true);
  10693. cli.set_read_timeout(std::chrono::seconds(1));
  10694. auto resa = cli.Get("/a");
  10695. ASSERT_FALSE(resa);
  10696. EXPECT_EQ(Error::Read, resa.error());
  10697. auto resb = cli.Get("/b");
  10698. ASSERT_TRUE(resb);
  10699. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10700. EXPECT_EQ("b", resb->body);
  10701. }
  10702. TEST(KeepAliveTest, MaxCount) {
  10703. size_t keep_alive_max_count = 3;
  10704. Server svr;
  10705. svr.set_keep_alive_max_count(keep_alive_max_count);
  10706. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10707. res.set_content("Hello World!", "text/plain");
  10708. });
  10709. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10710. auto se = detail::scope_exit([&] {
  10711. svr.stop();
  10712. listen_thread.join();
  10713. ASSERT_FALSE(svr.is_running());
  10714. });
  10715. svr.wait_until_ready();
  10716. Client cli(HOST, PORT);
  10717. cli.set_keep_alive(true);
  10718. for (size_t i = 0; i < 5; i++) {
  10719. auto result = cli.Get("/hi");
  10720. ASSERT_TRUE(result);
  10721. EXPECT_EQ(StatusCode::OK_200, result->status);
  10722. if (i == keep_alive_max_count - 1) {
  10723. EXPECT_EQ("close", result->get_header_value("Connection"));
  10724. } else {
  10725. EXPECT_FALSE(result->has_header("Connection"));
  10726. }
  10727. }
  10728. }
  10729. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10730. // can pull the next one into the server's buffer. The server must serve it
  10731. // without waiting for the socket to become readable again. The keep-alive
  10732. // timeout outlasts the client's read timeout, so a request left waiting for it
  10733. // shows up as a missing response.
  10734. static void serve_pipelining_routes(Server &svr,
  10735. const std::function<void(int)> &client) {
  10736. svr.set_keep_alive_timeout(5);
  10737. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10738. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10739. });
  10740. svr.Post("/echo", [](const Request &req, Response &res) {
  10741. res.set_content("echo " + req.body, "text/plain");
  10742. });
  10743. auto port = svr.bind_to_any_port(HOST);
  10744. thread t = thread([&] { svr.listen_after_bind(); });
  10745. auto se = detail::scope_exit([&] {
  10746. svr.stop();
  10747. t.join();
  10748. });
  10749. svr.wait_until_ready();
  10750. client(port);
  10751. }
  10752. static std::string
  10753. send_pipelined_requests(const std::vector<std::string> &parts) {
  10754. Server svr;
  10755. std::string res;
  10756. serve_pipelining_routes(svr, [&](int port) {
  10757. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10758. });
  10759. return res;
  10760. }
  10761. static void expect_in_order(const std::string &res,
  10762. const std::vector<std::string> &bodies) {
  10763. size_t pos = 0;
  10764. for (const auto &body : bodies) {
  10765. pos = res.find(body, pos);
  10766. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10767. pos += body.size();
  10768. }
  10769. }
  10770. TEST(KeepAliveTest, PipelinedRequests) {
  10771. auto res = send_pipelined_requests(
  10772. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10773. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10774. "Content-Length: 4\r\n\r\nbody"
  10775. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10776. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10777. }
  10778. // The second request starts in the server's buffer and ends on the socket.
  10779. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10780. auto res =
  10781. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10782. "GET /hi/2 HTTP/1.1\r\nHo",
  10783. "st: localhost\r\nConnection: close\r\n\r\n"});
  10784. expect_in_order(res, {"hi 1", "hi 2"});
  10785. }
  10786. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10787. // CRLF after a body does not turn into a 400 for the next request.
  10788. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10789. auto res = send_pipelined_requests(
  10790. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10791. "Content-Length: 4\r\n\r\nbody\r\n"
  10792. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10793. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10794. expect_in_order(res, {"echo body", "hi 2"});
  10795. }
  10796. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10797. // must not be served as the next request.
  10798. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10799. auto res = send_pipelined_requests(
  10800. {"INVALID REQUEST LINE\r\n\r\n"
  10801. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10802. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10803. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10804. }
  10805. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10806. // Over TLS, the next request is held by the TLS library as already decrypted
  10807. // data rather than on the socket.
  10808. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10809. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10810. std::string res;
  10811. serve_pipelining_routes(svr, [&](int port) {
  10812. // One part, so all three requests arrive in one TLS record
  10813. EXPECT_TRUE(send_ssl_request_in_parts(
  10814. 2,
  10815. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10816. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10817. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10818. &res, port));
  10819. });
  10820. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10821. }
  10822. #endif
  10823. TEST(KeepAliveTest, Issue1041) {
  10824. Server svr;
  10825. svr.set_keep_alive_timeout(3);
  10826. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10827. res.set_content("Hello World!", "text/plain");
  10828. });
  10829. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10830. auto se = detail::scope_exit([&] {
  10831. svr.stop();
  10832. listen_thread.join();
  10833. ASSERT_FALSE(svr.is_running());
  10834. });
  10835. svr.wait_until_ready();
  10836. Client cli(HOST, PORT);
  10837. cli.set_keep_alive(true);
  10838. auto result = cli.Get("/hi");
  10839. ASSERT_TRUE(result);
  10840. EXPECT_EQ(StatusCode::OK_200, result->status);
  10841. std::this_thread::sleep_for(std::chrono::seconds(5));
  10842. result = cli.Get("/hi");
  10843. ASSERT_TRUE(result);
  10844. EXPECT_EQ(StatusCode::OK_200, result->status);
  10845. }
  10846. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10847. Server svr;
  10848. svr.set_keep_alive_max_count(0);
  10849. std::set<int> remote_ports;
  10850. svr.Get("/hi", [&](const Request &req, Response &res) {
  10851. remote_ports.insert(req.remote_port);
  10852. res.set_content("hi", "text/plain");
  10853. });
  10854. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10855. auto se = detail::scope_exit([&] {
  10856. svr.stop();
  10857. listen_thread.join();
  10858. ASSERT_FALSE(svr.is_running());
  10859. });
  10860. svr.wait_until_ready();
  10861. Client cli(HOST, PORT);
  10862. cli.set_keep_alive(true);
  10863. for (int i = 0; i < 3; i++) {
  10864. auto res = cli.Get("/hi");
  10865. ASSERT_TRUE(res);
  10866. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  10867. }
  10868. // All three over one connection
  10869. EXPECT_EQ(1u, remote_ports.size());
  10870. }
  10871. TEST(KeepAliveTest, Issue1959) {
  10872. Server svr;
  10873. svr.set_keep_alive_timeout(5);
  10874. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10875. res.set_content("a", "text/plain");
  10876. });
  10877. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10878. auto se = detail::scope_exit([&] {
  10879. if (!svr.is_running()) return;
  10880. svr.stop();
  10881. listen_thread.join();
  10882. ASSERT_FALSE(svr.is_running());
  10883. });
  10884. svr.wait_until_ready();
  10885. Client cli("localhost", PORT);
  10886. cli.set_keep_alive(true);
  10887. using namespace std::chrono;
  10888. auto start = steady_clock::now();
  10889. cli.Get("/a");
  10890. svr.stop();
  10891. listen_thread.join();
  10892. auto end = steady_clock::now();
  10893. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10894. EXPECT_LT(elapsed, 5000);
  10895. }
  10896. #ifdef CPPHTTPLIB_SSL_ENABLED
  10897. TEST(KeepAliveTest, SSLClientReconnection) {
  10898. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10899. ASSERT_TRUE(svr.is_valid());
  10900. svr.set_keep_alive_timeout(1);
  10901. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10902. res.set_content("Hello World!", "text/plain");
  10903. });
  10904. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10905. auto se = detail::scope_exit([&] {
  10906. svr.stop();
  10907. listen_thread.join();
  10908. ASSERT_FALSE(svr.is_running());
  10909. });
  10910. svr.wait_until_ready();
  10911. SSLClient cli(HOST, PORT);
  10912. cli.enable_server_certificate_verification(false);
  10913. cli.set_keep_alive(true);
  10914. auto result = cli.Get("/hi");
  10915. ASSERT_TRUE(result);
  10916. EXPECT_EQ(StatusCode::OK_200, result->status);
  10917. result = cli.Get("/hi");
  10918. ASSERT_TRUE(result);
  10919. EXPECT_EQ(StatusCode::OK_200, result->status);
  10920. std::this_thread::sleep_for(std::chrono::seconds(2));
  10921. // Recoonect
  10922. result = cli.Get("/hi");
  10923. ASSERT_TRUE(result);
  10924. EXPECT_EQ(StatusCode::OK_200, result->status);
  10925. result = cli.Get("/hi");
  10926. ASSERT_TRUE(result);
  10927. EXPECT_EQ(StatusCode::OK_200, result->status);
  10928. }
  10929. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10930. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10931. ASSERT_TRUE(svr.is_valid());
  10932. svr.set_keep_alive_timeout(1);
  10933. std::string content = "reconnect";
  10934. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10935. res.set_content("Hello World!", "text/plain");
  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. SSLClient cli(HOST, PORT);
  10945. cli.enable_server_certificate_verification(false);
  10946. cli.set_keep_alive(true);
  10947. auto result = cli.Post(
  10948. "/hi", content.size(),
  10949. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10950. sink.write(content.c_str(), content.size());
  10951. return true;
  10952. },
  10953. "text/plain");
  10954. ASSERT_TRUE(result);
  10955. EXPECT_EQ(200, result->status);
  10956. std::this_thread::sleep_for(std::chrono::seconds(2));
  10957. // Recoonect
  10958. result = cli.Post(
  10959. "/hi", content.size(),
  10960. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10961. sink.write(content.c_str(), content.size());
  10962. return true;
  10963. },
  10964. "text/plain");
  10965. ASSERT_TRUE(result);
  10966. EXPECT_EQ(200, result->status);
  10967. result = cli.Post(
  10968. "/hi", content.size(),
  10969. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10970. sink.write(content.c_str(), content.size());
  10971. return true;
  10972. },
  10973. "text/plain");
  10974. ASSERT_TRUE(result);
  10975. EXPECT_EQ(200, result->status);
  10976. }
  10977. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10978. using namespace httplib::tls;
  10979. {
  10980. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10981. ASSERT_TRUE(svr.is_valid());
  10982. svr.Get("/sni", [&](const Request &req, Response &res) {
  10983. std::string expected = req.sni();
  10984. EXPECT_EQ(expected, req.get_param_value("expected"));
  10985. res.set_content("ok", "text/plain");
  10986. });
  10987. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10988. auto se = detail::scope_exit([&] {
  10989. svr.stop();
  10990. listen_thread.join();
  10991. ASSERT_FALSE(svr.is_running());
  10992. });
  10993. svr.wait_until_ready();
  10994. {
  10995. SSLClient cli("localhost", PORT);
  10996. cli.enable_server_certificate_verification(false);
  10997. auto res = cli.Get("/sni?expected=localhost");
  10998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10999. }
  11000. {
  11001. SSLClient cli("::1", PORT);
  11002. cli.enable_server_certificate_verification(false);
  11003. auto res = cli.Get("/sni?expected=");
  11004. // NOTE: This may fail if the server is listening on IPv4 only
  11005. // (e.g., when localhost resolves to 127.0.0.1 only)
  11006. if (res) {
  11007. EXPECT_EQ(StatusCode::OK_200, res->status);
  11008. } else {
  11009. EXPECT_EQ(Error::Connection, res.error());
  11010. }
  11011. }
  11012. }
  11013. }
  11014. #endif
  11015. TEST(ClientProblemDetectionTest, ContentProvider) {
  11016. Server svr;
  11017. size_t content_length = 1024 * 1024;
  11018. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11019. res.set_content_provider(
  11020. content_length, "text/plain",
  11021. [&](size_t offset, size_t length, DataSink &sink) {
  11022. auto out_len = std::min(length, static_cast<size_t>(1024));
  11023. std::string out(out_len, '@');
  11024. sink.write(out.data(), out_len);
  11025. return offset < 4096;
  11026. },
  11027. [](bool success) { ASSERT_FALSE(success); });
  11028. });
  11029. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11030. res.set_content_provider(
  11031. 0, "text/plain",
  11032. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11033. EXPECT_TRUE(false);
  11034. return true;
  11035. },
  11036. [](bool success) { ASSERT_FALSE(success); });
  11037. });
  11038. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11039. auto se = detail::scope_exit([&] {
  11040. svr.stop();
  11041. listen_thread.join();
  11042. ASSERT_FALSE(svr.is_running());
  11043. });
  11044. svr.wait_until_ready();
  11045. Client cli("localhost", PORT);
  11046. {
  11047. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11048. size_t /*data_length*/) { return false; });
  11049. ASSERT_FALSE(res);
  11050. }
  11051. {
  11052. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11053. size_t /*data_length*/) { return false; });
  11054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11055. }
  11056. }
  11057. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11058. // A provider that reports success without writing anything and without
  11059. // calling done() used to be handed the same offset and length again on every
  11060. // pass, so it spun for as long as the peer stayed connected.
  11061. Server svr;
  11062. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11063. res.set_content("ok", "text/plain");
  11064. });
  11065. auto port = svr.bind_to_any_port(HOST);
  11066. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11067. auto se = detail::scope_exit([&] {
  11068. svr.stop();
  11069. listen_thread.join();
  11070. ASSERT_FALSE(svr.is_running());
  11071. });
  11072. svr.wait_until_ready();
  11073. std::atomic<int> call_count{0};
  11074. Client cli(HOST, port);
  11075. auto res = cli.Post(
  11076. "/", 1024,
  11077. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11078. // Give up after enough passes to show the spin, so that losing the
  11079. // check below fails this test instead of hanging it.
  11080. return ++call_count < 100;
  11081. },
  11082. "text/plain");
  11083. ASSERT_FALSE(res);
  11084. EXPECT_EQ(Error::Write, res.error());
  11085. EXPECT_EQ(1, call_count.load());
  11086. }
  11087. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11088. // A writer only has to assign `write`. The other three used to be left as
  11089. // empty std::functions, so a provider calling one threw
  11090. // std::bad_function_call out of the thread running it and took the whole
  11091. // process down.
  11092. DataSink sink;
  11093. std::string written;
  11094. sink.write = [&](const char *data, size_t data_len) {
  11095. written.append(data, data_len);
  11096. return true;
  11097. };
  11098. EXPECT_TRUE(sink.is_writable());
  11099. sink.done();
  11100. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11101. EXPECT_TRUE(written.empty());
  11102. }
  11103. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11104. // A sink that cannot carry trailers still has to finish.
  11105. DataSink sink;
  11106. auto done_count = 0;
  11107. sink.done = [&]() { done_count++; };
  11108. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11109. EXPECT_EQ(1, done_count);
  11110. }
  11111. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11112. Server svr;
  11113. const std::string body(4096, 'x');
  11114. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11115. res.set_content_provider(body.size(), "text/plain",
  11116. [&](size_t offset, size_t length, DataSink &sink) {
  11117. sink.write(body.data() + offset, length);
  11118. sink.done();
  11119. return true;
  11120. });
  11121. });
  11122. auto port = svr.bind_to_any_port(HOST);
  11123. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11124. auto se = detail::scope_exit([&] {
  11125. svr.stop();
  11126. listen_thread.join();
  11127. ASSERT_FALSE(svr.is_running());
  11128. });
  11129. svr.wait_until_ready();
  11130. Client cli(HOST, port);
  11131. auto res = cli.Get("/");
  11132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11133. EXPECT_EQ(StatusCode::OK_200, res->status);
  11134. EXPECT_EQ(body, res->body);
  11135. }
  11136. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11137. Server svr;
  11138. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11139. res.set_content_provider(
  11140. 1024, "text/plain",
  11141. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11142. sink.write("hello", 5);
  11143. sink.done(); // short of the 1024 bytes the response promised
  11144. return true;
  11145. });
  11146. });
  11147. auto port = svr.bind_to_any_port(HOST);
  11148. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11149. auto se = detail::scope_exit([&] {
  11150. svr.stop();
  11151. listen_thread.join();
  11152. ASSERT_FALSE(svr.is_running());
  11153. });
  11154. svr.wait_until_ready();
  11155. Client cli(HOST, port);
  11156. cli.set_read_timeout(5, 0);
  11157. // The response is short of its Content-Length, so the client cannot read a
  11158. // complete body. What matters is that this returns at all: a no-op done()
  11159. // would leave the writer looping over a provider that never makes progress.
  11160. auto res = cli.Get("/");
  11161. EXPECT_FALSE(res);
  11162. }
  11163. // Read as the next response by a peer that sees it after a framed body.
  11164. static const std::string smuggled_response =
  11165. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11166. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11167. Server svr;
  11168. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11169. res.set_content_provider(
  11170. 5, "text/plain",
  11171. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11172. auto data = "AAAAA" + smuggled_response;
  11173. sink.write(data.data(), data.size());
  11174. return true;
  11175. });
  11176. });
  11177. thread t = thread([&] { svr.listen(HOST, PORT); });
  11178. auto se = detail::scope_exit([&] {
  11179. svr.stop();
  11180. t.join();
  11181. ASSERT_FALSE(svr.is_running());
  11182. });
  11183. svr.wait_until_ready();
  11184. std::string resp;
  11185. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11186. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11187. resp.clear();
  11188. ASSERT_TRUE(send_request(
  11189. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11190. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11191. }
  11192. TEST(NoContentTest, BodyIsNotSent) {
  11193. Server svr;
  11194. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11195. res.status = StatusCode::NoContent_204;
  11196. res.set_content(smuggled_response, "text/plain");
  11197. });
  11198. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11199. res.status = StatusCode::NotModified_304;
  11200. res.set_chunked_content_provider(
  11201. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11202. sink.write(smuggled_response.data(), smuggled_response.size());
  11203. sink.done();
  11204. return true;
  11205. });
  11206. });
  11207. thread t = thread([&] { svr.listen(HOST, PORT); });
  11208. auto se = detail::scope_exit([&] {
  11209. svr.stop();
  11210. t.join();
  11211. ASSERT_FALSE(svr.is_running());
  11212. });
  11213. svr.wait_until_ready();
  11214. for (auto path : {"/204", "/304"}) {
  11215. std::string resp;
  11216. ASSERT_TRUE(send_request(
  11217. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11218. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11219. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11220. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11221. }
  11222. }
  11223. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11224. Server svr;
  11225. std::atomic<bool> smuggled(false);
  11226. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11227. res.set_content("ok", "text/plain");
  11228. });
  11229. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11230. smuggled = true;
  11231. });
  11232. auto port = svr.bind_to_any_port(HOST);
  11233. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11234. auto se = detail::scope_exit([&] {
  11235. svr.stop();
  11236. listen_thread.join();
  11237. ASSERT_FALSE(svr.is_running());
  11238. });
  11239. svr.wait_until_ready();
  11240. // What follows the body would be read as the next request.
  11241. Client cli(HOST, port);
  11242. auto res = cli.Post(
  11243. "/", 5,
  11244. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11245. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11246. sink.write(data.data(), data.size());
  11247. return true;
  11248. },
  11249. "text/plain");
  11250. ASSERT_FALSE(res);
  11251. EXPECT_EQ(Error::Write, res.error());
  11252. EXPECT_FALSE(smuggled);
  11253. }
  11254. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11255. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11256. // The compressed path builds the whole body before connecting, so this
  11257. // fails client-side and never reaches a server.
  11258. Client cli(HOST, PORT);
  11259. cli.set_compress(true);
  11260. auto res = cli.Post(
  11261. "/", 1024,
  11262. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11263. sink.write("hello", 5);
  11264. sink.done(); // short of the 1024 bytes the request announced
  11265. return true;
  11266. },
  11267. "text/plain");
  11268. ASSERT_FALSE(res);
  11269. EXPECT_EQ(Error::Write, res.error());
  11270. }
  11271. #endif
  11272. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11273. Server svr;
  11274. svr.set_error_handler([](Request const &, Response &res) -> void {
  11275. res.set_chunked_content_provider(
  11276. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11277. sink.os << "hello";
  11278. sink.os << "world";
  11279. sink.done();
  11280. return true;
  11281. });
  11282. });
  11283. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11284. auto se = detail::scope_exit([&] {
  11285. svr.stop();
  11286. listen_thread.join();
  11287. ASSERT_FALSE(svr.is_running());
  11288. });
  11289. svr.wait_until_ready();
  11290. Client cli("localhost", PORT);
  11291. auto res = cli.Get("/");
  11292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11293. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11294. EXPECT_EQ("helloworld", res->body);
  11295. }
  11296. // A body set after a content provider must replace it, not be sent through it.
  11297. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11298. Server svr;
  11299. svr.set_mount_point("/", "./www");
  11300. svr.set_file_request_handler([](const Request &req, Response &res) {
  11301. if (req.path == "/dir/test.html") {
  11302. res.status = StatusCode::Forbidden_403;
  11303. res.set_content(std::string(5000, 'D'), "text/plain");
  11304. } else if (req.path == "/file") {
  11305. res.status = StatusCode::Forbidden_403;
  11306. res.body = "Denied";
  11307. }
  11308. });
  11309. auto port = svr.bind_to_any_port(HOST);
  11310. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11311. auto se = detail::scope_exit([&] {
  11312. svr.stop();
  11313. t.join();
  11314. ASSERT_FALSE(svr.is_running());
  11315. });
  11316. svr.wait_until_ready();
  11317. Client cli(HOST, port);
  11318. {
  11319. auto res = cli.Get("/dir/test.html");
  11320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11321. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11322. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11323. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11324. }
  11325. {
  11326. auto res = cli.Get("/file");
  11327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11328. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11329. EXPECT_EQ("Denied", res->body);
  11330. }
  11331. {
  11332. auto res = cli.Get("/dir/index.html");
  11333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11334. EXPECT_EQ(StatusCode::OK_200, res->status);
  11335. EXPECT_EQ(0U, res->body.find("<html>"));
  11336. }
  11337. }
  11338. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11339. Server svr;
  11340. std::vector<bool> released;
  11341. std::mutex released_mutex;
  11342. auto releaser = [&](bool success) {
  11343. std::lock_guard<std::mutex> guard(released_mutex);
  11344. released.push_back(success);
  11345. };
  11346. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11347. return sink.write(&"hello"[offset], length);
  11348. };
  11349. svr.Get("/sized", [&](const Request &, Response &res) {
  11350. res.status = StatusCode::NotFound_404;
  11351. res.set_content_provider(5, "text/plain", provider, releaser);
  11352. });
  11353. svr.Get("/chunked", [&](const Request &, Response &res) {
  11354. res.status = StatusCode::ServiceUnavailable_503;
  11355. res.set_chunked_content_provider(
  11356. "text/plain",
  11357. [](size_t, DataSink &sink) {
  11358. sink.os << "chunk";
  11359. sink.done();
  11360. return true;
  11361. },
  11362. releaser);
  11363. });
  11364. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11365. res.set_content_provider(5, "text/plain", provider, releaser);
  11366. throw std::runtime_error("after the provider");
  11367. });
  11368. svr.set_error_handler([](const Request &req, Response &res) {
  11369. // Leave the exception handler's content to it.
  11370. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11371. res.set_content(std::string(1000, 'E'), "text/html");
  11372. return Server::HandlerResponse::Handled;
  11373. });
  11374. svr.set_exception_handler(
  11375. [](const Request &, Response &res, std::exception_ptr) {
  11376. res.status = StatusCode::InternalServerError_500;
  11377. res.set_content(std::string(1000, 'X'), "text/html");
  11378. });
  11379. auto port = svr.bind_to_any_port(HOST);
  11380. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11381. auto se = detail::scope_exit([&] {
  11382. svr.stop();
  11383. t.join();
  11384. ASSERT_FALSE(svr.is_running());
  11385. });
  11386. svr.wait_until_ready();
  11387. Client cli(HOST, port);
  11388. {
  11389. auto res = cli.Get("/sized");
  11390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11391. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11392. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11393. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11394. }
  11395. {
  11396. auto res = cli.Get("/chunked");
  11397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11398. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11399. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11400. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11401. }
  11402. {
  11403. auto res = cli.Get("/throw");
  11404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11405. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11406. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11407. }
  11408. std::lock_guard<std::mutex> guard(released_mutex);
  11409. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11410. }
  11411. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11412. Server svr;
  11413. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11414. return sink.write(&"abc"[offset], length);
  11415. };
  11416. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11417. res.set_file_content("./www/dir/test.html");
  11418. res.set_content("body", "text/plain");
  11419. });
  11420. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11421. res.set_content(std::string(100, 'B'), "text/plain");
  11422. res.set_file_content("./www/dir/test.html");
  11423. });
  11424. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11425. res.set_content(std::string(100, 'B'), "text/plain");
  11426. res.set_content_provider(3, "text/x-provider", abc);
  11427. });
  11428. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11429. res.set_content_provider(3, "text/x-provider", abc);
  11430. res.set_content(std::string(100, 'B'), "text/plain");
  11431. });
  11432. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11433. res.set_content_provider(3, "text/x-provider", abc);
  11434. res.set_file_content("./www/dir/test.html", "text/x-file");
  11435. });
  11436. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11437. res.set_file_content("./www/dir/test.html");
  11438. res.set_header("Content-Type", "text/x-handler");
  11439. });
  11440. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11441. res.set_content_provider(3, "text/plain", abc);
  11442. res.body = "direct";
  11443. });
  11444. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11445. res.set_file_content("./www/dir/test.html");
  11446. res.body = "direct";
  11447. });
  11448. auto port = svr.bind_to_any_port(HOST);
  11449. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11450. auto se = detail::scope_exit([&] {
  11451. svr.stop();
  11452. t.join();
  11453. ASSERT_FALSE(svr.is_running());
  11454. });
  11455. svr.wait_until_ready();
  11456. Client cli(HOST, port);
  11457. auto expect_body = [&](const char *path, const std::string &body,
  11458. const std::string &type) {
  11459. // Uncompressed, so Content-Length can be compared with the body.
  11460. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11461. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11462. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11463. EXPECT_EQ(body, res->body) << path;
  11464. EXPECT_EQ(std::to_string(body.size()),
  11465. res->get_header_value("Content-Length"))
  11466. << path;
  11467. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11468. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11469. };
  11470. expect_body("/file-then-body", "body", "text/plain");
  11471. expect_body("/body-then-file", "test.html", "text/html");
  11472. expect_body("/body-then-provider", "abc", "text/x-provider");
  11473. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11474. expect_body("/provider-then-file", "test.html", "text/x-file");
  11475. expect_body("/file-then-header", "test.html", "text/x-handler");
  11476. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11477. expect_body("/file-then-direct-body", "direct", "text/plain");
  11478. // Ranges are checked against the body, not the dropped provider.
  11479. {
  11480. auto res = cli.Get("/provider-then-direct-body",
  11481. Headers{{make_range_header({{1, 2}})}});
  11482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11483. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11484. EXPECT_EQ("ir", res->body);
  11485. }
  11486. {
  11487. auto res = cli.Get("/file-then-direct-body",
  11488. Headers{{make_range_header({{7, 8}})}});
  11489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11490. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11491. }
  11492. }
  11493. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11494. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11495. const char *path = "./truncated_while_served.txt";
  11496. const size_t size = 32 * 1024 * 1024;
  11497. {
  11498. std::ofstream f(path, std::ios::binary);
  11499. f << std::string(size, 'x');
  11500. }
  11501. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11502. // Over TLS, where the bytes are encrypted in this process rather than
  11503. // copied by send().
  11504. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11505. svr.Get("/file", [&](const Request &, Response &res) {
  11506. res.set_file_content(path, "text/plain");
  11507. });
  11508. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11509. auto se = detail::scope_exit([&] {
  11510. svr.stop();
  11511. thread.join();
  11512. ASSERT_FALSE(svr.is_running());
  11513. });
  11514. svr.wait_until_ready();
  11515. // The file shrinks once the first bytes are in, as a rewrite in place
  11516. // would, and reading the mapping past its new end used to raise SIGBUS.
  11517. SSLClient cli(HOST, PORT);
  11518. cli.enable_server_certificate_verification(false);
  11519. size_t received = 0;
  11520. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11521. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11522. received += len;
  11523. return true;
  11524. });
  11525. EXPECT_FALSE(res);
  11526. EXPECT_LT(received, size);
  11527. }
  11528. #endif
  11529. // Forward declaration (see the base64_encode note).
  11530. namespace httplib {
  11531. namespace detail {
  11532. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11533. const std::string &content_type,
  11534. EncodingType encoding);
  11535. } // namespace detail
  11536. } // namespace httplib
  11537. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11538. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11539. ASSERT_TRUE(mm->is_open());
  11540. Response res;
  11541. detail::set_file_content_provider(res, mm, "text/html",
  11542. detail::EncodingType::None);
  11543. std::string out;
  11544. DataSink sink;
  11545. sink.write = [&](const char *d, size_t l) {
  11546. out.append(d, l);
  11547. return true;
  11548. };
  11549. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11550. EXPECT_EQ("test.html", out);
  11551. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11552. EXPECT_EQ("test.html", out);
  11553. }
  11554. TEST(LongPollingTest, ClientCloseDetection) {
  11555. Server svr;
  11556. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11557. res.set_chunked_content_provider(
  11558. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11559. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11560. sink.os << "hello";
  11561. auto count = 10;
  11562. while (count > 0 && sink.is_writable()) {
  11563. this_thread::sleep_for(chrono::milliseconds(10));
  11564. count--;
  11565. }
  11566. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11567. return true;
  11568. });
  11569. });
  11570. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11571. auto se = detail::scope_exit([&] {
  11572. svr.stop();
  11573. listen_thread.join();
  11574. ASSERT_FALSE(svr.is_running());
  11575. });
  11576. svr.wait_until_ready();
  11577. Client cli("localhost", PORT);
  11578. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11579. EXPECT_EQ("hello", string(data, data_length));
  11580. return false; // close the socket immediately.
  11581. });
  11582. ASSERT_FALSE(res);
  11583. }
  11584. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11585. Server svr;
  11586. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11587. res.set_chunked_content_provider(
  11588. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11589. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11590. sink.os << "hello";
  11591. EXPECT_TRUE(sink.os.good());
  11592. // Wait for the client to close the connection
  11593. auto count = 10;
  11594. while (count > 0 && sink.is_writable()) {
  11595. this_thread::sleep_for(chrono::milliseconds(10));
  11596. count--;
  11597. }
  11598. // After client disconnect, write repeatedly until the socket
  11599. // write actually fails (small writes may be absorbed by the
  11600. // kernel buffer)
  11601. std::string chunk(1024, 'x');
  11602. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11603. sink.os << chunk;
  11604. }
  11605. EXPECT_TRUE(sink.os.fail());
  11606. return true;
  11607. });
  11608. });
  11609. auto port = svr.bind_to_any_port("localhost");
  11610. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11611. auto se = detail::scope_exit([&] {
  11612. svr.stop();
  11613. listen_thread.join();
  11614. ASSERT_FALSE(svr.is_running());
  11615. });
  11616. svr.wait_until_ready();
  11617. Client cli("localhost", port);
  11618. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11619. EXPECT_EQ("hello", string(data, data_length));
  11620. return false; // close the socket immediately.
  11621. });
  11622. ASSERT_FALSE(res);
  11623. }
  11624. TEST(GetWithParametersTest, GetWithParameters) {
  11625. Server svr;
  11626. svr.Get("/", [&](const Request &req, Response &) {
  11627. EXPECT_EQ("world", req.get_param_value("hello"));
  11628. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11629. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11630. });
  11631. svr.Get("/params", [&](const Request &req, Response &) {
  11632. EXPECT_EQ("world", req.get_param_value("hello"));
  11633. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11634. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11635. });
  11636. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11637. EXPECT_EQ("resource-id", req.matches[1]);
  11638. EXPECT_EQ("foo", req.get_param_value("param1"));
  11639. EXPECT_EQ("bar", req.get_param_value("param2"));
  11640. });
  11641. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11642. EXPECT_EQ("user-id", req.path_params.at("id"));
  11643. EXPECT_EQ("foo", req.get_param_value("param1"));
  11644. EXPECT_EQ("bar", req.get_param_value("param2"));
  11645. });
  11646. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11647. auto se = detail::scope_exit([&] {
  11648. svr.stop();
  11649. listen_thread.join();
  11650. ASSERT_FALSE(svr.is_running());
  11651. });
  11652. svr.wait_until_ready();
  11653. {
  11654. Client cli(HOST, PORT);
  11655. Params params;
  11656. params.emplace("hello", "world");
  11657. params.emplace("hello2", "world2");
  11658. params.emplace("hello3", "world3");
  11659. auto res = cli.Get("/", params, Headers{});
  11660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11661. EXPECT_EQ(StatusCode::OK_200, res->status);
  11662. }
  11663. {
  11664. Client cli(HOST, PORT);
  11665. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11667. EXPECT_EQ(StatusCode::OK_200, res->status);
  11668. }
  11669. {
  11670. Client cli(HOST, PORT);
  11671. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11673. EXPECT_EQ(StatusCode::OK_200, res->status);
  11674. }
  11675. {
  11676. Client cli(HOST, PORT);
  11677. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11679. EXPECT_EQ(StatusCode::OK_200, res->status);
  11680. }
  11681. }
  11682. TEST(GetWithParametersTest, GetWithParameters2) {
  11683. Server svr;
  11684. svr.Get("/", [&](const Request &req, Response &res) {
  11685. auto text = req.get_param_value("hello");
  11686. res.set_content(text, "text/plain");
  11687. });
  11688. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11689. auto se = detail::scope_exit([&] {
  11690. svr.stop();
  11691. listen_thread.join();
  11692. ASSERT_FALSE(svr.is_running());
  11693. });
  11694. svr.wait_until_ready();
  11695. Client cli("localhost", PORT);
  11696. Params params;
  11697. params.emplace("hello", "world");
  11698. std::string body;
  11699. auto res = cli.Get("/", params, Headers{},
  11700. [&](const char *data, size_t data_length) {
  11701. body.append(data, data_length);
  11702. return true;
  11703. });
  11704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11705. EXPECT_EQ(StatusCode::OK_200, res->status);
  11706. EXPECT_EQ("world", body);
  11707. }
  11708. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11709. Server svr;
  11710. svr.Get("/search", [&](const Request &req, Response &res) {
  11711. auto q = req.get_param_value("q");
  11712. res.set_content(q, "text/plain");
  11713. });
  11714. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11715. auto se = detail::scope_exit([&] {
  11716. svr.stop();
  11717. listen_thread.join();
  11718. ASSERT_FALSE(svr.is_running());
  11719. });
  11720. svr.wait_until_ready();
  11721. Client cli("localhost", PORT);
  11722. // Verify that Get(path, params) works without requiring Headers argument
  11723. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11725. EXPECT_EQ(StatusCode::OK_200, res->status);
  11726. EXPECT_EQ("cpp-httplib", res->body);
  11727. }
  11728. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11729. auto host = "httpbingo.org";
  11730. auto path = std::string{"/range/32"};
  11731. #ifdef CPPHTTPLIB_SSL_ENABLED
  11732. SSLClient cli(host);
  11733. #else
  11734. Client cli(host);
  11735. #endif
  11736. cli.set_default_headers({make_range_header({{1, 10}})});
  11737. cli.set_connection_timeout(5);
  11738. {
  11739. auto res = cli.Get(path);
  11740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11741. EXPECT_EQ("bcdefghijk", res->body);
  11742. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11743. }
  11744. {
  11745. auto res = cli.Get(path);
  11746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11747. EXPECT_EQ("bcdefghijk", res->body);
  11748. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11749. }
  11750. }
  11751. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11752. Server svr;
  11753. svr.set_default_headers({{"Hello", "World"}});
  11754. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11755. res.set_content("ok", "text/plain");
  11756. });
  11757. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11758. auto se = detail::scope_exit([&] {
  11759. svr.stop();
  11760. listen_thread.join();
  11761. ASSERT_FALSE(svr.is_running());
  11762. });
  11763. svr.wait_until_ready();
  11764. Client cli("localhost", PORT);
  11765. auto res = cli.Get("/");
  11766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11767. EXPECT_EQ(StatusCode::OK_200, res->status);
  11768. EXPECT_EQ("ok", res->body);
  11769. EXPECT_EQ("World", res->get_header_value("Hello"));
  11770. }
  11771. #ifdef CPPHTTPLIB_SSL_ENABLED
  11772. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11773. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11774. ASSERT_TRUE(svr.is_valid());
  11775. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11776. std::this_thread::sleep_for(std::chrono::seconds(2));
  11777. res.set_content("a", "text/plain");
  11778. });
  11779. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11780. res.set_content("b", "text/plain");
  11781. });
  11782. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11783. auto se = detail::scope_exit([&] {
  11784. svr.stop();
  11785. listen_thread.join();
  11786. ASSERT_FALSE(svr.is_running());
  11787. });
  11788. svr.wait_until_ready();
  11789. SSLClient cli("localhost", PORT);
  11790. cli.enable_server_certificate_verification(false);
  11791. cli.set_keep_alive(true);
  11792. cli.set_read_timeout(std::chrono::seconds(1));
  11793. auto resa = cli.Get("/a");
  11794. ASSERT_TRUE(!resa);
  11795. EXPECT_EQ(Error::Read, resa.error());
  11796. auto resb = cli.Get("/b");
  11797. ASSERT_TRUE(resb);
  11798. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11799. EXPECT_EQ("b", resb->body);
  11800. }
  11801. // Closing an idle keep-alive connection sends close_notify and returns. The
  11802. // server must not wait for the client's close_notify: an idle client never
  11803. // sends one, so the worker would be held until the read timeout expires, and
  11804. // stop() would wait for it.
  11805. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11806. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11807. ASSERT_TRUE(svr.is_valid());
  11808. svr.set_keep_alive_timeout(1);
  11809. svr.set_read_timeout(10, 0);
  11810. svr.Get("/", [](const Request &, Response &res) {
  11811. res.set_content("ok", "text/plain");
  11812. });
  11813. auto port = svr.bind_to_any_port(HOST);
  11814. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11815. auto se = detail::scope_exit([&] {
  11816. if (listen_thread.joinable()) {
  11817. svr.stop();
  11818. listen_thread.join();
  11819. }
  11820. });
  11821. svr.wait_until_ready();
  11822. SSLClient cli(HOST, port);
  11823. cli.enable_server_certificate_verification(false);
  11824. cli.set_keep_alive(true);
  11825. auto res = cli.Get("/");
  11826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11827. EXPECT_EQ(StatusCode::OK_200, res->status);
  11828. // Stay idle past the keep-alive timeout so the server closes the connection.
  11829. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11830. auto start = std::chrono::steady_clock::now();
  11831. svr.stop();
  11832. listen_thread.join();
  11833. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11834. std::chrono::steady_clock::now() - start)
  11835. .count();
  11836. EXPECT_LT(elapsed, 3000);
  11837. }
  11838. #endif
  11839. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11840. protected:
  11841. ServerTestWithAI_PASSIVE()
  11842. : cli_(HOST, PORT)
  11843. #ifdef CPPHTTPLIB_SSL_ENABLED
  11844. ,
  11845. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11846. #endif
  11847. {
  11848. #ifdef CPPHTTPLIB_SSL_ENABLED
  11849. cli_.enable_server_certificate_verification(false);
  11850. #endif
  11851. }
  11852. virtual void SetUp() {
  11853. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11854. res.set_content("Hello World!", "text/plain");
  11855. });
  11856. t_ = thread(
  11857. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11858. svr_.wait_until_ready();
  11859. }
  11860. virtual void TearDown() {
  11861. svr_.stop();
  11862. t_.join();
  11863. }
  11864. #ifdef CPPHTTPLIB_SSL_ENABLED
  11865. SSLClient cli_;
  11866. SSLServer svr_;
  11867. #else
  11868. Client cli_;
  11869. Server svr_;
  11870. #endif
  11871. thread t_;
  11872. };
  11873. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11874. auto res = cli_.Get("/hi");
  11875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11876. EXPECT_EQ(StatusCode::OK_200, res->status);
  11877. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11878. EXPECT_EQ("Hello World!", res->body);
  11879. }
  11880. class ServerUpDownTest : public ::testing::Test {
  11881. protected:
  11882. ServerUpDownTest() : cli_(HOST, PORT) {}
  11883. virtual void SetUp() {
  11884. t_ = thread([&]() {
  11885. svr_.bind_to_any_port(HOST);
  11886. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11887. ASSERT_TRUE(svr_.listen_after_bind());
  11888. });
  11889. svr_.wait_until_ready();
  11890. }
  11891. virtual void TearDown() {
  11892. svr_.stop();
  11893. t_.join();
  11894. }
  11895. Client cli_;
  11896. Server svr_;
  11897. thread t_;
  11898. };
  11899. TEST_F(ServerUpDownTest, QuickStartStop) {
  11900. // Should not crash, especially when run with
  11901. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11902. }
  11903. class PayloadMaxLengthTest : public ::testing::Test {
  11904. protected:
  11905. PayloadMaxLengthTest()
  11906. : cli_(HOST, PORT)
  11907. #ifdef CPPHTTPLIB_SSL_ENABLED
  11908. ,
  11909. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11910. #endif
  11911. {
  11912. #ifdef CPPHTTPLIB_SSL_ENABLED
  11913. cli_.enable_server_certificate_verification(false);
  11914. #endif
  11915. }
  11916. virtual void SetUp() {
  11917. svr_.set_payload_max_length(8);
  11918. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11919. res.set_content("test", "text/plain");
  11920. });
  11921. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11922. svr_.wait_until_ready();
  11923. }
  11924. virtual void TearDown() {
  11925. svr_.stop();
  11926. t_.join();
  11927. }
  11928. #ifdef CPPHTTPLIB_SSL_ENABLED
  11929. SSLClient cli_;
  11930. SSLServer svr_;
  11931. #else
  11932. Client cli_;
  11933. Server svr_;
  11934. #endif
  11935. thread t_;
  11936. };
  11937. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11938. auto res = cli_.Post("/test", "123456789", "text/plain");
  11939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11940. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11941. res = cli_.Post("/test", "12345678", "text/plain");
  11942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11943. EXPECT_EQ(StatusCode::OK_200, res->status);
  11944. }
  11945. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11946. // Test chunked encoding with payload exceeding the 8-byte limit
  11947. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11948. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11950. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11951. }
  11952. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11953. // Test chunked encoding with payload within the 8-byte limit
  11954. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11955. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11957. EXPECT_EQ(StatusCode::OK_200, res->status);
  11958. }
  11959. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11960. // Test using send_request to send chunked data exceeding payload limit
  11961. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11962. "Host: " +
  11963. std::string(HOST) + ":" + std::to_string(PORT) +
  11964. "\r\n"
  11965. "Transfer-Encoding: chunked\r\n"
  11966. "Connection: close\r\n"
  11967. "\r\n"
  11968. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11969. "0123456789\r\n"
  11970. "0\r\n" // End chunk
  11971. "\r\n";
  11972. std::string response;
  11973. bool result = send_request(1, chunked_request, &response);
  11974. if (!result) {
  11975. // If send_request fails, it might be because the server closed the
  11976. // connection due to payload limit enforcement, which is acceptable
  11977. SUCCEED()
  11978. << "Server rejected oversized chunked request (connection closed)";
  11979. } else {
  11980. // If we got a response, check if it's an error response or connection was
  11981. // closed early Short response length indicates connection was closed due to
  11982. // payload limit
  11983. if (response.length() <= 10) {
  11984. SUCCEED() << "Server closed connection for oversized chunked request";
  11985. } else {
  11986. // Check for error status codes
  11987. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11988. response.find("Payload Too Large") != std::string::npos ||
  11989. response.find("400") != std::string::npos);
  11990. }
  11991. }
  11992. }
  11993. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11994. // Test request without Content-Length header exceeding payload limit
  11995. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11996. "Host: " +
  11997. std::string(HOST) + ":" +
  11998. std::to_string(PORT) +
  11999. "\r\n"
  12000. "Connection: close\r\n"
  12001. "\r\n";
  12002. // Add payload exceeding the 8-byte limit
  12003. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  12004. request_without_content_length += large_payload;
  12005. std::string response;
  12006. bool result = send_request(1, request_without_content_length, &response);
  12007. if (!result) {
  12008. // If send_request fails, server likely closed connection due to payload
  12009. // limit
  12010. SUCCEED() << "Server rejected oversized request without Content-Length "
  12011. "(connection closed)";
  12012. } else {
  12013. // Check if server responded with error or closed connection early
  12014. if (response.length() <= 10) {
  12015. SUCCEED() << "Server closed connection for oversized request without "
  12016. "Content-Length";
  12017. } else {
  12018. // Check for error status codes
  12019. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12020. response.find("Payload Too Large") != std::string::npos ||
  12021. response.find("400") != std::string::npos);
  12022. }
  12023. }
  12024. }
  12025. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  12026. // Test request without Content-Length header within payload limit
  12027. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12028. "Host: " +
  12029. std::string(HOST) + ":" +
  12030. std::to_string(PORT) +
  12031. "\r\n"
  12032. "Connection: close\r\n"
  12033. "\r\n";
  12034. // Add payload within the 8-byte limit
  12035. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  12036. request_without_content_length += small_payload;
  12037. std::string response;
  12038. bool result = send_request(1, request_without_content_length, &response);
  12039. // For requests without Content-Length, the server may have different behavior
  12040. // The key is that it should not reject due to payload limit for small
  12041. // payloads
  12042. if (result) {
  12043. // Check for any HTTP response (success or error, but not connection closed)
  12044. if (response.length() > 10) {
  12045. SUCCEED()
  12046. << "Server processed request without Content-Length within limit";
  12047. } else {
  12048. // Short response might indicate connection closed, which is acceptable
  12049. SUCCEED() << "Server closed connection for request without "
  12050. "Content-Length (acceptable behavior)";
  12051. }
  12052. } else {
  12053. // Connection failure might be due to protocol requirements
  12054. SUCCEED() << "Connection issue with request without Content-Length "
  12055. "(environment-specific)";
  12056. }
  12057. }
  12058. class LargePayloadMaxLengthTest : public ::testing::Test {
  12059. protected:
  12060. LargePayloadMaxLengthTest()
  12061. : cli_(HOST, PORT)
  12062. #ifdef CPPHTTPLIB_SSL_ENABLED
  12063. ,
  12064. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12065. #endif
  12066. {
  12067. #ifdef CPPHTTPLIB_SSL_ENABLED
  12068. cli_.enable_server_certificate_verification(false);
  12069. #endif
  12070. }
  12071. virtual void SetUp() {
  12072. // Set 10MB payload limit
  12073. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12074. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12075. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12076. res.set_content("Large payload test", "text/plain");
  12077. });
  12078. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12079. svr_.wait_until_ready();
  12080. }
  12081. virtual void TearDown() {
  12082. svr_.stop();
  12083. t_.join();
  12084. }
  12085. #ifdef CPPHTTPLIB_SSL_ENABLED
  12086. SSLClient cli_;
  12087. SSLServer svr_;
  12088. #else
  12089. Client cli_;
  12090. Server svr_;
  12091. #endif
  12092. thread t_;
  12093. };
  12094. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12095. // Test chunked encoding with payload within 10MB limit
  12096. std::string medium_payload(5 * 1024 * 1024,
  12097. 'A'); // 5MB payload, within 10MB limit
  12098. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12100. EXPECT_EQ(StatusCode::OK_200, res->status);
  12101. }
  12102. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12103. // Test chunked encoding with payload exceeding 10MB limit
  12104. std::string large_payload(12 * 1024 * 1024,
  12105. 'B'); // 12MB payload, exceeds 10MB limit
  12106. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12107. // Server may either return 413 or close the connection
  12108. if (res) {
  12109. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12110. } else {
  12111. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12112. }
  12113. }
  12114. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  12115. // Test request without Content-Length header within 10MB limit
  12116. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12117. "Host: " +
  12118. std::string(HOST) + ":" +
  12119. std::to_string(PORT) +
  12120. "\r\n"
  12121. "Connection: close\r\n"
  12122. "\r\n";
  12123. // Add 1MB payload (within 10MB limit)
  12124. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  12125. request_without_content_length += medium_payload;
  12126. std::string response;
  12127. bool result = send_request(5, request_without_content_length, &response);
  12128. if (result) {
  12129. // Should get a proper HTTP response for payloads within limit
  12130. if (response.length() > 10) {
  12131. SUCCEED() << "Server processed 1MB request without Content-Length within "
  12132. "10MB limit";
  12133. } else {
  12134. SUCCEED() << "Server closed connection (acceptable behavior for no "
  12135. "Content-Length)";
  12136. }
  12137. } else {
  12138. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  12139. }
  12140. }
  12141. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  12142. // Test request without Content-Length header exceeding 10MB limit
  12143. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12144. "Host: " +
  12145. std::string(HOST) + ":" +
  12146. std::to_string(PORT) +
  12147. "\r\n"
  12148. "Connection: close\r\n"
  12149. "\r\n";
  12150. // Add 12MB payload (exceeds 10MB limit)
  12151. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  12152. request_without_content_length += large_payload;
  12153. std::string response;
  12154. bool result = send_request(10, request_without_content_length, &response);
  12155. if (!result) {
  12156. // Server should close connection due to payload limit
  12157. SUCCEED() << "Server rejected 12MB request without Content-Length "
  12158. "(connection closed)";
  12159. } else {
  12160. // Check for error response
  12161. if (response.length() <= 10) {
  12162. SUCCEED()
  12163. << "Server closed connection for 12MB request exceeding 10MB limit";
  12164. } else {
  12165. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12166. response.find("Payload Too Large") != std::string::npos ||
  12167. response.find("400") != std::string::npos);
  12168. }
  12169. }
  12170. }
  12171. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12172. Server svr;
  12173. svr.Get("/", [](const Request &, Response &res) {
  12174. // Claims far more than it sends, then drops the connection.
  12175. res.set_content_provider(size_t(1) << 41, "text/plain",
  12176. [](size_t, size_t, DataSink &sink) {
  12177. sink.write("abc", 3);
  12178. return false;
  12179. });
  12180. });
  12181. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12182. auto se = detail::scope_exit([&] {
  12183. svr.stop();
  12184. thread.join();
  12185. ASSERT_FALSE(svr.is_running());
  12186. });
  12187. svr.wait_until_ready();
  12188. Client cli(HOST, PORT);
  12189. cli.set_payload_max_length(0);
  12190. EXPECT_FALSE(cli.Get("/"));
  12191. }
  12192. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12193. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12194. // path.
  12195. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12196. Server svr;
  12197. const size_t LIMIT = 64 * 1024; // 64KB
  12198. svr.set_payload_max_length(LIMIT);
  12199. size_t total = 0;
  12200. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12201. const ContentReader &content_reader) {
  12202. content_reader([&](const char * /*data*/, size_t len) {
  12203. total += len;
  12204. return true;
  12205. });
  12206. res.status = 200;
  12207. res.set_content("stream_ok", "text/plain");
  12208. });
  12209. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12210. auto se = detail::scope_exit([&] {
  12211. svr.stop();
  12212. thread.join();
  12213. ASSERT_FALSE(svr.is_running());
  12214. });
  12215. svr.wait_until_ready();
  12216. // Prepare 256KB raw data and gzip-compress it
  12217. std::string raw(256 * 1024, 'A');
  12218. std::string gz;
  12219. {
  12220. z_stream zs{};
  12221. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12222. Z_DEFAULT_STRATEGY);
  12223. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12224. zs.avail_in = static_cast<uInt>(raw.size());
  12225. char outbuf[4096];
  12226. int ret;
  12227. do {
  12228. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12229. zs.avail_out = sizeof(outbuf);
  12230. ret = deflate(&zs, Z_FINISH);
  12231. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12232. } while (ret != Z_STREAM_END);
  12233. deflateEnd(&zs);
  12234. }
  12235. Client cli(HOST, PORT);
  12236. cli.set_connection_timeout(std::chrono::seconds(5));
  12237. Headers headers = {{"Content-Encoding", "gzip"}};
  12238. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12239. "application/octet-stream");
  12240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12241. // Server must reject oversized decompressed payloads with 413.
  12242. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12243. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12244. EXPECT_LE(total, LIMIT);
  12245. }
  12246. #ifndef CPPHTTPLIB_SSL_ENABLED
  12247. // For a request with neither Content-Length nor Transfer-Encoding, the
  12248. // non-SSL raw-socket fallback in read_content_core() used to hand the
  12249. // compressed wire bytes straight to the ContentReader without ever routing
  12250. // them through the decompressor, so payload_max_length_ only bounded the
  12251. // compressed size on the wire, not the decompressed size.
  12252. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  12253. Server svr;
  12254. const size_t LIMIT = 64 * 1024; // 64KB
  12255. svr.set_payload_max_length(LIMIT);
  12256. size_t total = 0;
  12257. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12258. const ContentReader &content_reader) {
  12259. content_reader([&](const char * /*data*/, size_t len) {
  12260. total += len;
  12261. return true;
  12262. });
  12263. res.status = 200;
  12264. res.set_content("stream_ok", "text/plain");
  12265. });
  12266. auto port = svr.bind_to_any_port(HOST);
  12267. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12268. auto se = detail::scope_exit([&] {
  12269. svr.stop();
  12270. thread.join();
  12271. ASSERT_FALSE(svr.is_running());
  12272. });
  12273. svr.wait_until_ready();
  12274. // Prepare 256KB raw data and gzip-compress it, same payload as the
  12275. // StreamingGzipDecompression test above.
  12276. std::string raw(256 * 1024, 'A');
  12277. std::string gz;
  12278. {
  12279. httplib::detail::gzip_compressor compressor;
  12280. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  12281. [&](const char *chunk, size_t len) {
  12282. gz.append(chunk, len);
  12283. return true;
  12284. });
  12285. ASSERT_TRUE(result);
  12286. }
  12287. // Send the gzip body over raw TCP with neither Content-Length nor
  12288. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  12289. // kicks in.
  12290. std::string req = "POST /stream HTTP/1.1\r\n"
  12291. "Host: " +
  12292. std::string(HOST) + ":" + std::to_string(port) +
  12293. "\r\n"
  12294. "Content-Encoding: gzip\r\n"
  12295. "Connection: close\r\n"
  12296. "\r\n" +
  12297. gz;
  12298. std::string response;
  12299. ASSERT_TRUE(send_request(5, req, &response, port));
  12300. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12301. EXPECT_LE(total, LIMIT);
  12302. }
  12303. #endif
  12304. #endif
  12305. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12306. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12307. // the payload must be passed through untouched instead of being rejected.
  12308. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12309. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12310. Server svr;
  12311. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12312. res.set_content(body, "image/jpeg");
  12313. res.set_header("Content-Encoding", "UTF-8");
  12314. });
  12315. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12316. res.set_content(body, "image/jpeg");
  12317. res.set_header("Content-Encoding", "identity");
  12318. });
  12319. svr.Post("/echo", [](const Request &req, Response &res) {
  12320. res.set_content(req.body, "image/jpeg");
  12321. });
  12322. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12323. auto se = detail::scope_exit([&] {
  12324. svr.stop();
  12325. t.join();
  12326. ASSERT_FALSE(svr.is_running());
  12327. });
  12328. svr.wait_until_ready();
  12329. Client cli(HOST, PORT);
  12330. {
  12331. auto res = cli.Get("/image");
  12332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12333. EXPECT_EQ(StatusCode::OK_200, res->status);
  12334. EXPECT_EQ(body, res->body);
  12335. }
  12336. {
  12337. auto res = cli.Get("/identity");
  12338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12339. EXPECT_EQ(StatusCode::OK_200, res->status);
  12340. EXPECT_EQ(body, res->body);
  12341. }
  12342. {
  12343. // The same applies to a request body reaching the server.
  12344. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12345. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12347. EXPECT_EQ(StatusCode::OK_200, res->status);
  12348. EXPECT_EQ(body, res->body);
  12349. }
  12350. }
  12351. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12352. // gzip-encoded response even when the build has no zlib support.
  12353. static const char GZIPPED_HELLO_WORLD[] = {
  12354. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12355. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12356. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12357. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12358. // A content coding is a whole token, not something the field value merely
  12359. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12360. // as "fibre" look like Brotli, and turned a multi-coding value like
  12361. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12362. // it was never meant to see.
  12363. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12364. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12365. Server svr;
  12366. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12367. res.set_content(body, "image/jpeg");
  12368. res.set_header("Content-Encoding", "fibre");
  12369. });
  12370. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12371. res.set_content(body, "image/jpeg");
  12372. res.set_header("Content-Encoding", "gzip, br");
  12373. });
  12374. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12375. res.set_content(body, "image/jpeg");
  12376. res.set_header("Content-Encoding", "x-zstd-ish");
  12377. });
  12378. auto port = svr.bind_to_any_port(HOST);
  12379. thread t = thread([&]() { svr.listen_after_bind(); });
  12380. auto se = detail::scope_exit([&] {
  12381. svr.stop();
  12382. t.join();
  12383. ASSERT_FALSE(svr.is_running());
  12384. });
  12385. svr.wait_until_ready();
  12386. Client cli(HOST, port);
  12387. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12388. auto res = cli.Get(path);
  12389. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12390. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12391. // Not a coding we recognize, so the payload comes back untouched
  12392. EXPECT_EQ(body, res->body) << path;
  12393. }
  12394. }
  12395. // A content coding cpp-httplib recognizes but was not built with must be
  12396. // reported as such. Handing the still-compressed payload back to the caller
  12397. // would silently corrupt it.
  12398. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12399. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12400. Server svr;
  12401. // "image/jpeg" keeps the server from applying a content coding of its own,
  12402. // so the hand-crafted Content-Encoding below survives.
  12403. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12404. res.set_content(gzipped, "image/jpeg");
  12405. res.set_header("Content-Encoding", "gzip");
  12406. });
  12407. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12408. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12409. res.set_content(gzipped, "image/jpeg");
  12410. res.set_header("Content-Encoding", "GZIP");
  12411. });
  12412. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12413. auto se = detail::scope_exit([&] {
  12414. svr.stop();
  12415. t.join();
  12416. ASSERT_FALSE(svr.is_running());
  12417. });
  12418. svr.wait_until_ready();
  12419. Client cli(HOST, PORT);
  12420. {
  12421. auto res = cli.Get("/gzipped");
  12422. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12424. EXPECT_EQ("Hello World!", res->body);
  12425. #else
  12426. ASSERT_FALSE(res);
  12427. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12428. #endif
  12429. }
  12430. {
  12431. // open_stream() must behave the same way.
  12432. auto handle = cli.open_stream("GET", "/gzipped");
  12433. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12434. ASSERT_TRUE(handle.is_valid());
  12435. std::string received;
  12436. char buf[256];
  12437. ssize_t n;
  12438. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12439. received.append(buf, static_cast<size_t>(n));
  12440. }
  12441. EXPECT_EQ("Hello World!", received);
  12442. #else
  12443. EXPECT_FALSE(handle.is_valid());
  12444. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12445. #endif
  12446. }
  12447. {
  12448. // A differently-cased coding must not be mistaken for an unknown one, or
  12449. // the body would be handed back still compressed.
  12450. auto res = cli.Get("/gzipped-uppercase");
  12451. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12453. EXPECT_EQ("Hello World!", res->body);
  12454. #else
  12455. ASSERT_FALSE(res);
  12456. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12457. #endif
  12458. }
  12459. }
  12460. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12461. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12462. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12463. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12464. // body a second time and appending a second Content-Encoding field line, so
  12465. // clients that decode one coding per listed value handed back raw gzip bytes.
  12466. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12467. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12468. Server svr;
  12469. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12470. // keeps the server from applying a coding of its own.
  12471. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12472. res.set_content(gzipped, "text/plain");
  12473. res.set_header("Content-Encoding", "gzip");
  12474. });
  12475. auto port = svr.bind_to_any_port(HOST);
  12476. thread t = thread([&]() { svr.listen_after_bind(); });
  12477. auto se = detail::scope_exit([&] {
  12478. svr.stop();
  12479. t.join();
  12480. ASSERT_FALSE(svr.is_running());
  12481. });
  12482. svr.wait_until_ready();
  12483. Client cli(HOST, port);
  12484. Headers headers = {{"Accept-Encoding", "gzip"}};
  12485. auto res = cli.Get("/pre-gzipped", headers);
  12486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12487. EXPECT_EQ(StatusCode::OK_200, res->status);
  12488. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12489. EXPECT_EQ("Hello World!", res->body);
  12490. }
  12491. // A chunked provider settles its coding where the headers are written and
  12492. // reuses it at write time. Both ends of that have to hold: a handler's own
  12493. // Content-Encoding suppresses the coding, and a response without one is still
  12494. // compressed as it always was.
  12495. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12496. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12497. const std::string plain = "Hello World! Hello World! Hello World!";
  12498. Server svr;
  12499. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12500. res.set_header("Content-Encoding", "gzip");
  12501. res.set_chunked_content_provider(
  12502. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12503. sink.write(gzipped.data(), gzipped.size());
  12504. sink.done();
  12505. return true;
  12506. });
  12507. });
  12508. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12509. res.set_chunked_content_provider(
  12510. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12511. sink.write(plain.data(), plain.size());
  12512. sink.done();
  12513. return true;
  12514. });
  12515. });
  12516. auto port = svr.bind_to_any_port(HOST);
  12517. thread t = thread([&]() { svr.listen_after_bind(); });
  12518. auto se = detail::scope_exit([&] {
  12519. svr.stop();
  12520. t.join();
  12521. ASSERT_FALSE(svr.is_running());
  12522. });
  12523. svr.wait_until_ready();
  12524. Client cli(HOST, port);
  12525. Headers headers = {{"Accept-Encoding", "gzip"}};
  12526. {
  12527. auto res = cli.Get("/pre-gzipped", headers);
  12528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12529. EXPECT_EQ(StatusCode::OK_200, res->status);
  12530. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12531. EXPECT_EQ("Hello World!", res->body);
  12532. }
  12533. {
  12534. auto res = cli.Get("/negotiated", headers);
  12535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12536. EXPECT_EQ(StatusCode::OK_200, res->status);
  12537. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12538. EXPECT_EQ(plain, res->body);
  12539. }
  12540. }
  12541. #endif
  12542. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12543. // the same message as the comma-joined one, so both have to be read the same
  12544. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12545. // single gzip coding, and a body the sender says was encoded twice was handed
  12546. // back after one pass, still compressed but presented as decoded.
  12547. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12548. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12549. Server svr;
  12550. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12551. res.set_content(body, "image/jpeg");
  12552. res.headers.emplace("Content-Encoding", "gzip");
  12553. res.headers.emplace("Content-Encoding", "gzip");
  12554. });
  12555. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12556. res.set_content(body, "image/jpeg");
  12557. res.set_header("Content-Encoding", "gzip, gzip");
  12558. });
  12559. auto port = svr.bind_to_any_port(HOST);
  12560. thread t = thread([&]() { svr.listen_after_bind(); });
  12561. auto se = detail::scope_exit([&] {
  12562. svr.stop();
  12563. t.join();
  12564. ASSERT_FALSE(svr.is_running());
  12565. });
  12566. svr.wait_until_ready();
  12567. Client cli(HOST, port);
  12568. // Two codings is not something cpp-httplib decodes, so both representations
  12569. // take the pass-through path rather than one of them being gunzipped once.
  12570. for (const char *path : {"/split", "/joined"}) {
  12571. auto res = cli.Get(path);
  12572. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12573. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12574. EXPECT_EQ(body, res->body) << path;
  12575. }
  12576. }
  12577. // Regression test for DoS vulnerability: a malicious server sending a response
  12578. // without Content-Length header must not cause unbounded memory consumption on
  12579. // the client side. The client should stop reading after a reasonable limit,
  12580. // similar to the server-side set_payload_max_length protection.
  12581. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12582. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12583. #ifndef _WIN32
  12584. signal(SIGPIPE, SIG_IGN);
  12585. #endif
  12586. auto server_thread = std::thread([] {
  12587. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12588. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12589. default_socket_options(srv);
  12590. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12591. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12592. sockaddr_in addr{};
  12593. addr.sin_family = AF_INET;
  12594. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12595. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12596. int opt = 1;
  12597. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12598. #ifdef _WIN32
  12599. reinterpret_cast<const char *>(&opt),
  12600. #else
  12601. &opt,
  12602. #endif
  12603. sizeof(opt));
  12604. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12605. ::listen(srv, 1);
  12606. sockaddr_in cli_addr{};
  12607. socklen_t cli_len = sizeof(cli_addr);
  12608. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12609. if (cli != INVALID_SOCKET) {
  12610. char buf[4096];
  12611. ::recv(cli, buf, sizeof(buf), 0);
  12612. // Malicious response: no Content-Length, no chunked encoding
  12613. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12614. "Connection: close\r\n"
  12615. "\r\n";
  12616. ::send(cli,
  12617. #ifdef _WIN32
  12618. static_cast<const char *>(response_header.c_str()),
  12619. static_cast<int>(response_header.size()),
  12620. #else
  12621. response_header.c_str(), response_header.size(),
  12622. #endif
  12623. 0);
  12624. // Send 10MB of data
  12625. std::string chunk(64 * 1024, 'A');
  12626. size_t total_sent = 0;
  12627. while (total_sent < MALICIOUS_DATA_SIZE) {
  12628. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12629. auto sent = ::send(cli,
  12630. #ifdef _WIN32
  12631. static_cast<const char *>(chunk.c_str()),
  12632. static_cast<int>(to_send),
  12633. #else
  12634. chunk.c_str(), to_send,
  12635. #endif
  12636. 0);
  12637. if (sent <= 0) break;
  12638. total_sent += static_cast<size_t>(sent);
  12639. }
  12640. detail::close_socket(cli);
  12641. }
  12642. detail::close_socket(srv);
  12643. });
  12644. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12645. size_t total_read = 0;
  12646. {
  12647. Client cli("127.0.0.1", PORT + 2);
  12648. cli.set_read_timeout(5, 0);
  12649. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12650. auto stream = cli.open_stream("GET", "/malicious");
  12651. ASSERT_TRUE(stream.is_valid());
  12652. char buffer[64 * 1024];
  12653. ssize_t n;
  12654. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12655. total_read += static_cast<size_t>(n);
  12656. }
  12657. } // StreamHandle and Client destroyed here, closing the socket
  12658. server_thread.join();
  12659. // With set_payload_max_length, the client must stop reading before consuming
  12660. // all 10MB. The read loop should be cut off at or near the configured limit.
  12661. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12662. << "Client read " << total_read << " bytes, exceeding the configured "
  12663. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12664. }
  12665. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12666. // the entire response body without truncation.
  12667. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12668. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12669. #ifndef _WIN32
  12670. signal(SIGPIPE, SIG_IGN);
  12671. #endif
  12672. auto server_thread = std::thread([] {
  12673. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12674. default_socket_options(srv);
  12675. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12676. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12677. sockaddr_in addr{};
  12678. addr.sin_family = AF_INET;
  12679. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12680. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12681. int opt = 1;
  12682. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12683. #ifdef _WIN32
  12684. reinterpret_cast<const char *>(&opt),
  12685. #else
  12686. &opt,
  12687. #endif
  12688. sizeof(opt));
  12689. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12690. ::listen(srv, 1);
  12691. sockaddr_in cli_addr{};
  12692. socklen_t cli_len = sizeof(cli_addr);
  12693. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12694. if (cli != INVALID_SOCKET) {
  12695. char buf[4096];
  12696. ::recv(cli, buf, sizeof(buf), 0);
  12697. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12698. "Connection: close\r\n"
  12699. "\r\n";
  12700. ::send(cli,
  12701. #ifdef _WIN32
  12702. static_cast<const char *>(response_header.c_str()),
  12703. static_cast<int>(response_header.size()),
  12704. #else
  12705. response_header.c_str(), response_header.size(),
  12706. #endif
  12707. 0);
  12708. std::string chunk(64 * 1024, 'A');
  12709. size_t total_sent = 0;
  12710. while (total_sent < DATA_SIZE) {
  12711. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12712. auto sent = ::send(cli,
  12713. #ifdef _WIN32
  12714. static_cast<const char *>(chunk.c_str()),
  12715. static_cast<int>(to_send),
  12716. #else
  12717. chunk.c_str(), to_send,
  12718. #endif
  12719. 0);
  12720. if (sent <= 0) break;
  12721. total_sent += static_cast<size_t>(sent);
  12722. }
  12723. #ifdef _WIN32
  12724. ::shutdown(cli, SD_SEND);
  12725. #else
  12726. ::shutdown(cli, SHUT_WR);
  12727. #endif
  12728. // Drain until the client closes its end, ensuring all data is delivered
  12729. char drain[1024];
  12730. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12731. detail::close_socket(cli);
  12732. }
  12733. detail::close_socket(srv);
  12734. });
  12735. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12736. size_t total_read = 0;
  12737. {
  12738. Client cli("127.0.0.1", PORT + 2);
  12739. cli.set_read_timeout(5, 0);
  12740. cli.set_payload_max_length(0); // 0 means no limit
  12741. auto stream = cli.open_stream("GET", "/data");
  12742. ASSERT_TRUE(stream.is_valid());
  12743. char buffer[64 * 1024];
  12744. ssize_t n;
  12745. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12746. total_read += static_cast<size_t>(n);
  12747. }
  12748. }
  12749. server_thread.join();
  12750. EXPECT_EQ(total_read, DATA_SIZE)
  12751. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12752. << " bytes without truncation, but only read " << total_read << " bytes.";
  12753. }
  12754. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12755. // enormous Content-Length must not cause the client to pre-allocate a huge
  12756. // response body buffer. The reservation is capped at payload_max_length_, and
  12757. // the read itself fails when the body exceeds the limit.
  12758. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12759. #ifndef _WIN32
  12760. signal(SIGPIPE, SIG_IGN);
  12761. #endif
  12762. auto server_thread = std::thread([] {
  12763. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12764. default_socket_options(srv);
  12765. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12766. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12767. sockaddr_in addr{};
  12768. addr.sin_family = AF_INET;
  12769. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12770. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12771. int opt = 1;
  12772. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12773. #ifdef _WIN32
  12774. reinterpret_cast<const char *>(&opt),
  12775. #else
  12776. &opt,
  12777. #endif
  12778. sizeof(opt));
  12779. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12780. ::listen(srv, 1);
  12781. sockaddr_in cli_addr{};
  12782. socklen_t cli_len = sizeof(cli_addr);
  12783. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12784. if (cli != INVALID_SOCKET) {
  12785. char buf[4096];
  12786. ::recv(cli, buf, sizeof(buf), 0);
  12787. // Malicious response: claim a 20GB body but send only a tiny payload.
  12788. std::string response = "HTTP/1.1 200 OK\r\n"
  12789. "Content-Length: 20000000000\r\n"
  12790. "\r\n"
  12791. "abc";
  12792. ::send(cli,
  12793. #ifdef _WIN32
  12794. static_cast<const char *>(response.c_str()),
  12795. static_cast<int>(response.size()),
  12796. #else
  12797. response.c_str(), response.size(),
  12798. #endif
  12799. 0);
  12800. detail::close_socket(cli);
  12801. }
  12802. detail::close_socket(srv);
  12803. });
  12804. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12805. {
  12806. Client cli("127.0.0.1", PORT + 2);
  12807. cli.set_read_timeout(5, 0);
  12808. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12809. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12810. // (server claims more bytes than payload_max_length permits), but it must
  12811. // not exhaust memory before getting there.
  12812. auto res = cli.Get("/malicious");
  12813. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12814. }
  12815. server_thread.join();
  12816. }
  12817. // Verify that content_receiver bypasses the default payload_max_length,
  12818. // allowing streaming downloads larger than 100MB without requiring an explicit
  12819. // set_payload_max_length call.
  12820. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12821. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12822. #ifndef _WIN32
  12823. signal(SIGPIPE, SIG_IGN);
  12824. #endif
  12825. auto server_thread = std::thread([] {
  12826. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12827. default_socket_options(srv);
  12828. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12829. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12830. sockaddr_in addr{};
  12831. addr.sin_family = AF_INET;
  12832. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12833. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12834. int opt = 1;
  12835. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12836. #ifdef _WIN32
  12837. reinterpret_cast<const char *>(&opt),
  12838. #else
  12839. &opt,
  12840. #endif
  12841. sizeof(opt));
  12842. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12843. ::listen(srv, 1);
  12844. sockaddr_in cli_addr{};
  12845. socklen_t cli_len = sizeof(cli_addr);
  12846. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12847. if (cli != INVALID_SOCKET) {
  12848. char buf[4096];
  12849. ::recv(cli, buf, sizeof(buf), 0);
  12850. // Response with Content-Length larger than default 100MB limit
  12851. auto content_length = std::to_string(DATA_SIZE);
  12852. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12853. "Content-Length: " +
  12854. content_length +
  12855. "\r\n"
  12856. "Connection: close\r\n"
  12857. "\r\n";
  12858. ::send(cli,
  12859. #ifdef _WIN32
  12860. static_cast<const char *>(response_header.c_str()),
  12861. static_cast<int>(response_header.size()),
  12862. #else
  12863. response_header.c_str(), response_header.size(),
  12864. #endif
  12865. 0);
  12866. std::string chunk(64 * 1024, 'A');
  12867. size_t total_sent = 0;
  12868. while (total_sent < DATA_SIZE) {
  12869. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12870. auto sent = ::send(cli,
  12871. #ifdef _WIN32
  12872. static_cast<const char *>(chunk.c_str()),
  12873. static_cast<int>(to_send),
  12874. #else
  12875. chunk.c_str(), to_send,
  12876. #endif
  12877. 0);
  12878. if (sent <= 0) break;
  12879. total_sent += static_cast<size_t>(sent);
  12880. }
  12881. detail::close_socket(cli);
  12882. }
  12883. detail::close_socket(srv);
  12884. });
  12885. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12886. size_t total_received = 0;
  12887. {
  12888. Client cli("127.0.0.1", PORT + 2);
  12889. cli.set_read_timeout(10, 0);
  12890. // Do NOT call set_payload_max_length — use the default 100MB limit
  12891. auto res =
  12892. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12893. total_received += data_length;
  12894. return true;
  12895. });
  12896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12897. EXPECT_EQ(StatusCode::OK_200, res->status);
  12898. }
  12899. server_thread.join();
  12900. EXPECT_EQ(total_received, DATA_SIZE)
  12901. << "With content_receiver, the client should read all " << DATA_SIZE
  12902. << " bytes despite the default 100MB payload_max_length, but only read "
  12903. << total_received << " bytes.";
  12904. }
  12905. // Verify that an explicit set_payload_max_length smaller than the response is
  12906. // enforced even when a content_receiver is used.
  12907. TEST(ClientVulnerabilityTest,
  12908. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12909. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12910. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12911. #ifndef _WIN32
  12912. signal(SIGPIPE, SIG_IGN);
  12913. #endif
  12914. auto server_thread = std::thread([] {
  12915. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12916. default_socket_options(srv);
  12917. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12918. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12919. sockaddr_in addr{};
  12920. addr.sin_family = AF_INET;
  12921. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12922. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12923. int opt = 1;
  12924. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12925. #ifdef _WIN32
  12926. reinterpret_cast<const char *>(&opt),
  12927. #else
  12928. &opt,
  12929. #endif
  12930. sizeof(opt));
  12931. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12932. ::listen(srv, 1);
  12933. sockaddr_in cli_addr{};
  12934. socklen_t cli_len = sizeof(cli_addr);
  12935. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12936. if (cli != INVALID_SOCKET) {
  12937. char buf[4096];
  12938. ::recv(cli, buf, sizeof(buf), 0);
  12939. auto content_length = std::to_string(DATA_SIZE);
  12940. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12941. "Content-Length: " +
  12942. content_length +
  12943. "\r\n"
  12944. "Connection: close\r\n"
  12945. "\r\n";
  12946. ::send(cli,
  12947. #ifdef _WIN32
  12948. static_cast<const char *>(response_header.c_str()),
  12949. static_cast<int>(response_header.size()),
  12950. #else
  12951. response_header.c_str(), response_header.size(),
  12952. #endif
  12953. 0);
  12954. std::string chunk(64 * 1024, 'A');
  12955. size_t total_sent = 0;
  12956. while (total_sent < DATA_SIZE) {
  12957. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12958. auto sent = ::send(cli,
  12959. #ifdef _WIN32
  12960. static_cast<const char *>(chunk.c_str()),
  12961. static_cast<int>(to_send),
  12962. #else
  12963. chunk.c_str(), to_send,
  12964. #endif
  12965. 0);
  12966. if (sent <= 0) break;
  12967. total_sent += static_cast<size_t>(sent);
  12968. }
  12969. detail::close_socket(cli);
  12970. }
  12971. detail::close_socket(srv);
  12972. });
  12973. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12974. size_t total_received = 0;
  12975. {
  12976. Client cli("127.0.0.1", PORT + 2);
  12977. cli.set_read_timeout(10, 0);
  12978. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12979. auto res =
  12980. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12981. total_received += data_length;
  12982. return true;
  12983. });
  12984. // Should fail because 200MB exceeds the explicit 150MB limit
  12985. EXPECT_FALSE(res);
  12986. }
  12987. server_thread.join();
  12988. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12989. << "Client with content_receiver should respect the explicit "
  12990. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12991. << total_received << " bytes.";
  12992. }
  12993. // Verify that an explicit set_payload_max_length larger than the response
  12994. // allows the content_receiver to read all data successfully.
  12995. TEST(ClientVulnerabilityTest,
  12996. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12997. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12998. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12999. #ifndef _WIN32
  13000. signal(SIGPIPE, SIG_IGN);
  13001. #endif
  13002. auto server_thread = std::thread([] {
  13003. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13004. default_socket_options(srv);
  13005. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13006. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13007. sockaddr_in addr{};
  13008. addr.sin_family = AF_INET;
  13009. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13010. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13011. int opt = 1;
  13012. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13013. #ifdef _WIN32
  13014. reinterpret_cast<const char *>(&opt),
  13015. #else
  13016. &opt,
  13017. #endif
  13018. sizeof(opt));
  13019. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13020. ::listen(srv, 1);
  13021. sockaddr_in cli_addr{};
  13022. socklen_t cli_len = sizeof(cli_addr);
  13023. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13024. if (cli != INVALID_SOCKET) {
  13025. char buf[4096];
  13026. ::recv(cli, buf, sizeof(buf), 0);
  13027. auto content_length = std::to_string(DATA_SIZE);
  13028. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13029. "Content-Length: " +
  13030. content_length +
  13031. "\r\n"
  13032. "Connection: close\r\n"
  13033. "\r\n";
  13034. ::send(cli,
  13035. #ifdef _WIN32
  13036. static_cast<const char *>(response_header.c_str()),
  13037. static_cast<int>(response_header.size()),
  13038. #else
  13039. response_header.c_str(), response_header.size(),
  13040. #endif
  13041. 0);
  13042. std::string chunk(64 * 1024, 'A');
  13043. size_t total_sent = 0;
  13044. while (total_sent < DATA_SIZE) {
  13045. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13046. auto sent = ::send(cli,
  13047. #ifdef _WIN32
  13048. static_cast<const char *>(chunk.c_str()),
  13049. static_cast<int>(to_send),
  13050. #else
  13051. chunk.c_str(), to_send,
  13052. #endif
  13053. 0);
  13054. if (sent <= 0) break;
  13055. total_sent += static_cast<size_t>(sent);
  13056. }
  13057. #ifdef _WIN32
  13058. ::shutdown(cli, SD_SEND);
  13059. #else
  13060. ::shutdown(cli, SHUT_WR);
  13061. #endif
  13062. char drain[1024];
  13063. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13064. detail::close_socket(cli);
  13065. }
  13066. detail::close_socket(srv);
  13067. });
  13068. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13069. size_t total_received = 0;
  13070. {
  13071. Client cli("127.0.0.1", PORT + 2);
  13072. cli.set_read_timeout(10, 0);
  13073. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13074. auto res =
  13075. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13076. total_received += data_length;
  13077. return true;
  13078. });
  13079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13080. EXPECT_EQ(StatusCode::OK_200, res->status);
  13081. }
  13082. server_thread.join();
  13083. EXPECT_EQ(total_received, DATA_SIZE)
  13084. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13085. << " bytes (larger than " << DATA_SIZE
  13086. << " bytes response), content_receiver should read all data, but only "
  13087. "read "
  13088. << total_received << " bytes.";
  13089. }
  13090. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13091. // Regression test for "zip bomb" attack on the client side: a malicious server
  13092. // sends a small gzip-compressed response that decompresses to a huge payload.
  13093. // The client must enforce payload_max_length on the decompressed size.
  13094. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13095. constexpr size_t DECOMPRESSED_SIZE =
  13096. 10 * 1024 * 1024; // 10MB after decompression
  13097. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13098. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13099. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13100. std::string compressed;
  13101. {
  13102. httplib::detail::gzip_compressor compressor;
  13103. bool ok =
  13104. compressor.compress(uncompressed.data(), uncompressed.size(),
  13105. /*last=*/true, [&](const char *buf, size_t len) {
  13106. compressed.append(buf, len);
  13107. return true;
  13108. });
  13109. ASSERT_TRUE(ok);
  13110. }
  13111. // Sanity: compressed data should be much smaller than the decompressed size
  13112. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13113. #ifndef _WIN32
  13114. signal(SIGPIPE, SIG_IGN);
  13115. #endif
  13116. // Set up the listening socket in the main thread so the server is guaranteed
  13117. // to be ready before the client connects (eliminates race condition).
  13118. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13119. default_socket_options(srv);
  13120. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13121. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13122. sockaddr_in addr{};
  13123. addr.sin_family = AF_INET;
  13124. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13125. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13126. int opt = 1;
  13127. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13128. #ifdef _WIN32
  13129. reinterpret_cast<const char *>(&opt),
  13130. #else
  13131. &opt,
  13132. #endif
  13133. sizeof(opt));
  13134. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13135. ASSERT_EQ(0, ::listen(srv, 1));
  13136. auto server_thread = std::thread([&compressed, srv] {
  13137. sockaddr_in cli_addr{};
  13138. socklen_t cli_len = sizeof(cli_addr);
  13139. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13140. if (cli != INVALID_SOCKET) {
  13141. // Read the full HTTP request (until \r\n\r\n)
  13142. char buf[4096];
  13143. size_t total = 0;
  13144. while (total < sizeof(buf)) {
  13145. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13146. if (n <= 0) break;
  13147. total += static_cast<size_t>(n);
  13148. // Check for end of headers
  13149. if (total >= 4) {
  13150. std::string req(buf, total);
  13151. if (req.find("\r\n\r\n") != std::string::npos) break;
  13152. }
  13153. }
  13154. // Malicious response: gzip-compressed body, no Content-Length
  13155. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13156. "Content-Encoding: gzip\r\n"
  13157. "Connection: close\r\n"
  13158. "\r\n";
  13159. ::send(cli,
  13160. #ifdef _WIN32
  13161. static_cast<const char *>(response_header.c_str()),
  13162. static_cast<int>(response_header.size()),
  13163. #else
  13164. response_header.c_str(), response_header.size(),
  13165. #endif
  13166. 0);
  13167. // Send the compressed payload (small on the wire, huge when decompressed)
  13168. size_t total_sent = 0;
  13169. while (total_sent < compressed.size()) {
  13170. auto to_send = std::min(compressed.size() - total_sent,
  13171. static_cast<size_t>(64 * 1024));
  13172. auto sent =
  13173. ::send(cli,
  13174. #ifdef _WIN32
  13175. static_cast<const char *>(compressed.c_str() + total_sent),
  13176. static_cast<int>(to_send),
  13177. #else
  13178. compressed.c_str() + total_sent, to_send,
  13179. #endif
  13180. 0);
  13181. if (sent <= 0) break;
  13182. total_sent += static_cast<size_t>(sent);
  13183. }
  13184. detail::close_socket(cli);
  13185. }
  13186. });
  13187. auto se = detail::scope_exit([&] {
  13188. detail::close_socket(srv);
  13189. server_thread.join();
  13190. });
  13191. size_t total_decompressed = 0;
  13192. {
  13193. Client cli("127.0.0.1", PORT + 3);
  13194. cli.set_read_timeout(5, 0);
  13195. cli.set_decompress(true);
  13196. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13197. auto stream = cli.open_stream("GET", "/zipbomb");
  13198. ASSERT_TRUE(stream.is_valid());
  13199. char buffer[64 * 1024];
  13200. ssize_t n;
  13201. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13202. total_decompressed += static_cast<size_t>(n);
  13203. }
  13204. }
  13205. // The decompressed size must be capped by payload_max_length. Without
  13206. // protection, the client would decompress the full 10MB from a tiny
  13207. // compressed payload, enabling a zip bomb DoS attack.
  13208. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13209. << "Client decompressed " << total_decompressed
  13210. << " bytes from a gzip response. The decompressed size should be "
  13211. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13212. }
  13213. #endif
  13214. TEST(HostAndPortPropertiesTest, NoSSL) {
  13215. httplib::Client cli("www.google.com", 1234);
  13216. ASSERT_EQ("www.google.com", cli.host());
  13217. ASSERT_EQ(1234, cli.port());
  13218. }
  13219. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13220. httplib::Client cli("www.google.com:1234");
  13221. ASSERT_EQ("www.google.com", cli.host());
  13222. ASSERT_EQ(1234, cli.port());
  13223. }
  13224. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13225. // Port number that overflows int — should not crash, client becomes invalid
  13226. httplib::Client cli("http://www.google.com:99999999999999999999");
  13227. ASSERT_FALSE(cli.is_valid());
  13228. }
  13229. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13230. // Port 99999 exceeds valid range (1-65535) — should not crash
  13231. httplib::Client cli("http://www.google.com:99999");
  13232. ASSERT_FALSE(cli.is_valid());
  13233. auto res = cli.Get("/");
  13234. EXPECT_FALSE(res);
  13235. EXPECT_EQ(Error::Connection, res.error());
  13236. }
  13237. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13238. httplib::Client cli("http://user:pass@localhost:1234");
  13239. ASSERT_FALSE(cli.is_valid());
  13240. EXPECT_FALSE(cli.Get("/"));
  13241. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13242. }
  13243. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13244. httplib::Client cli("http://www.google.com:80abc");
  13245. ASSERT_FALSE(cli.is_valid());
  13246. }
  13247. #ifdef CPPHTTPLIB_SSL_ENABLED
  13248. TEST(HostAndPortPropertiesTest, SSL) {
  13249. httplib::SSLClient cli("www.google.com");
  13250. ASSERT_EQ("www.google.com", cli.host());
  13251. ASSERT_EQ(443, cli.port());
  13252. }
  13253. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13254. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13255. std::string cert;
  13256. read_file(CA_CERT_FILE, cert);
  13257. httplib::SSLClient httplib_client("www.google.com");
  13258. // Load CA store first time
  13259. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13260. // Load CA store second time (update)
  13261. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13262. // Verify client is still valid and can make connections
  13263. httplib_client.enable_server_certificate_verification(true);
  13264. auto res = httplib_client.Get("/");
  13265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13266. // Google may return 200 or 301 depending on various factors
  13267. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13268. res->status == StatusCode::MovedPermanently_301);
  13269. }
  13270. TEST(SSLClientTest, ServerNameIndication_Online) {
  13271. auto host = "httpbingo.org";
  13272. auto path = std::string{"/get"};
  13273. SSLClient cli(host, 443);
  13274. auto res = cli.Get(path);
  13275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13276. ASSERT_EQ(StatusCode::OK_200, res->status);
  13277. }
  13278. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13279. // Use a site that will cause SSL verification failure due to self-signed cert
  13280. SSLClient cli("self-signed.badssl.com", 443);
  13281. cli.enable_server_certificate_verification(true);
  13282. auto res = cli.Get("/");
  13283. ASSERT_TRUE(!res);
  13284. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13285. // Verify backend error is captured for SSLServerVerification
  13286. // This occurs when certificate verification fails
  13287. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13288. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13289. EXPECT_NE(0UL, res.ssl_backend_error());
  13290. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13291. // For OpenSSL, ssl_error is 0 for verification errors
  13292. EXPECT_EQ(0, res.ssl_error());
  13293. #if !defined(_WIN32) || \
  13294. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13295. // On non-Windows or when Windows Schannel is disabled, the error comes
  13296. // from OpenSSL's verification
  13297. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13298. res.ssl_backend_error());
  13299. #endif
  13300. #endif
  13301. }
  13302. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13303. // Use a site where hostname doesn't match the certificate
  13304. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13305. SSLClient cli("wrong.host.badssl.com", 443);
  13306. cli.enable_server_certificate_verification(true);
  13307. cli.enable_server_hostname_verification(true);
  13308. auto res = cli.Get("/");
  13309. ASSERT_TRUE(!res);
  13310. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13311. // Verify backend error is captured for hostname verification failure
  13312. EXPECT_NE(0UL, res.ssl_backend_error());
  13313. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13314. // For OpenSSL, ssl_error is 0 for verification errors
  13315. EXPECT_EQ(0, res.ssl_error());
  13316. #if !defined(_WIN32) || \
  13317. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13318. // On non-Windows or when Windows Schannel is disabled, the error comes
  13319. // from OpenSSL's hostname verification
  13320. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13321. res.ssl_backend_error());
  13322. #endif
  13323. #endif
  13324. }
  13325. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13326. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13327. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13328. SSLClient cli("www.google.com", 443);
  13329. cli.enable_server_certificate_verification(true);
  13330. auto res = cli.Get("/");
  13331. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13332. }
  13333. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13334. SSLClient cli("www.google.com", 443);
  13335. cli.enable_server_certificate_verification(true);
  13336. cli.enable_windows_certificate_verification(false);
  13337. auto res = cli.Get("/");
  13338. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13339. }
  13340. // The server sends an intermediate cross-signed by a root Windows trusts,
  13341. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13342. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13343. SSLClient cli("accounts.spotify.com", 443);
  13344. auto res = cli.Get("/");
  13345. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13346. << " ssl_backend_error=" << res.ssl_backend_error();
  13347. }
  13348. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13349. // policy status, which no backend reports for a self-signed certificate.
  13350. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13351. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13352. ASSERT_TRUE(svr.is_valid());
  13353. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13354. auto se = detail::scope_exit([&] {
  13355. svr.stop();
  13356. t.join();
  13357. ASSERT_FALSE(svr.is_running());
  13358. });
  13359. svr.wait_until_ready();
  13360. SSLClient cli("127.0.0.1", PORT);
  13361. cli.set_connection_timeout(30);
  13362. auto res = cli.Get("/");
  13363. ASSERT_FALSE(res);
  13364. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13365. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13366. }
  13367. #endif
  13368. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13369. Client cli("https://google.com");
  13370. auto res = cli.Get("/");
  13371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13372. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13373. }
  13374. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13375. SSLClient cli("google.com");
  13376. cli.set_ca_cert_path(CA_CERT_FILE);
  13377. auto res = cli.Get("/");
  13378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13379. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13380. }
  13381. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13382. SSLClient cli("google.com");
  13383. cli.enable_server_certificate_verification(true);
  13384. cli.set_ca_cert_path("hello");
  13385. auto res = cli.Get("/");
  13386. ASSERT_TRUE(!res);
  13387. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13388. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13389. // should be set
  13390. EXPECT_EQ(0, res.ssl_error());
  13391. // Verify backend error is captured for SSLLoadingCerts
  13392. // This error occurs when loading CA certificates fails
  13393. EXPECT_NE(0UL, res.ssl_backend_error());
  13394. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13395. // OpenSSL specific error codes:
  13396. // > openssl errstr 0x80000002
  13397. // error:80000002:system library::No such file or directory
  13398. // > openssl errstr 0xA000126
  13399. // error:0A000126:SSL routines::unexpected eof while reading
  13400. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13401. res.ssl_backend_error() == 0xA000126);
  13402. #endif
  13403. }
  13404. TEST(SSLClientTest, ServerCertificateVerification4) {
  13405. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13406. ASSERT_TRUE(svr.is_valid());
  13407. svr.Get("/test", [&](const Request &, Response &res) {
  13408. res.set_content("test", "text/plain");
  13409. svr.stop();
  13410. ASSERT_TRUE(true);
  13411. });
  13412. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13413. auto se = detail::scope_exit([&] {
  13414. t.join();
  13415. ASSERT_FALSE(svr.is_running());
  13416. });
  13417. svr.wait_until_ready();
  13418. SSLClient cli("127.0.0.1", PORT);
  13419. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13420. cli.enable_server_certificate_verification(true);
  13421. cli.set_connection_timeout(30);
  13422. auto res = cli.Get("/test");
  13423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13424. ASSERT_EQ(StatusCode::OK_200, res->status);
  13425. }
  13426. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13427. std::string cert;
  13428. read_file(CA_CERT_FILE, cert);
  13429. SSLClient cli("google.com");
  13430. cli.load_ca_cert_store(cert.data(), cert.size());
  13431. const auto res = cli.Get("/");
  13432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13433. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13434. }
  13435. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13436. // clang-format off
  13437. static constexpr char cert[] =
  13438. "GlobalSign Root CA\n"
  13439. "==================\n"
  13440. "-----BEGIN CERTIFICATE-----\n"
  13441. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13442. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13443. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13444. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13445. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13446. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13447. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13448. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13449. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13450. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13451. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13452. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13453. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13454. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13455. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13456. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13457. "-----END CERTIFICATE-----\n";
  13458. // clang-format on
  13459. SSLClient cli("google.com");
  13460. cli.load_ca_cert_store(cert, sizeof(cert));
  13461. const auto res = cli.Get("/");
  13462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13463. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13464. }
  13465. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13466. SSLClient cli("www.youtube.com");
  13467. cli.set_ca_cert_path(CA_CERT_FILE);
  13468. cli.enable_server_certificate_verification(true);
  13469. cli.set_follow_location(true);
  13470. auto res = cli.Get("/");
  13471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13472. ASSERT_EQ(StatusCode::OK_200, res->status);
  13473. }
  13474. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13475. SSLClient cli("wWw.YouTube.Com");
  13476. cli.set_ca_cert_path(CA_CERT_FILE);
  13477. cli.enable_server_certificate_verification(true);
  13478. cli.enable_server_hostname_verification(true);
  13479. cli.set_follow_location(true);
  13480. auto res = cli.Get("/");
  13481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13482. ASSERT_EQ(StatusCode::OK_200, res->status);
  13483. }
  13484. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13485. SSLClient cli("gOoGlE.COm");
  13486. cli.enable_server_certificate_verification(true);
  13487. cli.enable_server_hostname_verification(true);
  13488. cli.set_follow_location(true);
  13489. auto res = cli.Get("/");
  13490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13491. ASSERT_EQ(StatusCode::OK_200, res->status);
  13492. }
  13493. TEST(SSLClientTest, Issue2004_Online) {
  13494. Client client("https://google.com");
  13495. client.set_follow_location(true);
  13496. auto res = client.Get("/");
  13497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13498. ASSERT_EQ(StatusCode::OK_200, res->status);
  13499. auto body = res->body;
  13500. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13501. }
  13502. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13503. // Create SSLClient with invalid cert/key to make is_valid() return false
  13504. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13505. "nonexistent_key.pem");
  13506. // is_valid() should be false due to cert loading failure
  13507. ASSERT_FALSE(cli.is_valid());
  13508. auto res = cli.Get("/");
  13509. ASSERT_FALSE(res);
  13510. EXPECT_EQ(Error::SSLConnection, res.error());
  13511. }
  13512. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13513. // Test for Issue #2251: SSL error not properly reported when client cert
  13514. // and key paths are swapped or mismatched
  13515. // This simulates the scenario where user accidentally swaps the cert and key
  13516. // files
  13517. // Using client cert file as private key and vice versa (completely wrong)
  13518. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13519. // Should fail validation due to cert/key mismatch
  13520. ASSERT_FALSE(cli.is_valid());
  13521. // Attempt to make a request should fail with proper error
  13522. auto res = cli.Get("/");
  13523. ASSERT_FALSE(res);
  13524. EXPECT_EQ(Error::SSLConnection, res.error());
  13525. // SSL error should be recorded in the Result object (this is the key fix for
  13526. // Issue #2251)
  13527. auto backend_error = res.ssl_backend_error();
  13528. EXPECT_NE(0u, backend_error);
  13529. }
  13530. // Tests cert/key mismatch detection at the TLS context level
  13531. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13532. // Test that using mismatched cert/key causes connection failure.
  13533. // We verify this at the SSLClient level rather than through internal
  13534. // TLS API functions.
  13535. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13536. cli.enable_server_certificate_verification(false);
  13537. cli.set_connection_timeout(2);
  13538. // The mismatch should cause a connection or handshake error
  13539. auto res = cli.Get("/test");
  13540. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13541. // Either way, the request should fail
  13542. EXPECT_FALSE(res);
  13543. }
  13544. #endif
  13545. #if 0
  13546. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13547. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13548. ASSERT_TRUE(cli != nullptr);
  13549. cli->set_address_family(AF_INET6);
  13550. cli->set_interface("en0");
  13551. auto res = cli->Get("/get");
  13552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13553. ASSERT_EQ(StatusCode::OK_200, res->status);
  13554. }
  13555. #endif
  13556. // Client certificate tests - work with all TLS backends
  13557. #ifdef CPPHTTPLIB_SSL_ENABLED
  13558. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13559. void ClientCertPresent(
  13560. const std::string &client_cert_file,
  13561. const std::string &client_private_key_file,
  13562. const std::string &client_encrypted_private_key_pass = std::string(),
  13563. const ClientCertServerSetup &setup = nullptr) {
  13564. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13565. CLIENT_CA_CERT_DIR);
  13566. ASSERT_TRUE(svr.is_valid());
  13567. if (setup) { setup(svr); }
  13568. svr.Get("/test", [&](const Request &req, Response &res) {
  13569. res.set_content("test", "text/plain");
  13570. auto cert = req.peer_cert();
  13571. ASSERT_TRUE(static_cast<bool>(cert));
  13572. std::string common_name = cert.subject_cn();
  13573. EXPECT_EQ("Common Name", common_name);
  13574. });
  13575. auto port = svr.bind_to_any_port(HOST);
  13576. ASSERT_LT(0, port);
  13577. thread t = thread([&]() { svr.listen_after_bind(); });
  13578. auto se = detail::scope_exit([&] {
  13579. svr.stop();
  13580. t.join();
  13581. ASSERT_FALSE(svr.is_running());
  13582. });
  13583. svr.wait_until_ready();
  13584. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13585. client_encrypted_private_key_pass);
  13586. cli.enable_server_certificate_verification(false);
  13587. cli.set_connection_timeout(30);
  13588. auto res = cli.Get("/test");
  13589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13590. ASSERT_EQ(StatusCode::OK_200, res->status);
  13591. }
  13592. TEST(SSLClientServerTest, ClientCertPresent) {
  13593. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13594. }
  13595. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13596. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13597. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13598. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13599. }
  13600. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13601. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13602. CLIENT_CA_CERT_DIR);
  13603. ASSERT_TRUE(svr.is_valid());
  13604. if (setup) { setup(svr); }
  13605. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13606. auto port = svr.bind_to_any_port(HOST);
  13607. ASSERT_LT(0, port);
  13608. thread t = thread([&]() { svr.listen_after_bind(); });
  13609. auto se = detail::scope_exit([&] {
  13610. svr.stop();
  13611. t.join();
  13612. ASSERT_FALSE(svr.is_running());
  13613. });
  13614. svr.wait_until_ready();
  13615. SSLClient cli(HOST, port);
  13616. cli.set_connection_timeout(30);
  13617. // Skip the server certificate check, so that the request fails because the
  13618. // client certificate is missing rather than because cert.pem is not trusted
  13619. cli.enable_server_certificate_verification(false);
  13620. auto res = cli.Get("/test");
  13621. ASSERT_FALSE(res);
  13622. // The server rejects the client during the handshake, or on TLS 1.3 right
  13623. // after it, which the client notices on its first write or read
  13624. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13625. res.error() == Error::Write || res.error() == Error::Read)
  13626. << to_string(res.error());
  13627. if (res.error() == Error::SSLConnection) {
  13628. EXPECT_NE(0UL, res.ssl_backend_error());
  13629. }
  13630. // A rejection noticed on the write keeps the TLS error the write hit
  13631. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13632. }
  13633. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13634. // A server that requires client certificates must keep requiring them after a
  13635. // verify callback is set on its context, or set and then cleared again.
  13636. void ClientCertStillRequired(bool clear_callback) {
  13637. auto setup = [clear_callback](SSLServer &svr) {
  13638. ASSERT_TRUE(tls::set_verify_callback(
  13639. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13640. if (clear_callback) {
  13641. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13642. }
  13643. };
  13644. ClientCertMissing(setup);
  13645. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13646. setup);
  13647. }
  13648. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13649. ClientCertStillRequired(false);
  13650. }
  13651. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13652. ClientCertStillRequired(true);
  13653. }
  13654. // A TLS error from one request must not show up in a later request's Result
  13655. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13656. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13657. ASSERT_TRUE(svr.is_valid());
  13658. svr.Get("/test", [](const Request &, Response &res) {
  13659. res.set_content("test", "text/plain");
  13660. });
  13661. auto port = svr.bind_to_any_port(HOST);
  13662. ASSERT_LT(0, port);
  13663. thread t = thread([&]() { svr.listen_after_bind(); });
  13664. auto se = detail::scope_exit([&] {
  13665. svr.stop();
  13666. t.join();
  13667. ASSERT_FALSE(svr.is_running());
  13668. });
  13669. svr.wait_until_ready();
  13670. SSLClient cli(HOST, port);
  13671. cli.set_connection_timeout(30);
  13672. cli.enable_server_hostname_verification(false);
  13673. // cert.pem is not trusted, so the handshake fails
  13674. ASSERT_FALSE(cli.Get("/test"));
  13675. cli.enable_server_certificate_verification(false);
  13676. auto res = cli.Get("/test");
  13677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13678. EXPECT_EQ(0, res.ssl_error());
  13679. EXPECT_EQ(0UL, res.ssl_backend_error());
  13680. }
  13681. // PEM memory-based constructor tests (works with all TLS backends)
  13682. void PemMemoryClientCertPresent(
  13683. const std::string &client_cert_file,
  13684. const std::string &client_private_key_file,
  13685. const std::string &client_encrypted_private_key_pass = std::string()) {
  13686. // Read PEM files into memory
  13687. std::string server_cert_pem, server_key_pem;
  13688. std::string client_ca_pem;
  13689. std::string client_cert_pem, client_key_pem;
  13690. read_file(SERVER_CERT_FILE, server_cert_pem);
  13691. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13692. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13693. read_file(client_cert_file, client_cert_pem);
  13694. read_file(client_private_key_file, client_key_pem);
  13695. // Create server with PEM memory
  13696. SSLServer::PemMemory server_pem = {
  13697. server_cert_pem.c_str(),
  13698. server_cert_pem.size(),
  13699. server_key_pem.c_str(),
  13700. server_key_pem.size(),
  13701. client_ca_pem.c_str(),
  13702. client_ca_pem.size(),
  13703. nullptr // no password for server key
  13704. };
  13705. SSLServer svr(server_pem);
  13706. ASSERT_TRUE(svr.is_valid());
  13707. svr.Get("/test", [&](const Request &, Response &res) {
  13708. res.set_content("test", "text/plain");
  13709. });
  13710. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13711. auto se = detail::scope_exit([&] {
  13712. svr.stop();
  13713. t.join();
  13714. ASSERT_FALSE(svr.is_running());
  13715. });
  13716. svr.wait_until_ready();
  13717. // Create client with PEM memory
  13718. const char *password = client_encrypted_private_key_pass.empty()
  13719. ? nullptr
  13720. : client_encrypted_private_key_pass.c_str();
  13721. SSLClient::PemMemory client_pem = {
  13722. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  13723. client_key_pem.size(), password};
  13724. SSLClient cli(HOST, PORT, client_pem);
  13725. cli.enable_server_certificate_verification(false);
  13726. cli.set_connection_timeout(30);
  13727. auto res = cli.Get("/test");
  13728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13729. ASSERT_EQ(StatusCode::OK_200, res->status);
  13730. }
  13731. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13732. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13733. }
  13734. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13735. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13736. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13737. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13738. }
  13739. TEST(SSLClientServerTest, TrustDirOptional) {
  13740. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13741. ASSERT_TRUE(svr.is_valid());
  13742. svr.Get("/test", [&](const Request &, Response &res) {
  13743. res.set_content("test", "text/plain");
  13744. });
  13745. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13746. auto se = detail::scope_exit([&] {
  13747. svr.stop();
  13748. t.join();
  13749. ASSERT_FALSE(svr.is_running());
  13750. });
  13751. svr.wait_until_ready();
  13752. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13753. cli.enable_server_certificate_verification(false);
  13754. cli.set_connection_timeout(30);
  13755. auto res = cli.Get("/test");
  13756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13757. ASSERT_EQ(StatusCode::OK_200, res->status);
  13758. }
  13759. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13760. class NoListenSSLServer : public SSLServer {
  13761. public:
  13762. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13763. const char *client_ca_cert_file_path,
  13764. const char *client_ca_cert_dir_path = nullptr)
  13765. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13766. client_ca_cert_dir_path),
  13767. stop_(false) {}
  13768. std::atomic_bool stop_;
  13769. private:
  13770. bool process_and_close_socket(socket_t /*sock*/) override {
  13771. // Don't create SSL context
  13772. while (!stop_.load()) {
  13773. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13774. }
  13775. return true;
  13776. }
  13777. };
  13778. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13779. CLIENT_CA_CERT_FILE);
  13780. ASSERT_TRUE(svr.is_valid());
  13781. svr.Get("/test", [&](const Request &, Response &res) {
  13782. res.set_content("test", "text/plain");
  13783. });
  13784. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13785. auto se = detail::scope_exit([&] {
  13786. svr.stop_ = true;
  13787. svr.stop();
  13788. t.join();
  13789. ASSERT_FALSE(svr.is_running());
  13790. });
  13791. svr.wait_until_ready();
  13792. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13793. cli.enable_server_certificate_verification(false);
  13794. cli.set_connection_timeout(1);
  13795. auto res = cli.Get("/test");
  13796. ASSERT_TRUE(!res);
  13797. EXPECT_EQ(Error::SSLConnection, res.error());
  13798. // Timeout results in WantRead error code (maps to backend-specific value)
  13799. EXPECT_NE(0, res.ssl_error());
  13800. }
  13801. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13802. // Test SSLServer with client certificate verification using the standard
  13803. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13804. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13805. CLIENT_CA_CERT_DIR);
  13806. ASSERT_TRUE(svr.is_valid());
  13807. svr.Get("/test", [&](const Request &req, Response &res) {
  13808. res.set_content("test", "text/plain");
  13809. auto cert = req.peer_cert();
  13810. ASSERT_TRUE(static_cast<bool>(cert));
  13811. auto common_name = cert.subject_cn();
  13812. EXPECT_EQ("Common Name", common_name);
  13813. });
  13814. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13815. auto se = detail::scope_exit([&] {
  13816. svr.stop();
  13817. t.join();
  13818. ASSERT_FALSE(svr.is_running());
  13819. });
  13820. svr.wait_until_ready();
  13821. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13822. cli.enable_server_certificate_verification(false);
  13823. cli.set_connection_timeout(30);
  13824. auto res = cli.Get("/test");
  13825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13826. ASSERT_EQ(StatusCode::OK_200, res->status);
  13827. }
  13828. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13829. // Verifies that wildcard matching and exact matching work consistently
  13830. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13831. using namespace httplib::tls;
  13832. // We need a running server to test against
  13833. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13834. ASSERT_TRUE(svr.is_valid());
  13835. svr.Get("/test", [](const Request &, Response &res) {
  13836. res.set_content("ok", "text/plain");
  13837. });
  13838. thread t([&]() { svr.listen(HOST, PORT); });
  13839. auto se = detail::scope_exit([&] {
  13840. svr.stop();
  13841. t.join();
  13842. });
  13843. svr.wait_until_ready();
  13844. bool verify_callback_called = false;
  13845. bool verify_result_wrong = false;
  13846. SSLClient cli(HOST, PORT);
  13847. cli.enable_server_certificate_verification(true);
  13848. cli.set_ca_cert_path(CA_CERT_FILE);
  13849. cli.set_connection_timeout(5);
  13850. // Note: Test certificate has CN="Common Name", not "localhost"
  13851. bool verify_result_cn = false;
  13852. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13853. verify_callback_called = true;
  13854. if (!ctx.cert) return false;
  13855. // Test 1: "Common Name" should match (our test server cert CN)
  13856. verify_result_cn = ctx.check_hostname("Common Name");
  13857. // Test 2: wrong hostname should not match
  13858. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13859. return true; // Accept for the purpose of this test
  13860. });
  13861. auto res = cli.Get("/test");
  13862. // The request may succeed or fail depending on cert configuration
  13863. // but the callback should have been called
  13864. ASSERT_TRUE(verify_callback_called)
  13865. << "Verify callback should have been called";
  13866. // CN="Common Name" should match our test certificate
  13867. //
  13868. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13869. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13870. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13871. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13872. // <openssl/base.h>, which is included transitively when
  13873. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13874. #if defined(OPENSSL_IS_BORINGSSL)
  13875. EXPECT_FALSE(verify_result_cn)
  13876. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13877. #else
  13878. EXPECT_TRUE(verify_result_cn)
  13879. << "verify_hostname should match 'Common Name' (certificate CN)";
  13880. #endif
  13881. // Wrong hostname should not match
  13882. EXPECT_FALSE(verify_result_wrong)
  13883. << "verify_hostname should not match 'wronghost.example.com'";
  13884. }
  13885. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13886. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13887. // X509_check_ip behavior and must hold for every backend.
  13888. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13889. using namespace httplib::tls;
  13890. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13891. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13892. ASSERT_TRUE(svr.is_valid());
  13893. svr.Get("/test", [](const Request &, Response &res) {
  13894. res.set_content("ok", "text/plain");
  13895. });
  13896. thread t([&]() { svr.listen(HOST, PORT); });
  13897. auto se = detail::scope_exit([&] {
  13898. svr.stop();
  13899. t.join();
  13900. });
  13901. svr.wait_until_ready();
  13902. bool verify_callback_called = false;
  13903. bool ip_matched_via_cn = true;
  13904. SSLClient cli(HOST, PORT);
  13905. cli.enable_server_certificate_verification(true);
  13906. cli.set_ca_cert_path(CA_CERT_FILE);
  13907. cli.set_connection_timeout(5);
  13908. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13909. verify_callback_called = true;
  13910. if (!ctx.cert) return false;
  13911. // The IP appears only in the CN, so it must NOT be accepted.
  13912. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13913. return true; // Accept for the purpose of this test
  13914. });
  13915. cli.Get("/test");
  13916. ASSERT_TRUE(verify_callback_called)
  13917. << "Verify callback should have been called";
  13918. EXPECT_FALSE(ip_matched_via_cn)
  13919. << "An IP host must not be authenticated via the certificate CN";
  13920. }
  13921. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13922. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13923. using namespace httplib::tls;
  13924. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13925. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13926. ASSERT_TRUE(svr.is_valid());
  13927. svr.Get("/test", [](const Request &, Response &res) {
  13928. res.set_content("ok", "text/plain");
  13929. });
  13930. thread t([&]() { svr.listen(HOST, PORT); });
  13931. auto se = detail::scope_exit([&] {
  13932. svr.stop();
  13933. t.join();
  13934. });
  13935. svr.wait_until_ready();
  13936. bool verify_callback_called = false;
  13937. bool san_matched = false;
  13938. bool wrong_ipv6_matched = true;
  13939. bool cn_ipv6_matched = true;
  13940. SSLClient cli(HOST, PORT);
  13941. cli.enable_server_certificate_verification(true);
  13942. cli.set_ca_cert_path(CA_CERT_FILE);
  13943. cli.set_connection_timeout(5);
  13944. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13945. verify_callback_called = true;
  13946. if (!ctx.cert) return false;
  13947. // Matches the IPv6 iPAddress SAN.
  13948. san_matched = ctx.check_hostname("2001:db8::1");
  13949. // A different IPv6 address must not match.
  13950. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13951. // "::1" lives only in the CN, so it must not be accepted.
  13952. cn_ipv6_matched = ctx.check_hostname("::1");
  13953. return true; // Accept for the purpose of this test
  13954. });
  13955. cli.Get("/test");
  13956. ASSERT_TRUE(verify_callback_called)
  13957. << "Verify callback should have been called";
  13958. EXPECT_TRUE(san_matched)
  13959. << "verify_hostname should match an IPv6 iPAddress SAN";
  13960. EXPECT_FALSE(wrong_ipv6_matched)
  13961. << "verify_hostname should not match a non-matching IPv6 address";
  13962. EXPECT_FALSE(cn_ipv6_matched)
  13963. << "An IPv6 host must not be authenticated via the certificate CN";
  13964. }
  13965. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13966. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13967. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13968. using namespace httplib::tls;
  13969. // SANs: DNS:a.zz, IP:42.46.122.122
  13970. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13971. ASSERT_TRUE(svr.is_valid());
  13972. svr.Get("/test", [](const Request &, Response &res) {
  13973. res.set_content("ok", "text/plain");
  13974. });
  13975. auto port = svr.bind_to_any_port(HOST);
  13976. thread t([&]() { svr.listen_after_bind(); });
  13977. auto se = detail::scope_exit([&] {
  13978. svr.stop();
  13979. t.join();
  13980. });
  13981. svr.wait_until_ready();
  13982. bool verify_callback_called = false;
  13983. bool dns_san_matched = false;
  13984. bool ip_san_matched = false;
  13985. bool ip_matched_via_dns_san = true;
  13986. bool dns_matched_via_ip_san = true;
  13987. bool cn_matched_next_to_dns_san = true;
  13988. SSLClient cli(HOST, port);
  13989. cli.enable_server_certificate_verification(true);
  13990. cli.set_ca_cert_path(CA_CERT_FILE);
  13991. cli.set_connection_timeout(5);
  13992. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13993. verify_callback_called = true;
  13994. if (!ctx.cert) return false;
  13995. dns_san_matched = ctx.check_hostname("a.zz");
  13996. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13997. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13998. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13999. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14000. return true; // Accept for the purpose of this test
  14001. });
  14002. cli.Get("/test");
  14003. ASSERT_TRUE(verify_callback_called)
  14004. << "Verify callback should have been called";
  14005. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14006. EXPECT_TRUE(ip_san_matched)
  14007. << "verify_hostname should match an iPAddress SAN";
  14008. EXPECT_FALSE(ip_matched_via_dns_san)
  14009. << "An IP host must not be authenticated via a dNSName SAN";
  14010. EXPECT_FALSE(dns_matched_via_ip_san)
  14011. << "A DNS host must not be authenticated via an iPAddress SAN";
  14012. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14013. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14014. }
  14015. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14016. // "www.*.example.test" names one host and not every host under example.test.
  14017. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14018. using namespace httplib::tls;
  14019. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14020. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14021. ASSERT_TRUE(svr.is_valid());
  14022. svr.Get("/test", [](const Request &, Response &res) {
  14023. res.set_content("ok", "text/plain");
  14024. });
  14025. auto port = svr.bind_to_any_port(HOST);
  14026. thread t([&]() { svr.listen_after_bind(); });
  14027. auto se = detail::scope_exit([&] {
  14028. svr.stop();
  14029. t.join();
  14030. });
  14031. svr.wait_until_ready();
  14032. bool verify_callback_called = false;
  14033. bool leftmost_wildcard_matched = false;
  14034. bool wildcard_spanned_labels = true;
  14035. bool inner_wildcard_matched = true;
  14036. SSLClient cli(HOST, port);
  14037. cli.enable_server_certificate_verification(true);
  14038. cli.set_ca_cert_path(CA_CERT_FILE);
  14039. cli.set_connection_timeout(5);
  14040. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14041. verify_callback_called = true;
  14042. if (!ctx.cert) return false;
  14043. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14044. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14045. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14046. return true; // Accept for the purpose of this test
  14047. });
  14048. cli.Get("/test");
  14049. ASSERT_TRUE(verify_callback_called)
  14050. << "Verify callback should have been called";
  14051. EXPECT_TRUE(leftmost_wildcard_matched)
  14052. << "A leftmost wildcard should match a single label";
  14053. EXPECT_FALSE(wildcard_spanned_labels)
  14054. << "A wildcard label must not match more than one label";
  14055. EXPECT_FALSE(inner_wildcard_matched)
  14056. << "A wildcard outside the leftmost label must not be honoured";
  14057. }
  14058. // sans() must report each SAN entry under its own type.
  14059. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14060. using namespace httplib::tls;
  14061. // SANs: DNS:a.zz, IP:42.46.122.122
  14062. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14063. ASSERT_TRUE(svr.is_valid());
  14064. svr.Get("/test", [](const Request &, Response &res) {
  14065. res.set_content("ok", "text/plain");
  14066. });
  14067. auto port = svr.bind_to_any_port(HOST);
  14068. thread t([&]() { svr.listen_after_bind(); });
  14069. auto se = detail::scope_exit([&] {
  14070. svr.stop();
  14071. t.join();
  14072. });
  14073. svr.wait_until_ready();
  14074. bool verify_callback_called = false;
  14075. std::vector<SanEntry> sans;
  14076. SSLClient cli(HOST, port);
  14077. cli.enable_server_certificate_verification(true);
  14078. cli.set_ca_cert_path(CA_CERT_FILE);
  14079. cli.set_connection_timeout(5);
  14080. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14081. verify_callback_called = true;
  14082. if (!ctx.cert) return false;
  14083. sans = ctx.sans();
  14084. return true; // Accept for the purpose of this test
  14085. });
  14086. cli.Get("/test");
  14087. ASSERT_TRUE(verify_callback_called)
  14088. << "Verify callback should have been called";
  14089. auto has_san = [&](SanType type, const std::string &value) {
  14090. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14091. return san.type == type && san.value == value;
  14092. });
  14093. };
  14094. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14095. << "sans() should report the dNSName SAN";
  14096. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14097. << "sans() should report the iPAddress SAN";
  14098. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14099. << "sans() must not report the dNSName SAN as an address";
  14100. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14101. << "sans() must not report the iPAddress SAN as a DNS name";
  14102. }
  14103. #endif
  14104. // mbedTLS-specific callback constructor test
  14105. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14106. #ifdef CPPHTTPLIB_SSL_ENABLED
  14107. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14108. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14109. ASSERT_TRUE(svr.is_valid());
  14110. // Set up a handler to verify client certificate is present
  14111. bool client_cert_verified = false;
  14112. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14113. // Verify that client certificate was provided
  14114. client_cert_verified = true;
  14115. res.set_content("success", "text/plain");
  14116. });
  14117. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14118. auto se = detail::scope_exit([&] {
  14119. svr.stop();
  14120. t.join();
  14121. ASSERT_FALSE(svr.is_running());
  14122. });
  14123. svr.wait_until_ready();
  14124. // Client with certificate
  14125. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14126. cli.enable_server_certificate_verification(false);
  14127. cli.set_connection_timeout(30);
  14128. auto res = cli.Get("/test");
  14129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14130. ASSERT_EQ(StatusCode::OK_200, res->status);
  14131. ASSERT_TRUE(client_cert_verified);
  14132. EXPECT_EQ("success", res->body);
  14133. }
  14134. #endif
  14135. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14136. // backends
  14137. #ifdef CPPHTTPLIB_SSL_ENABLED
  14138. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14139. using namespace httplib::tls;
  14140. // Test that when client CA cert file is provided,
  14141. // the server properly requests and validates client certificates
  14142. // Create a server with client authentication
  14143. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14144. ASSERT_TRUE(svr.is_valid());
  14145. bool handler_called = false;
  14146. svr.Get("/test", [&](const Request &req, Response &res) {
  14147. handler_called = true;
  14148. // Verify that a client certificate was provided
  14149. auto cert = req.peer_cert();
  14150. ASSERT_TRUE(static_cast<bool>(cert));
  14151. // Get the issuer name
  14152. std::string issuer_str = cert.issuer_name();
  14153. ASSERT_FALSE(issuer_str.empty());
  14154. // The client certificate should be issued by our test CA
  14155. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14156. res.set_content("authenticated", "text/plain");
  14157. });
  14158. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14159. auto se = detail::scope_exit([&] {
  14160. svr.stop();
  14161. t.join();
  14162. ASSERT_FALSE(svr.is_running());
  14163. });
  14164. svr.wait_until_ready();
  14165. // Connect with a client certificate issued by the CA
  14166. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14167. cli.enable_server_certificate_verification(false);
  14168. cli.set_connection_timeout(30);
  14169. auto res = cli.Get("/test");
  14170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14171. ASSERT_EQ(StatusCode::OK_200, res->status);
  14172. ASSERT_TRUE(handler_called);
  14173. EXPECT_EQ("authenticated", res->body);
  14174. }
  14175. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14176. using namespace httplib::tls;
  14177. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14178. ASSERT_TRUE(svr.is_valid());
  14179. svr.Get("/test", [](const Request &, Response &res) {
  14180. res.set_content("ok", "text/plain");
  14181. });
  14182. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14183. auto se = detail::scope_exit([&] {
  14184. svr.stop();
  14185. t.join();
  14186. });
  14187. svr.wait_until_ready();
  14188. SSLClient cli(HOST, PORT);
  14189. cli.enable_server_certificate_verification(false);
  14190. cli.set_connection_timeout(30);
  14191. bool cert_checked = false;
  14192. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14193. if (ctx.cert) {
  14194. auto sans = ctx.sans();
  14195. // Test certificate may or may not have SANs - just verify the API
  14196. // works If SANs exist, verify the types are valid
  14197. for (const auto &san : sans) {
  14198. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14199. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14200. san.type == SanType::OTHER);
  14201. EXPECT_FALSE(san.value.empty());
  14202. }
  14203. cert_checked = true;
  14204. }
  14205. return true;
  14206. });
  14207. auto res = cli.Get("/test");
  14208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14209. EXPECT_TRUE(cert_checked);
  14210. }
  14211. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14212. using namespace httplib::tls;
  14213. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14214. ASSERT_TRUE(svr.is_valid());
  14215. svr.Get("/test", [](const Request &, Response &res) {
  14216. res.set_content("ok", "text/plain");
  14217. });
  14218. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14219. auto se = detail::scope_exit([&] {
  14220. svr.stop();
  14221. t.join();
  14222. });
  14223. svr.wait_until_ready();
  14224. SSLClient cli(HOST, PORT);
  14225. cli.enable_server_certificate_verification(false);
  14226. cli.set_connection_timeout(30);
  14227. bool validity_checked = false;
  14228. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14229. if (ctx.cert) {
  14230. time_t not_before = 0, not_after = 0;
  14231. bool result = ctx.validity(not_before, not_after);
  14232. EXPECT_TRUE(result);
  14233. // Verify that not_before < now < not_after for a valid cert
  14234. time_t now = time(nullptr);
  14235. EXPECT_LT(not_before, now);
  14236. EXPECT_GT(not_after, now);
  14237. validity_checked = true;
  14238. }
  14239. return true;
  14240. });
  14241. auto res = cli.Get("/test");
  14242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14243. EXPECT_TRUE(validity_checked);
  14244. }
  14245. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14246. using namespace httplib::tls;
  14247. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14248. ASSERT_TRUE(svr.is_valid());
  14249. svr.Get("/test", [](const Request &, Response &res) {
  14250. res.set_content("ok", "text/plain");
  14251. });
  14252. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14253. auto se = detail::scope_exit([&] {
  14254. svr.stop();
  14255. t.join();
  14256. });
  14257. svr.wait_until_ready();
  14258. SSLClient cli(HOST, PORT);
  14259. cli.enable_server_certificate_verification(false);
  14260. cli.set_connection_timeout(30);
  14261. bool serial_checked = false;
  14262. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14263. if (ctx.cert) {
  14264. std::string serial = ctx.serial();
  14265. EXPECT_FALSE(serial.empty());
  14266. // Serial should be a hex string
  14267. for (char c : serial) {
  14268. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14269. (c >= 'a' && c <= 'f'));
  14270. }
  14271. serial_checked = true;
  14272. }
  14273. return true;
  14274. });
  14275. auto res = cli.Get("/test");
  14276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14277. EXPECT_TRUE(serial_checked);
  14278. }
  14279. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14280. // Test 1: Valid CA file - no error should be recorded
  14281. {
  14282. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14283. CLIENT_CA_CERT_FILE);
  14284. ASSERT_TRUE(svr.is_valid());
  14285. // With valid setup, last_ssl_error should be 0
  14286. EXPECT_EQ(0, svr.ssl_last_error());
  14287. }
  14288. // Test 2: Invalid CA file content
  14289. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14290. {
  14291. // Create a temporary file with completely invalid content
  14292. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14293. {
  14294. std::ofstream ofs(temp_invalid_ca);
  14295. ofs << "This is not a certificate file at all\n";
  14296. ofs << "Just plain text content\n";
  14297. }
  14298. // Create server with invalid CA file
  14299. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14300. // Clean up temporary file
  14301. std::remove(temp_invalid_ca);
  14302. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14303. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14304. // Note: SSL_CTX_load_verify_locations typically fails first,
  14305. // but our error handling code path is still exercised
  14306. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14307. }
  14308. }
  14309. TEST(VerifyCallbackTest, VerifyContextFields) {
  14310. using namespace httplib::tls;
  14311. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14312. ASSERT_TRUE(svr.is_valid());
  14313. svr.Get("/test", [](const Request &, Response &res) {
  14314. res.set_content("ok", "text/plain");
  14315. });
  14316. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14317. auto se = detail::scope_exit([&] {
  14318. svr.stop();
  14319. t.join();
  14320. });
  14321. svr.wait_until_ready();
  14322. SSLClient cli(HOST, PORT);
  14323. cli.enable_server_certificate_verification(false);
  14324. cli.set_connection_timeout(30);
  14325. int callback_count = 0;
  14326. bool saw_leaf_cert = false;
  14327. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14328. if (ctx.cert) {
  14329. callback_count++;
  14330. // We should see at least one certificate (the leaf)
  14331. std::string cn = ctx.subject_cn();
  14332. if (!cn.empty()) { saw_leaf_cert = true; }
  14333. // Verify context fields are populated
  14334. EXPECT_NE(ctx.session, nullptr);
  14335. EXPECT_GE(ctx.depth, 0);
  14336. }
  14337. return true;
  14338. });
  14339. auto res = cli.Get("/test");
  14340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14341. EXPECT_GT(callback_count, 0);
  14342. EXPECT_TRUE(saw_leaf_cert);
  14343. }
  14344. // A verifier belongs to the client that set it, not to the thread that set it.
  14345. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14346. using namespace httplib::tls;
  14347. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14348. ASSERT_TRUE(svr.is_valid());
  14349. svr.Get("/test", [](const Request &, Response &res) {
  14350. res.set_content("ok", "text/plain");
  14351. });
  14352. auto port = svr.bind_to_any_port(HOST);
  14353. thread t([&]() { svr.listen_after_bind(); });
  14354. auto se = detail::scope_exit([&] {
  14355. svr.stop();
  14356. t.join();
  14357. });
  14358. svr.wait_until_ready();
  14359. auto rejecting_calls = 0;
  14360. SSLClient rejecting(HOST, port);
  14361. rejecting.enable_server_certificate_verification(false);
  14362. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14363. rejecting_calls++;
  14364. return false;
  14365. });
  14366. auto accepting_calls = 0;
  14367. SSLClient accepting(HOST, port);
  14368. accepting.enable_server_certificate_verification(false);
  14369. // Set on another thread than the requests below.
  14370. thread([&]() {
  14371. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14372. accepting_calls++;
  14373. return true;
  14374. });
  14375. }).join();
  14376. // Requested on another thread than the verifier was set on.
  14377. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14378. EXPECT_GT(rejecting_calls, 0);
  14379. auto res = accepting.Get("/test");
  14380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14381. EXPECT_GT(accepting_calls, 0);
  14382. }
  14383. // A verifier replaced while a handshake runs it lives until it returns.
  14384. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14385. using namespace httplib::tls;
  14386. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14387. ASSERT_TRUE(svr.is_valid());
  14388. svr.Get("/test", [](const Request &, Response &res) {
  14389. res.set_content("ok", "text/plain");
  14390. });
  14391. auto port = svr.bind_to_any_port(HOST);
  14392. thread t([&]() { svr.listen_after_bind(); });
  14393. auto se = detail::scope_exit([&] {
  14394. svr.stop();
  14395. t.join();
  14396. });
  14397. svr.wait_until_ready();
  14398. SSLClient cli(HOST, port);
  14399. cli.enable_server_certificate_verification(false);
  14400. std::promise<void> entered;
  14401. std::promise<void> replaced;
  14402. auto replaced_future = replaced.get_future();
  14403. auto first_call = true;
  14404. // Long enough to live on the heap
  14405. std::string expected(64, 'v');
  14406. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14407. if (first_call) {
  14408. first_call = false;
  14409. entered.set_value();
  14410. replaced_future.wait();
  14411. }
  14412. return expected == std::string(64, 'v');
  14413. });
  14414. thread request([&]() {
  14415. auto res = cli.Get("/test");
  14416. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14417. });
  14418. entered.get_future().wait();
  14419. cli.set_server_certificate_verifier(
  14420. [](const VerifyContext &) { return true; });
  14421. replaced.set_value();
  14422. request.join();
  14423. }
  14424. // VerifyContext::session is the same handle the other tls:: functions take.
  14425. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14426. using namespace httplib::tls;
  14427. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14428. ASSERT_TRUE(svr.is_valid());
  14429. svr.Get("/test", [](const Request &, Response &res) {
  14430. res.set_content("ok", "text/plain");
  14431. });
  14432. auto port = svr.bind_to_any_port(HOST);
  14433. thread t([&]() { svr.listen_after_bind(); });
  14434. auto se = detail::scope_exit([&] {
  14435. svr.stop();
  14436. t.join();
  14437. });
  14438. svr.wait_until_ready();
  14439. SSLClient cli(HOST, port);
  14440. cli.enable_server_certificate_verification(false);
  14441. session_t verifier_session = nullptr;
  14442. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14443. verifier_session = ctx.session;
  14444. return true;
  14445. });
  14446. session_t session_verifier_session = nullptr;
  14447. cli.set_session_verifier([&](session_t session) {
  14448. session_verifier_session = session;
  14449. return SSLVerifierResponse::NoDecisionMade;
  14450. });
  14451. auto res = cli.Get("/test");
  14452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14453. EXPECT_NE(nullptr, verifier_session);
  14454. EXPECT_EQ(session_verifier_session, verifier_session);
  14455. }
  14456. // Each client's verifier is stored with its own TLS context, so configuring a
  14457. // second client on the same thread must not replace the first one's.
  14458. TEST(VerifyCallbackTest, PerClientVerifiersOnSameThread) {
  14459. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14460. ASSERT_TRUE(svr.is_valid());
  14461. svr.Get("/test", [](const Request &, Response &res) {
  14462. res.set_content("ok", "text/plain");
  14463. });
  14464. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14465. auto se = detail::scope_exit([&] {
  14466. svr.stop();
  14467. t.join();
  14468. });
  14469. svr.wait_until_ready();
  14470. std::atomic<int> count1{0};
  14471. std::atomic<int> count2{0};
  14472. SSLClient cli1(HOST, PORT);
  14473. cli1.enable_server_certificate_verification(false);
  14474. cli1.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  14475. count1++;
  14476. return true;
  14477. });
  14478. SSLClient cli2(HOST, PORT);
  14479. cli2.enable_server_certificate_verification(false);
  14480. cli2.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  14481. count2++;
  14482. return true;
  14483. });
  14484. auto res1 = cli1.Get("/test");
  14485. ASSERT_TRUE(res1) << "Error: " << to_string(res1.error());
  14486. EXPECT_GT(count1.load(), 0);
  14487. EXPECT_EQ(0, count2.load());
  14488. count1 = 0;
  14489. auto res2 = cli2.Get("/test");
  14490. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  14491. EXPECT_EQ(0, count1.load());
  14492. EXPECT_GT(count2.load(), 0);
  14493. }
  14494. // A verifier set on one thread must still run when the request is made from
  14495. // another thread.
  14496. TEST(VerifyCallbackTest, VerifierRunsOnAnotherThread) {
  14497. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14498. ASSERT_TRUE(svr.is_valid());
  14499. svr.Get("/test", [](const Request &, Response &res) {
  14500. res.set_content("ok", "text/plain");
  14501. });
  14502. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14503. auto se = detail::scope_exit([&] {
  14504. svr.stop();
  14505. t.join();
  14506. });
  14507. svr.wait_until_ready();
  14508. std::atomic<int> count{0};
  14509. SSLClient cli(HOST, PORT);
  14510. cli.enable_server_certificate_verification(false);
  14511. cli.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  14512. count++;
  14513. return true;
  14514. });
  14515. Result res;
  14516. thread worker([&]() { res = cli.Get("/test"); });
  14517. worker.join();
  14518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14519. EXPECT_GT(count.load(), 0);
  14520. }
  14521. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14522. using httplib::tls::TlsError;
  14523. // Test that verify_error_to_string returns empty for success
  14524. std::string success_str = TlsError::verify_error_to_string(0);
  14525. EXPECT_TRUE(success_str.empty());
  14526. // Test that verify_error_to_string returns non-empty for error codes
  14527. // Using a common error code (certificate expired)
  14528. std::string error_str =
  14529. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14530. EXPECT_FALSE(error_str.empty());
  14531. }
  14532. TEST(SessionVerifierTest, CertificateAccepted) {
  14533. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14534. ASSERT_TRUE(svr.is_valid());
  14535. svr.Get("/test", [](const Request &, Response &res) {
  14536. res.set_content("ok", "text/plain");
  14537. });
  14538. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14539. auto se = detail::scope_exit([&] {
  14540. svr.stop();
  14541. t.join();
  14542. });
  14543. svr.wait_until_ready();
  14544. SSLClient cli(HOST, PORT);
  14545. cli.enable_server_certificate_verification(false);
  14546. cli.set_connection_timeout(30);
  14547. bool callback_called = false;
  14548. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14549. EXPECT_NE(session, nullptr);
  14550. callback_called = true;
  14551. return SSLVerifierResponse::CertificateAccepted;
  14552. });
  14553. auto res = cli.Get("/test");
  14554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14555. EXPECT_EQ(200, res->status);
  14556. EXPECT_TRUE(callback_called);
  14557. }
  14558. TEST(SessionVerifierTest, CertificateRejected) {
  14559. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14560. ASSERT_TRUE(svr.is_valid());
  14561. svr.Get("/test", [](const Request &, Response &res) {
  14562. res.set_content("ok", "text/plain");
  14563. });
  14564. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14565. auto se = detail::scope_exit([&] {
  14566. svr.stop();
  14567. t.join();
  14568. });
  14569. svr.wait_until_ready();
  14570. SSLClient cli(HOST, PORT);
  14571. cli.enable_server_certificate_verification(false);
  14572. cli.set_connection_timeout(30);
  14573. bool callback_called = false;
  14574. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14575. EXPECT_NE(session, nullptr);
  14576. callback_called = true;
  14577. return SSLVerifierResponse::CertificateRejected;
  14578. });
  14579. auto res = cli.Get("/test");
  14580. EXPECT_FALSE(res);
  14581. EXPECT_TRUE(callback_called);
  14582. }
  14583. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14584. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14585. ASSERT_TRUE(svr.is_valid());
  14586. svr.Get("/test", [](const Request &, Response &res) {
  14587. res.set_content("ok", "text/plain");
  14588. });
  14589. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14590. auto se = detail::scope_exit([&] {
  14591. svr.stop();
  14592. t.join();
  14593. });
  14594. svr.wait_until_ready();
  14595. // NoDecisionMade with verification disabled should succeed (no default check)
  14596. SSLClient cli(HOST, PORT);
  14597. cli.enable_server_certificate_verification(false);
  14598. cli.set_connection_timeout(30);
  14599. bool callback_called = false;
  14600. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14601. EXPECT_NE(session, nullptr);
  14602. callback_called = true;
  14603. return SSLVerifierResponse::NoDecisionMade;
  14604. });
  14605. auto res = cli.Get("/test");
  14606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14607. EXPECT_EQ(200, res->status);
  14608. EXPECT_TRUE(callback_called);
  14609. }
  14610. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14611. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14612. ASSERT_TRUE(svr.is_valid());
  14613. svr.Get("/test", [](const Request &, Response &res) {
  14614. res.set_content("ok", "text/plain");
  14615. });
  14616. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14617. auto se = detail::scope_exit([&] {
  14618. svr.stop();
  14619. t.join();
  14620. });
  14621. svr.wait_until_ready();
  14622. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14623. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14624. // so we only check that the request fails, not whether the callback was
  14625. // called.
  14626. SSLClient cli(HOST, PORT);
  14627. cli.enable_server_certificate_verification(true);
  14628. cli.set_connection_timeout(30);
  14629. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14630. EXPECT_NE(session, nullptr);
  14631. return SSLVerifierResponse::NoDecisionMade;
  14632. });
  14633. auto res = cli.Get("/test");
  14634. EXPECT_FALSE(res);
  14635. }
  14636. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14637. // Test SSL server using PemMemory constructor with client CA certificates
  14638. // Read PEM files
  14639. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14640. read_file(SERVER_CERT_FILE, server_cert_pem);
  14641. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14642. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14643. // Create SSLServer with PemMemory constructor including client CA
  14644. SSLServer::PemMemory server_pem = {
  14645. server_cert_pem.c_str(),
  14646. server_cert_pem.size(),
  14647. server_key_pem.c_str(),
  14648. server_key_pem.size(),
  14649. client_ca_pem.c_str(),
  14650. client_ca_pem.size(),
  14651. nullptr // no password for server key
  14652. };
  14653. SSLServer svr(server_pem);
  14654. ASSERT_TRUE(svr.is_valid());
  14655. // No SSL error should be recorded for valid setup
  14656. EXPECT_EQ(0, svr.ssl_last_error());
  14657. // Set up server endpoints
  14658. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14659. res.set_content("ok", "text/plain");
  14660. });
  14661. // Start server in a thread
  14662. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14663. svr.wait_until_ready();
  14664. // Connect with client certificate (using constructor with paths)
  14665. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14666. cli.enable_server_certificate_verification(false);
  14667. auto res = cli.Get("/test-pem-ca");
  14668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14669. EXPECT_EQ(200, res->status);
  14670. EXPECT_EQ("ok", res->body);
  14671. svr.stop();
  14672. server_thread.join();
  14673. }
  14674. #endif
  14675. #ifdef _WIN32
  14676. TEST(CleanupTest, WSACleanup) {
  14677. int ret = WSACleanup();
  14678. ASSERT_EQ(0, ret);
  14679. }
  14680. #endif
  14681. #ifndef CPPHTTPLIB_SSL_ENABLED
  14682. TEST(NoSSLSupport, SimpleInterface) {
  14683. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14684. }
  14685. #endif
  14686. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14687. TEST(InvalidScheme, SimpleInterface) {
  14688. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14689. }
  14690. #endif
  14691. TEST(NoScheme, SimpleInterface) {
  14692. Client cli("yahoo.com:80");
  14693. ASSERT_TRUE(cli.is_valid());
  14694. }
  14695. TEST(SendAPI, SimpleInterface_Online) {
  14696. Client cli("http://yahoo.com");
  14697. Request req;
  14698. req.method = "GET";
  14699. req.path = "/";
  14700. auto res = cli.send(req);
  14701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14702. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14703. }
  14704. TEST(SendAPI, WithParamsInRequest) {
  14705. Server svr;
  14706. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14707. EXPECT_TRUE(req.has_param("test"));
  14708. EXPECT_EQ("test_value", req.get_param_value("test"));
  14709. });
  14710. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14711. auto se = detail::scope_exit([&] {
  14712. svr.stop();
  14713. t.join();
  14714. ASSERT_FALSE(svr.is_running());
  14715. });
  14716. svr.wait_until_ready();
  14717. Client cli(HOST, PORT);
  14718. {
  14719. Request req;
  14720. req.method = "GET";
  14721. req.path = "/";
  14722. req.params.emplace("test", "test_value");
  14723. auto res = cli.send(req);
  14724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14725. }
  14726. {
  14727. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14729. }
  14730. }
  14731. TEST(ClientImplMethods, GetSocketTest) {
  14732. httplib::Server svr;
  14733. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14734. res.status = StatusCode::OK_200;
  14735. });
  14736. auto port = svr.bind_to_any_port("127.0.0.1");
  14737. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14738. auto se = detail::scope_exit([&] {
  14739. svr.stop();
  14740. thread.join();
  14741. ASSERT_FALSE(svr.is_running());
  14742. });
  14743. svr.wait_until_ready();
  14744. {
  14745. httplib::Client cli("127.0.0.1", port);
  14746. cli.set_keep_alive(true);
  14747. // Use the behavior of cpp-httplib of opening the connection
  14748. // only when the first request happens. If that changes,
  14749. // this test would be obsolete.
  14750. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14751. // This also implicitly tests the server. But other tests would fail much
  14752. // earlier than this one to be considered.
  14753. auto res = cli.Get("/");
  14754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14755. EXPECT_EQ(StatusCode::OK_200, res->status);
  14756. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14757. }
  14758. }
  14759. #ifdef CPPHTTPLIB_SSL_ENABLED
  14760. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14761. Client cli("http://yahoo.com");
  14762. auto res = cli.Get("/");
  14763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14764. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14765. cli.set_follow_location(true);
  14766. res = cli.Get("/");
  14767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14768. EXPECT_EQ(StatusCode::OK_200, res->status);
  14769. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14770. }
  14771. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14772. Client cli("https://yahoo.com");
  14773. auto res = cli.Get("/");
  14774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14775. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14776. cli.set_follow_location(true);
  14777. res = cli.Get("/");
  14778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14779. EXPECT_EQ(StatusCode::OK_200, res->status);
  14780. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14781. }
  14782. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14783. Client cli("https://yahoo.com");
  14784. auto res = cli.Get("/");
  14785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14786. ASSERT_FALSE(!res);
  14787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14788. ASSERT_FALSE(res == nullptr);
  14789. ASSERT_TRUE(res != nullptr);
  14790. EXPECT_EQ(Error::Success, res.error());
  14791. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14792. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14793. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14794. cli.set_follow_location(true);
  14795. res = cli.Get("/");
  14796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14797. EXPECT_EQ(Error::Success, res.error());
  14798. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14799. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14800. EXPECT_EQ(StatusCode::OK_200, res->status);
  14801. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14802. }
  14803. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14804. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14805. Client cli("https://cdnjs.cloudflare.com");
  14806. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14807. Headers{{"Accept-Encoding", "br"}});
  14808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14809. EXPECT_EQ(StatusCode::OK_200, res->status);
  14810. EXPECT_EQ(287630U, res->body.size());
  14811. EXPECT_EQ("application/javascript; charset=utf-8",
  14812. res->get_header_value("Content-Type"));
  14813. }
  14814. #endif
  14815. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14816. #undef REDIR_HOST // Silence compiler warning
  14817. #define REDIR_HOST "https://httpbingo.org"
  14818. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14819. Client cli(REDIR_HOST);
  14820. cli.set_follow_location(true);
  14821. auto res =
  14822. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14824. EXPECT_EQ(StatusCode::OK_200, res->status);
  14825. }
  14826. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14827. Client cli(REDIR_HOST);
  14828. cli.set_follow_location(true);
  14829. Params params;
  14830. params.emplace("url", "http://example.com");
  14831. params.emplace("status_code", "302");
  14832. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14834. EXPECT_EQ(StatusCode::OK_200, res->status);
  14835. }
  14836. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14837. Client cli(REDIR_HOST);
  14838. cli.set_follow_location(true);
  14839. Params params;
  14840. params.emplace("url", "http://example.com");
  14841. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14843. EXPECT_EQ(StatusCode::OK_200, res->status);
  14844. }
  14845. TEST(HttpToHttpsRedirectTest, CertFile) {
  14846. auto ssl_port = PORT + 1;
  14847. Server svr;
  14848. ASSERT_TRUE(svr.is_valid());
  14849. svr.Get("/index", [&](const Request &, Response &res) {
  14850. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14851. "/index");
  14852. svr.stop();
  14853. });
  14854. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14855. ASSERT_TRUE(ssl_svr.is_valid());
  14856. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14857. res.set_content("test", "text/plain");
  14858. ssl_svr.stop();
  14859. });
  14860. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14861. thread t2 =
  14862. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14863. auto se = detail::scope_exit([&] {
  14864. t2.join();
  14865. t.join();
  14866. ASSERT_FALSE(svr.is_running());
  14867. });
  14868. svr.wait_until_ready();
  14869. ssl_svr.wait_until_ready();
  14870. Client cli("127.0.0.1", PORT);
  14871. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14872. cli.enable_server_certificate_verification(true);
  14873. cli.set_follow_location(true);
  14874. cli.set_connection_timeout(30);
  14875. auto res = cli.Get("/index");
  14876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14877. ASSERT_EQ(StatusCode::OK_200, res->status);
  14878. }
  14879. TEST(SSLClientRedirectTest, CertFile) {
  14880. auto ssl_port = PORT + 1;
  14881. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14882. ASSERT_TRUE(ssl_svr1.is_valid());
  14883. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14884. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14885. "/index");
  14886. ssl_svr1.stop();
  14887. });
  14888. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14889. ASSERT_TRUE(ssl_svr2.is_valid());
  14890. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14891. res.set_content("test", "text/plain");
  14892. ssl_svr2.stop();
  14893. });
  14894. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14895. thread t2 =
  14896. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14897. auto se = detail::scope_exit([&] {
  14898. t2.join();
  14899. t.join();
  14900. ASSERT_FALSE(ssl_svr1.is_running());
  14901. });
  14902. ssl_svr1.wait_until_ready();
  14903. ssl_svr2.wait_until_ready();
  14904. SSLClient cli("127.0.0.1", PORT);
  14905. std::string cert;
  14906. read_file(SERVER_CERT2_FILE, cert);
  14907. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14908. cli.enable_server_certificate_verification(true);
  14909. cli.set_follow_location(true);
  14910. cli.set_connection_timeout(30);
  14911. auto res = cli.Get("/index");
  14912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14913. ASSERT_EQ(StatusCode::OK_200, res->status);
  14914. }
  14915. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14916. // another port, so the client follows it with a new client.
  14917. static Result GetThroughTlsRedirectToDifferentPort(
  14918. const std::function<void(SSLClient &)> &setup,
  14919. const char *target_cert = SERVER_CERT2_FILE,
  14920. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  14921. auto ssl_port = PORT + 1;
  14922. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14923. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14924. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14925. "/index");
  14926. });
  14927. SSLServer ssl_svr2(target_cert, target_key);
  14928. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14929. res.set_content("test", "text/plain");
  14930. });
  14931. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14932. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14933. auto se = detail::scope_exit([&] {
  14934. ssl_svr2.stop();
  14935. ssl_svr1.stop();
  14936. t2.join();
  14937. t.join();
  14938. });
  14939. ssl_svr1.wait_until_ready();
  14940. ssl_svr2.wait_until_ready();
  14941. SSLClient cli("127.0.0.1", PORT);
  14942. cli.set_follow_location(true);
  14943. cli.set_connection_timeout(30);
  14944. setup(cli);
  14945. return cli.Get("/index");
  14946. }
  14947. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14948. auto calls = 0;
  14949. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14950. cli.enable_server_certificate_verification(false);
  14951. // Accept the first server only.
  14952. cli.set_session_verifier([&](tls::session_t) {
  14953. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14954. : SSLVerifierResponse::CertificateRejected;
  14955. });
  14956. });
  14957. EXPECT_FALSE(res);
  14958. EXPECT_EQ(2, calls);
  14959. }
  14960. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14961. std::string pinned;
  14962. auto res = GetThroughTlsRedirectToDifferentPort(
  14963. [&](SSLClient &cli) {
  14964. cli.enable_server_certificate_verification(false);
  14965. // Pin the first certificate seen.
  14966. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14967. if (pinned.empty()) { pinned = ctx.serial(); }
  14968. return ctx.serial() == pinned;
  14969. });
  14970. },
  14971. // A certificate other than the first server's.
  14972. SERVER_CERT_FILE);
  14973. EXPECT_FALSE(res);
  14974. EXPECT_FALSE(pinned.empty());
  14975. }
  14976. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14977. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14978. std::string cert;
  14979. read_file(SERVER_CERT2_FILE, cert);
  14980. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14981. });
  14982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14983. EXPECT_EQ(StatusCode::OK_200, res->status);
  14984. }
  14985. // The target's certificate is signed by the root CA, which the first server's
  14986. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  14987. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  14988. auto res = GetThroughTlsRedirectToDifferentPort(
  14989. [](SSLClient &cli) {
  14990. std::string root_ca, cert;
  14991. read_file(CLIENT_CA_CERT_FILE, root_ca);
  14992. read_file(SERVER_CERT2_FILE, cert);
  14993. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  14994. cli.load_ca_cert_store(cert.data(), cert.size());
  14995. cli.enable_server_hostname_verification(false);
  14996. },
  14997. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14999. EXPECT_EQ(StatusCode::OK_200, res->status);
  15000. }
  15001. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15002. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15003. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15004. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15005. auto res = GetThroughTlsRedirectToDifferentPort(
  15006. [](SSLClient &cli) {
  15007. std::string root_ca, cert;
  15008. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15009. read_file(SERVER_CERT2_FILE, cert);
  15010. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15011. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15012. cli.enable_server_hostname_verification(false);
  15013. },
  15014. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15015. ASSERT_FALSE(res);
  15016. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15017. }
  15018. #endif
  15019. // A store set via set_ca_cert_store() must be carried over to the client that
  15020. // follows a cross-host redirect, rather than replaced by the system CAs.
  15021. TEST(SSLClientRedirectTest, SetCaCertStore) {
  15022. auto ssl_port = PORT + 1;
  15023. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15024. ASSERT_TRUE(ssl_svr1.is_valid());
  15025. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15026. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15027. "/index");
  15028. });
  15029. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15030. ASSERT_TRUE(ssl_svr2.is_valid());
  15031. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15032. res.set_content("test", "text/plain");
  15033. });
  15034. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15035. thread t2 =
  15036. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15037. auto se = detail::scope_exit([&] {
  15038. ssl_svr2.stop();
  15039. ssl_svr1.stop();
  15040. t2.join();
  15041. t.join();
  15042. ASSERT_FALSE(ssl_svr1.is_running());
  15043. });
  15044. ssl_svr1.wait_until_ready();
  15045. ssl_svr2.wait_until_ready();
  15046. SSLClient cli("127.0.0.1", PORT);
  15047. std::string cert;
  15048. read_file(SERVER_CERT2_FILE, cert);
  15049. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15050. cli.enable_server_certificate_verification(true);
  15051. cli.set_follow_location(true);
  15052. cli.set_connection_timeout(30);
  15053. auto res = cli.Get("/index");
  15054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15055. ASSERT_EQ(StatusCode::OK_200, res->status);
  15056. }
  15057. // The session verifier must also run for the host a redirect leads to.
  15058. TEST(SSLClientRedirectTest, SessionVerifier) {
  15059. auto ssl_port = PORT + 1;
  15060. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15061. ASSERT_TRUE(ssl_svr1.is_valid());
  15062. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15063. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15064. "/index");
  15065. });
  15066. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15067. ASSERT_TRUE(ssl_svr2.is_valid());
  15068. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15069. res.set_content("test", "text/plain");
  15070. });
  15071. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15072. thread t2 =
  15073. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15074. auto se = detail::scope_exit([&] {
  15075. ssl_svr2.stop();
  15076. ssl_svr1.stop();
  15077. t2.join();
  15078. t.join();
  15079. ASSERT_FALSE(ssl_svr1.is_running());
  15080. });
  15081. ssl_svr1.wait_until_ready();
  15082. ssl_svr2.wait_until_ready();
  15083. SSLClient cli("127.0.0.1", PORT);
  15084. std::string cert;
  15085. read_file(SERVER_CERT2_FILE, cert);
  15086. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15087. cli.enable_server_certificate_verification(true);
  15088. cli.set_follow_location(true);
  15089. cli.set_connection_timeout(30);
  15090. // Accept the first host only.
  15091. std::atomic<int> sessions{0};
  15092. cli.set_session_verifier([&](tls::session_t) -> SSLVerifierResponse {
  15093. return sessions++ == 0 ? SSLVerifierResponse::CertificateAccepted
  15094. : SSLVerifierResponse::CertificateRejected;
  15095. });
  15096. auto res = cli.Get("/index");
  15097. ASSERT_FALSE(res);
  15098. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15099. EXPECT_EQ(2, sessions.load());
  15100. }
  15101. // So must the verifier given to set_server_certificate_verifier().
  15102. TEST(SSLClientRedirectTest, ServerCertificateVerifier) {
  15103. auto ssl_port = PORT + 1;
  15104. std::atomic<bool> redirected{false};
  15105. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15106. ASSERT_TRUE(ssl_svr1.is_valid());
  15107. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15108. redirected = true;
  15109. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15110. "/index");
  15111. });
  15112. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15113. ASSERT_TRUE(ssl_svr2.is_valid());
  15114. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15115. res.set_content("test", "text/plain");
  15116. });
  15117. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15118. thread t2 =
  15119. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15120. auto se = detail::scope_exit([&] {
  15121. ssl_svr2.stop();
  15122. ssl_svr1.stop();
  15123. t2.join();
  15124. t.join();
  15125. ASSERT_FALSE(ssl_svr1.is_running());
  15126. });
  15127. ssl_svr1.wait_until_ready();
  15128. ssl_svr2.wait_until_ready();
  15129. SSLClient cli("127.0.0.1", PORT);
  15130. std::string cert;
  15131. read_file(SERVER_CERT2_FILE, cert);
  15132. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15133. cli.enable_server_certificate_verification(true);
  15134. cli.set_follow_location(true);
  15135. cli.set_connection_timeout(30);
  15136. // Accept the host that redirects only; the verifier runs once per
  15137. // certificate in the chain, so count the calls made after the redirect.
  15138. std::atomic<int> calls_after_redirect{0};
  15139. cli.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  15140. if (!redirected) { return true; }
  15141. calls_after_redirect++;
  15142. return false;
  15143. });
  15144. auto res = cli.Get("/index");
  15145. ASSERT_FALSE(res);
  15146. EXPECT_LT(0, calls_after_redirect.load());
  15147. }
  15148. #endif
  15149. #ifdef CPPHTTPLIB_SSL_ENABLED
  15150. // Test that set_ca_cert_store() skips system certs (consistent with
  15151. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15152. // should be trusted - system certs should NOT be loaded.
  15153. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15154. // Load a specific cert that is NOT a system CA cert
  15155. std::string cert;
  15156. read_file(SERVER_CERT2_FILE, cert);
  15157. SSLClient cli("google.com");
  15158. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15159. cli.enable_server_certificate_verification(true);
  15160. // This should FAIL because:
  15161. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15162. // 2. System certs should NOT be loaded when custom store is set
  15163. // If system certs WERE loaded, this would succeed
  15164. auto res = cli.Get("/");
  15165. ASSERT_FALSE(res);
  15166. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15167. }
  15168. // Same as above, but through the native store handle path. Regression test:
  15169. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15170. // merged system certs into the user-provided store.
  15171. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15172. std::string cert;
  15173. read_file(SERVER_CERT2_FILE, cert);
  15174. SSLClient cli("google.com");
  15175. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15176. cli.enable_server_certificate_verification(true);
  15177. auto res = cli.Get("/");
  15178. ASSERT_FALSE(res);
  15179. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15180. }
  15181. // A custom store set via the native handle must still verify a server whose
  15182. // cert it does contain.
  15183. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15184. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15185. ASSERT_TRUE(svr.is_valid());
  15186. svr.Get("/test", [&](const Request &, Response &res) {
  15187. res.set_content("test", "text/plain");
  15188. });
  15189. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15190. auto se = detail::scope_exit([&] {
  15191. svr.stop();
  15192. t.join();
  15193. ASSERT_FALSE(svr.is_running());
  15194. });
  15195. svr.wait_until_ready();
  15196. SSLClient cli("127.0.0.1", PORT);
  15197. std::string cert;
  15198. read_file(SERVER_CERT2_FILE, cert);
  15199. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15200. cli.enable_server_certificate_verification(true);
  15201. cli.set_connection_timeout(30);
  15202. auto res = cli.Get("/test");
  15203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15204. ASSERT_EQ(StatusCode::OK_200, res->status);
  15205. }
  15206. // CA certs loaded through the universal Client must be transferred to the
  15207. // client created internally for following an HTTPS redirect. Regression test:
  15208. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15209. // the CA data for redirect transfer.
  15210. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15211. auto ssl_port = PORT + 1;
  15212. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15213. ASSERT_TRUE(ssl_svr1.is_valid());
  15214. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15215. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15216. "/index");
  15217. });
  15218. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15219. ASSERT_TRUE(ssl_svr2.is_valid());
  15220. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15221. res.set_content("test", "text/plain");
  15222. });
  15223. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15224. thread t2 =
  15225. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15226. auto se = detail::scope_exit([&] {
  15227. ssl_svr2.stop();
  15228. ssl_svr1.stop();
  15229. t2.join();
  15230. t.join();
  15231. ASSERT_FALSE(ssl_svr1.is_running());
  15232. });
  15233. ssl_svr1.wait_until_ready();
  15234. ssl_svr2.wait_until_ready();
  15235. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15236. std::string cert;
  15237. read_file(SERVER_CERT2_FILE, cert);
  15238. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15239. cli.enable_server_certificate_verification(true);
  15240. cli.set_follow_location(true);
  15241. cli.set_connection_timeout(30);
  15242. auto res = cli.Get("/index");
  15243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15244. ASSERT_EQ(StatusCode::OK_200, res->status);
  15245. }
  15246. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15247. // so a host signed by a system CA verifies even though a custom CA is set
  15248. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15249. std::string cert;
  15250. read_file(SERVER_CERT2_FILE, cert);
  15251. SSLClient cli("google.com");
  15252. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15253. cli.enable_system_ca(true);
  15254. cli.enable_server_certificate_verification(true);
  15255. auto res = cli.Get("/");
  15256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15257. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15258. }
  15259. // The custom CA remains effective when combined with the system CA
  15260. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15261. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15262. ASSERT_TRUE(svr.is_valid());
  15263. svr.Get("/test", [&](const Request &, Response &res) {
  15264. res.set_content("test", "text/plain");
  15265. });
  15266. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15267. auto se = detail::scope_exit([&] {
  15268. svr.stop();
  15269. t.join();
  15270. ASSERT_FALSE(svr.is_running());
  15271. });
  15272. svr.wait_until_ready();
  15273. SSLClient cli("127.0.0.1", PORT);
  15274. std::string cert;
  15275. read_file(SERVER_CERT2_FILE, cert);
  15276. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15277. cli.enable_system_ca(true);
  15278. cli.enable_server_certificate_verification(true);
  15279. cli.set_connection_timeout(30);
  15280. auto res = cli.Get("/test");
  15281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15282. ASSERT_EQ(StatusCode::OK_200, res->status);
  15283. }
  15284. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15285. // skip chain verification entirely (only the certificate identity was
  15286. // checked), so a server presenting an untrusted certificate with a matching
  15287. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15288. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15289. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15290. ASSERT_TRUE(svr.is_valid());
  15291. svr.Get("/test", [&](const Request &, Response &res) {
  15292. res.set_content("test", "text/plain");
  15293. });
  15294. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15295. auto se = detail::scope_exit([&] {
  15296. svr.stop();
  15297. t.join();
  15298. ASSERT_FALSE(svr.is_running());
  15299. });
  15300. svr.wait_until_ready();
  15301. SSLClient cli("127.0.0.1", PORT);
  15302. std::string cert;
  15303. // A trusted CA that did not sign the server certificate. The server cert
  15304. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15305. // this connection.
  15306. read_file(CLIENT_CA_CERT_FILE, cert);
  15307. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15308. cli.enable_server_certificate_verification(true);
  15309. cli.set_connection_timeout(30);
  15310. auto res = cli.Get("/test");
  15311. ASSERT_FALSE(res);
  15312. }
  15313. // enable_system_ca(false) prevents system CA loading entirely
  15314. TEST(SSLClientTest, DisableSystemCa_Online) {
  15315. SSLClient cli("google.com");
  15316. cli.enable_system_ca(false);
  15317. cli.enable_server_certificate_verification(true);
  15318. auto res = cli.Get("/");
  15319. ASSERT_FALSE(res);
  15320. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15321. // itself when the CA chain is empty
  15322. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15323. res.error() == Error::SSLConnection);
  15324. }
  15325. // The universal Client forwards enable_system_ca()
  15326. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15327. std::string cert;
  15328. read_file(SERVER_CERT2_FILE, cert);
  15329. Client cli("https://google.com");
  15330. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15331. cli.enable_system_ca(true);
  15332. cli.enable_server_certificate_verification(true);
  15333. auto res = cli.Get("/");
  15334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15335. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15336. }
  15337. // The system CA policy must carry over to the client created internally for
  15338. // following a cross-host HTTPS redirect
  15339. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15340. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15341. ASSERT_TRUE(svr.is_valid());
  15342. svr.Get("/index", [&](const Request &, Response &res) {
  15343. res.set_redirect("https://www.google.com/");
  15344. });
  15345. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15346. auto se = detail::scope_exit([&] {
  15347. svr.stop();
  15348. t.join();
  15349. ASSERT_FALSE(svr.is_running());
  15350. });
  15351. svr.wait_until_ready();
  15352. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15353. std::string cert;
  15354. read_file(SERVER_CERT2_FILE, cert);
  15355. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15356. cli.enable_system_ca(true);
  15357. cli.enable_server_certificate_verification(true);
  15358. cli.set_follow_location(true);
  15359. cli.set_connection_timeout(30);
  15360. // Receiving any response proves the redirect client completed the TLS
  15361. // handshake with a system-CA-signed host
  15362. auto res = cli.Get("/index");
  15363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15364. }
  15365. TEST(MultipartFormDataTest, LargeData) {
  15366. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15367. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15368. const ContentReader &content_reader) {
  15369. if (req.is_multipart_form_data()) {
  15370. std::vector<FormData> items;
  15371. content_reader(
  15372. [&](const FormData &file) {
  15373. items.push_back(file);
  15374. return true;
  15375. },
  15376. [&](const char *data, size_t data_length) {
  15377. items.back().content.append(data, data_length);
  15378. return true;
  15379. });
  15380. EXPECT_TRUE(std::string(items[0].name) == "document");
  15381. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15382. EXPECT_TRUE(items[0].filename == "2MB_data");
  15383. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15384. EXPECT_TRUE(items[1].name == "hello");
  15385. EXPECT_TRUE(items[1].content == "world");
  15386. EXPECT_TRUE(items[1].filename == "");
  15387. EXPECT_TRUE(items[1].content_type == "");
  15388. } else {
  15389. std::string body;
  15390. content_reader([&](const char *data, size_t data_length) {
  15391. body.append(data, data_length);
  15392. return true;
  15393. });
  15394. }
  15395. });
  15396. auto port = svr.bind_to_any_port(HOST);
  15397. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15398. auto se = detail::scope_exit([&] {
  15399. svr.stop();
  15400. t.join();
  15401. ASSERT_FALSE(svr.is_running());
  15402. });
  15403. svr.wait_until_ready();
  15404. {
  15405. std::string data(1024 * 1024 * 2, '.');
  15406. std::stringstream buffer;
  15407. buffer << data;
  15408. SSLClient cli(HOST, port);
  15409. cli.enable_server_certificate_verification(false);
  15410. UploadFormDataItems items{
  15411. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15412. {"hello", "world", "", ""},
  15413. };
  15414. auto res = cli.Post("/post", items);
  15415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15416. ASSERT_EQ(StatusCode::OK_200, res->status);
  15417. }
  15418. }
  15419. TEST(MultipartFormDataTest, DataProviderItems) {
  15420. std::random_device seed_gen;
  15421. std::mt19937 random(seed_gen());
  15422. std::string rand1;
  15423. rand1.resize(1000);
  15424. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15425. std::string rand2;
  15426. rand2.resize(3000);
  15427. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15428. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15429. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15430. const ContentReader &content_reader) {
  15431. ASSERT_FALSE(req.is_multipart_form_data());
  15432. std::string body;
  15433. content_reader([&](const char *data, size_t data_length) {
  15434. body.append(data, data_length);
  15435. return true;
  15436. });
  15437. EXPECT_EQ(body, "");
  15438. });
  15439. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15440. const ContentReader &content_reader) {
  15441. ASSERT_TRUE(req.is_multipart_form_data());
  15442. std::vector<FormData> items;
  15443. content_reader(
  15444. [&](const FormData &file) {
  15445. items.push_back(file);
  15446. return true;
  15447. },
  15448. [&](const char *data, size_t data_length) {
  15449. items.back().content.append(data, data_length);
  15450. return true;
  15451. });
  15452. ASSERT_TRUE(items.size() == 2);
  15453. EXPECT_EQ(std::string(items[0].name), "name1");
  15454. EXPECT_EQ(items[0].content, "Testing123");
  15455. EXPECT_EQ(items[0].filename, "filename1");
  15456. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15457. EXPECT_EQ(items[1].name, "name2");
  15458. EXPECT_EQ(items[1].content, "Testing456");
  15459. EXPECT_EQ(items[1].filename, "");
  15460. EXPECT_EQ(items[1].content_type, "");
  15461. });
  15462. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15463. const ContentReader &content_reader) {
  15464. ASSERT_TRUE(req.is_multipart_form_data());
  15465. std::vector<FormData> items;
  15466. content_reader(
  15467. [&](const FormData &file) {
  15468. items.push_back(file);
  15469. return true;
  15470. },
  15471. [&](const char *data, size_t data_length) {
  15472. items.back().content.append(data, data_length);
  15473. return true;
  15474. });
  15475. ASSERT_TRUE(items.size() == 2);
  15476. EXPECT_EQ(items[0].name, "name3");
  15477. EXPECT_EQ(items[0].content, rand1);
  15478. EXPECT_EQ(items[0].filename, "filename3");
  15479. EXPECT_EQ(items[0].content_type, "");
  15480. EXPECT_EQ(items[1].name, "name4");
  15481. EXPECT_EQ(items[1].content, rand2);
  15482. EXPECT_EQ(items[1].filename, "filename4");
  15483. EXPECT_EQ(items[1].content_type, "");
  15484. });
  15485. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15486. const ContentReader &content_reader) {
  15487. ASSERT_TRUE(req.is_multipart_form_data());
  15488. std::vector<FormData> items;
  15489. content_reader(
  15490. [&](const FormData &file) {
  15491. items.push_back(file);
  15492. return true;
  15493. },
  15494. [&](const char *data, size_t data_length) {
  15495. items.back().content.append(data, data_length);
  15496. return true;
  15497. });
  15498. ASSERT_TRUE(items.size() == 4);
  15499. EXPECT_EQ(std::string(items[0].name), "name1");
  15500. EXPECT_EQ(items[0].content, "Testing123");
  15501. EXPECT_EQ(items[0].filename, "filename1");
  15502. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15503. EXPECT_EQ(items[1].name, "name2");
  15504. EXPECT_EQ(items[1].content, "Testing456");
  15505. EXPECT_EQ(items[1].filename, "");
  15506. EXPECT_EQ(items[1].content_type, "");
  15507. EXPECT_EQ(items[2].name, "name3");
  15508. EXPECT_EQ(items[2].content, rand1);
  15509. EXPECT_EQ(items[2].filename, "filename3");
  15510. EXPECT_EQ(items[2].content_type, "");
  15511. EXPECT_EQ(items[3].name, "name4");
  15512. EXPECT_EQ(items[3].content, rand2);
  15513. EXPECT_EQ(items[3].filename, "filename4");
  15514. EXPECT_EQ(items[3].content_type, "");
  15515. });
  15516. auto port = svr.bind_to_any_port("localhost");
  15517. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15518. auto se = detail::scope_exit([&] {
  15519. svr.stop();
  15520. t.join();
  15521. ASSERT_FALSE(svr.is_running());
  15522. });
  15523. svr.wait_until_ready();
  15524. {
  15525. SSLClient cli("localhost", port);
  15526. cli.enable_server_certificate_verification(false);
  15527. UploadFormDataItems items{
  15528. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15529. {"name2", "Testing456", "", ""}, // not a file
  15530. };
  15531. {
  15532. auto res = cli.Post("/post-none", {}, {}, {});
  15533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15534. ASSERT_EQ(StatusCode::OK_200, res->status);
  15535. }
  15536. FormDataProviderItems providers;
  15537. {
  15538. auto res =
  15539. cli.Post("/post-items", {}, items, providers); // empty providers
  15540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15541. ASSERT_EQ(StatusCode::OK_200, res->status);
  15542. }
  15543. providers.push_back({"name3",
  15544. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15545. // test the offset is given correctly at each step
  15546. if (!offset)
  15547. sink.os.write(rand1.data(), 30);
  15548. else if (offset == 30)
  15549. sink.os.write(rand1.data() + 30, 300);
  15550. else if (offset == 330)
  15551. sink.os.write(rand1.data() + 330, 670);
  15552. else if (offset == rand1.size())
  15553. sink.done();
  15554. return true;
  15555. },
  15556. "filename3",
  15557. {}});
  15558. providers.push_back({"name4",
  15559. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15560. // test the offset is given correctly at each step
  15561. if (!offset)
  15562. sink.os.write(rand2.data(), 2000);
  15563. else if (offset == 2000)
  15564. sink.os.write(rand2.data() + 2000, 1);
  15565. else if (offset == 2001)
  15566. sink.os.write(rand2.data() + 2001, 999);
  15567. else if (offset == rand2.size())
  15568. sink.done();
  15569. return true;
  15570. },
  15571. "filename4",
  15572. {}});
  15573. {
  15574. auto res = cli.Post("/post-providers", {}, {}, providers);
  15575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15576. ASSERT_EQ(StatusCode::OK_200, res->status);
  15577. }
  15578. {
  15579. auto res = cli.Post("/post-both", {}, items, providers);
  15580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15581. ASSERT_EQ(StatusCode::OK_200, res->status);
  15582. }
  15583. }
  15584. }
  15585. TEST(MultipartFormDataTest, BadHeader) {
  15586. Server svr;
  15587. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15588. res.set_content("ok", "text/plain");
  15589. });
  15590. thread t = thread([&] { svr.listen(HOST, PORT); });
  15591. auto se = detail::scope_exit([&] {
  15592. svr.stop();
  15593. t.join();
  15594. ASSERT_FALSE(svr.is_running());
  15595. });
  15596. svr.wait_until_ready();
  15597. const std::string body =
  15598. "This is the preamble. It is to be ignored, though it\r\n"
  15599. "is a handy place for composition agents to include an\r\n"
  15600. "explanatory note to non-MIME conformant readers.\r\n"
  15601. "\r\n"
  15602. "\r\n"
  15603. "--simple boundary\r\n"
  15604. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15605. ": BAD...\r\n"
  15606. "\r\n"
  15607. "value1\r\n"
  15608. "--simple boundary\r\n"
  15609. "Content-Disposition: form-data; name=\"field2\"; "
  15610. "filename=\"example.txt\"\r\n"
  15611. "\r\n"
  15612. "value2\r\n"
  15613. "--simple boundary--\r\n"
  15614. "This is the epilogue. It is also to be ignored.\r\n";
  15615. std::string content_type =
  15616. R"(multipart/form-data; boundary="simple boundary")";
  15617. Client cli(HOST, PORT);
  15618. auto res = cli.Post("/post", body, content_type.c_str());
  15619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15620. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15621. }
  15622. TEST(MultipartFormDataTest, WithPreamble) {
  15623. Server svr;
  15624. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15625. res.set_content("ok", "text/plain");
  15626. });
  15627. thread t = thread([&] { svr.listen(HOST, PORT); });
  15628. auto se = detail::scope_exit([&] {
  15629. svr.stop();
  15630. t.join();
  15631. ASSERT_FALSE(svr.is_running());
  15632. });
  15633. svr.wait_until_ready();
  15634. const std::string body =
  15635. "This is the preamble. It is to be ignored, though it\r\n"
  15636. "is a handy place for composition agents to include an\r\n"
  15637. "explanatory note to non-MIME conformant readers.\r\n"
  15638. "\r\n"
  15639. "\r\n"
  15640. "--simple boundary\r\n"
  15641. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15642. "\r\n"
  15643. "value1\r\n"
  15644. "--simple boundary\r\n"
  15645. "Content-Disposition: form-data; name=\"field2\"; "
  15646. "filename=\"example.txt\"\r\n"
  15647. "\r\n"
  15648. "value2\r\n"
  15649. "--simple boundary--\r\n"
  15650. "This is the epilogue. It is also to be ignored.\r\n";
  15651. std::string content_type =
  15652. R"(multipart/form-data; boundary="simple boundary")";
  15653. Client cli(HOST, PORT);
  15654. auto res = cli.Post("/post", body, content_type.c_str());
  15655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15656. EXPECT_EQ(StatusCode::OK_200, res->status);
  15657. }
  15658. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15659. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15660. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15661. const ContentReader &content_reader) {
  15662. if (req.is_multipart_form_data()) {
  15663. std::vector<FormData> items;
  15664. content_reader(
  15665. [&](const FormData &file) {
  15666. items.push_back(file);
  15667. return true;
  15668. },
  15669. [&](const char *data, size_t data_length) {
  15670. items.back().content.append(data, data_length);
  15671. return true;
  15672. });
  15673. EXPECT_TRUE(std::string(items[0].name) == "document");
  15674. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15675. EXPECT_TRUE(items[0].filename == "2MB_data");
  15676. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15677. EXPECT_TRUE(items[1].name == "hello");
  15678. EXPECT_TRUE(items[1].content == "world");
  15679. EXPECT_TRUE(items[1].filename == "");
  15680. EXPECT_TRUE(items[1].content_type == "");
  15681. } else {
  15682. std::string body;
  15683. content_reader([&](const char *data, size_t data_length) {
  15684. body.append(data, data_length);
  15685. return true;
  15686. });
  15687. }
  15688. });
  15689. auto port = svr.bind_to_any_port("localhost");
  15690. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15691. auto se = detail::scope_exit([&] {
  15692. svr.stop();
  15693. t.join();
  15694. ASSERT_FALSE(svr.is_running());
  15695. });
  15696. svr.wait_until_ready();
  15697. {
  15698. std::string data(1024 * 1024 * 2, '.');
  15699. std::stringstream buffer;
  15700. buffer << data;
  15701. SSLClient cli("localhost", port);
  15702. cli.enable_server_certificate_verification(false);
  15703. UploadFormDataItems items{
  15704. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15705. {"hello", "world", "", ""},
  15706. };
  15707. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15709. ASSERT_EQ(StatusCode::OK_200, res->status);
  15710. }
  15711. }
  15712. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15713. std::string data(1024 * 1024 * 2, '&');
  15714. std::stringstream buffer;
  15715. buffer << data;
  15716. Client cli("https://localhost:8080");
  15717. UploadFormDataItems items{
  15718. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15719. {"hello", "world", "", ""},
  15720. };
  15721. for (const char &c : " \t\r\n") {
  15722. auto res =
  15723. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15724. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15725. ASSERT_FALSE(res);
  15726. }
  15727. }
  15728. TEST(MultipartFormDataTest, PutFormData) {
  15729. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15730. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15731. const ContentReader &content_reader) {
  15732. if (req.is_multipart_form_data()) {
  15733. std::vector<FormData> items;
  15734. content_reader(
  15735. [&](const FormData &file) {
  15736. items.push_back(file);
  15737. return true;
  15738. },
  15739. [&](const char *data, size_t data_length) {
  15740. items.back().content.append(data, data_length);
  15741. return true;
  15742. });
  15743. EXPECT_TRUE(std::string(items[0].name) == "document");
  15744. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15745. EXPECT_TRUE(items[0].filename == "2MB_data");
  15746. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15747. EXPECT_TRUE(items[1].name == "hello");
  15748. EXPECT_TRUE(items[1].content == "world");
  15749. EXPECT_TRUE(items[1].filename == "");
  15750. EXPECT_TRUE(items[1].content_type == "");
  15751. } else {
  15752. std::string body;
  15753. content_reader([&](const char *data, size_t data_length) {
  15754. body.append(data, data_length);
  15755. return true;
  15756. });
  15757. }
  15758. });
  15759. auto port = svr.bind_to_any_port("localhost");
  15760. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15761. auto se = detail::scope_exit([&] {
  15762. svr.stop();
  15763. t.join();
  15764. ASSERT_FALSE(svr.is_running());
  15765. });
  15766. svr.wait_until_ready();
  15767. {
  15768. std::string data(1024 * 1024 * 2, '&');
  15769. std::stringstream buffer;
  15770. buffer << data;
  15771. SSLClient cli("localhost", port);
  15772. cli.enable_server_certificate_verification(false);
  15773. UploadFormDataItems items{
  15774. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15775. {"hello", "world", "", ""},
  15776. };
  15777. auto res = cli.Put("/put", items);
  15778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15779. ASSERT_EQ(StatusCode::OK_200, res->status);
  15780. }
  15781. }
  15782. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15783. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15784. svr.Put("/put_customboundary",
  15785. [&](const Request &req, const Response & /*res*/,
  15786. const ContentReader &content_reader) {
  15787. if (req.is_multipart_form_data()) {
  15788. std::vector<FormData> items;
  15789. content_reader(
  15790. [&](const FormData &file) {
  15791. items.push_back(file);
  15792. return true;
  15793. },
  15794. [&](const char *data, size_t data_length) {
  15795. items.back().content.append(data, data_length);
  15796. return true;
  15797. });
  15798. EXPECT_TRUE(std::string(items[0].name) == "document");
  15799. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15800. EXPECT_TRUE(items[0].filename == "2MB_data");
  15801. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15802. EXPECT_TRUE(items[1].name == "hello");
  15803. EXPECT_TRUE(items[1].content == "world");
  15804. EXPECT_TRUE(items[1].filename == "");
  15805. EXPECT_TRUE(items[1].content_type == "");
  15806. } else {
  15807. std::string body;
  15808. content_reader([&](const char *data, size_t data_length) {
  15809. body.append(data, data_length);
  15810. return true;
  15811. });
  15812. }
  15813. });
  15814. auto port = svr.bind_to_any_port("localhost");
  15815. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15816. auto se = detail::scope_exit([&] {
  15817. svr.stop();
  15818. t.join();
  15819. ASSERT_FALSE(svr.is_running());
  15820. });
  15821. svr.wait_until_ready();
  15822. {
  15823. std::string data(1024 * 1024 * 2, '&');
  15824. std::stringstream buffer;
  15825. buffer << data;
  15826. SSLClient cli("localhost", port);
  15827. cli.enable_server_certificate_verification(false);
  15828. UploadFormDataItems items{
  15829. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15830. {"hello", "world", "", ""},
  15831. };
  15832. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15834. ASSERT_EQ(StatusCode::OK_200, res->status);
  15835. }
  15836. }
  15837. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15838. std::string data(1024 * 1024 * 2, '&');
  15839. std::stringstream buffer;
  15840. buffer << data;
  15841. Client cli("https://localhost:8080");
  15842. cli.enable_server_certificate_verification(false);
  15843. UploadFormDataItems items{
  15844. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15845. {"hello", "world", "", ""},
  15846. };
  15847. for (const char &c : " \t\r\n") {
  15848. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15849. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15850. ASSERT_FALSE(res);
  15851. }
  15852. }
  15853. TEST(MultipartFormDataTest, AlternateFilename) {
  15854. auto handled = false;
  15855. Server svr;
  15856. svr.Post("/test", [&](const Request &req, Response &res) {
  15857. ASSERT_EQ(2u, req.form.files.size());
  15858. ASSERT_EQ(1u, req.form.fields.size());
  15859. // Test files
  15860. const auto &file1 = req.form.get_file("file1");
  15861. ASSERT_EQ("file1", file1.name);
  15862. ASSERT_EQ("A.txt", file1.filename);
  15863. ASSERT_EQ("text/plain", file1.content_type);
  15864. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15865. const auto &file2 = req.form.get_file("file2");
  15866. ASSERT_EQ("file2", file2.name);
  15867. ASSERT_EQ("a.html", file2.filename);
  15868. ASSERT_EQ("text/html", file2.content_type);
  15869. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15870. file2.content);
  15871. // Test text field
  15872. const auto &text = req.form.get_field("text");
  15873. ASSERT_EQ("text default", text);
  15874. res.set_content("ok", "text/plain");
  15875. handled = true;
  15876. });
  15877. thread t = thread([&] { svr.listen(HOST, PORT); });
  15878. auto se = detail::scope_exit([&] {
  15879. svr.stop();
  15880. t.join();
  15881. ASSERT_FALSE(svr.is_running());
  15882. ASSERT_TRUE(handled);
  15883. });
  15884. svr.wait_until_ready();
  15885. auto req = "POST /test HTTP/1.1\r\n"
  15886. "Host: localhost\r\n"
  15887. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15888. "Content-Length: 399\r\n"
  15889. "\r\n"
  15890. "----------\r\n"
  15891. "Content-Disposition: form-data; name=\"text\"\r\n"
  15892. "\r\n"
  15893. "text default\r\n"
  15894. "----------\r\n"
  15895. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15896. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15897. "Content-Type: text/plain\r\n"
  15898. "\r\n"
  15899. "Content of a.txt.\r\n"
  15900. "\r\n"
  15901. "----------\r\n"
  15902. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  15903. "\"a.html\"\r\n"
  15904. "Content-Type: text/html\r\n"
  15905. "\r\n"
  15906. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  15907. "\r\n"
  15908. "------------\r\n";
  15909. ASSERT_TRUE(send_request(1, req));
  15910. }
  15911. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15912. auto handled = false;
  15913. Server svr;
  15914. svr.Post("/test", [&](const Request &req, Response &res) {
  15915. // Case-insensitive "utf-8''" prefix with a long value
  15916. const auto &file = req.form.get_file("file1");
  15917. ASSERT_EQ("file1", file.name);
  15918. // 8000 chars exercises both the Content-Disposition parser and the
  15919. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15920. // Prior to the fix, std::regex_match on this header would cause O(N)
  15921. // stack recursion in libstdc++, leading to SIGSEGV.
  15922. std::string expected_filename(8000, 'A');
  15923. ASSERT_EQ(expected_filename, file.filename);
  15924. res.set_content("ok", "text/plain");
  15925. handled = true;
  15926. });
  15927. thread t = thread([&] { svr.listen(HOST, PORT); });
  15928. auto se = detail::scope_exit([&] {
  15929. svr.stop();
  15930. t.join();
  15931. ASSERT_FALSE(svr.is_running());
  15932. ASSERT_TRUE(handled);
  15933. });
  15934. svr.wait_until_ready();
  15935. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15936. // Regression test for GHSA-qq6v-r583-3h69
  15937. std::string long_filename(8000, 'A');
  15938. std::string body = "----------\r\n"
  15939. "Content-Disposition: form-data; name=\"file1\"; "
  15940. "filename*=\"Utf-8''" +
  15941. long_filename +
  15942. "\"\r\n"
  15943. "\r\n"
  15944. "hello\r\n"
  15945. "------------\r\n";
  15946. auto req = "POST /test HTTP/1.1\r\n"
  15947. "Host: localhost\r\n"
  15948. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15949. "Content-Length: " +
  15950. std::to_string(body.size()) + "\r\n\r\n" + body;
  15951. ASSERT_TRUE(send_request(1, req));
  15952. }
  15953. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15954. auto handled = false;
  15955. Server svr;
  15956. svr.Post("/test", [&](const Request &req, Response &) {
  15957. ASSERT_EQ(2u, req.form.fields.size());
  15958. const auto &text1 = req.form.get_field("text1");
  15959. ASSERT_EQ("text1", text1);
  15960. const auto &text2 = req.form.get_field("text2");
  15961. ASSERT_EQ("text2", text2);
  15962. handled = true;
  15963. });
  15964. thread t = thread([&] { svr.listen(HOST, PORT); });
  15965. auto se = detail::scope_exit([&] {
  15966. svr.stop();
  15967. t.join();
  15968. ASSERT_FALSE(svr.is_running());
  15969. ASSERT_TRUE(handled);
  15970. });
  15971. svr.wait_until_ready();
  15972. auto req = "POST /test HTTP/1.1\r\n"
  15973. "Host: localhost\r\n"
  15974. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15975. "Content-Length: 146\r\n"
  15976. "\r\n----------\r\n"
  15977. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15978. "\r\n"
  15979. "text1"
  15980. "\r\n----------\r\n"
  15981. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15982. "\r\n"
  15983. "text2"
  15984. "\r\n------------";
  15985. std::string response;
  15986. ASSERT_TRUE(send_request(1, req, &response));
  15987. ASSERT_EQ("200", response.substr(9, 3));
  15988. }
  15989. TEST(MultipartFormDataTest, ContentLength) {
  15990. auto handled = false;
  15991. Server svr;
  15992. svr.Post("/test", [&](const Request &req, Response &) {
  15993. ASSERT_EQ(2u, req.form.fields.size());
  15994. const auto &text1 = req.form.get_field("text1");
  15995. ASSERT_EQ("text1", text1);
  15996. const auto &text2 = req.form.get_field("text2");
  15997. ASSERT_EQ("text2", text2);
  15998. handled = true;
  15999. });
  16000. thread t = thread([&] { svr.listen(HOST, PORT); });
  16001. auto se = detail::scope_exit([&] {
  16002. svr.stop();
  16003. t.join();
  16004. ASSERT_FALSE(svr.is_running());
  16005. ASSERT_TRUE(handled);
  16006. });
  16007. svr.wait_until_ready();
  16008. auto req = "POST /test HTTP/1.1\r\n"
  16009. "Host: localhost\r\n"
  16010. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16011. "Content-Length: 167\r\n"
  16012. "\r\n----------\r\n"
  16013. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16014. "Content-Length: 5\r\n"
  16015. "\r\n"
  16016. "text1"
  16017. "\r\n----------\r\n"
  16018. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16019. "\r\n"
  16020. "text2"
  16021. "\r\n------------\r\n";
  16022. std::string response;
  16023. ASSERT_TRUE(send_request(1, req, &response));
  16024. ASSERT_EQ("200", response.substr(9, 3));
  16025. }
  16026. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16027. auto handled = false;
  16028. Server svr;
  16029. svr.Post("/test", [&](const Request &req, Response &) {
  16030. ASSERT_EQ(2u, req.form.fields.size());
  16031. const auto &text1 = req.form.get_field("text1");
  16032. ASSERT_EQ("text1", text1);
  16033. // TODO: Add header access for text fields if needed
  16034. const auto &text2 = req.form.get_field("text2");
  16035. ASSERT_EQ("text2", text2);
  16036. // TODO: Header access for text fields needs to be implemented
  16037. // auto &headers = it->second.headers;
  16038. // ASSERT_EQ(3U, headers.size());
  16039. // auto custom_header = headers.find("x-whatever");
  16040. // ASSERT_TRUE(custom_header != headers.end());
  16041. // ASSERT_NE("customvalue", custom_header->second);
  16042. // ASSERT_EQ("CustomValue", custom_header->second);
  16043. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16044. handled = true;
  16045. });
  16046. thread t = thread([&] { svr.listen(HOST, PORT); });
  16047. auto se = detail::scope_exit([&] {
  16048. svr.stop();
  16049. t.join();
  16050. ASSERT_FALSE(svr.is_running());
  16051. ASSERT_TRUE(handled);
  16052. });
  16053. svr.wait_until_ready();
  16054. auto req = "POST /test HTTP/1.1\r\n"
  16055. "Host: localhost\r\n"
  16056. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16057. "Content-Length: 232\r\n"
  16058. "\r\n----------\r\n"
  16059. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16060. "Content-Length: 5\r\n"
  16061. "X-Test: 1\r\n"
  16062. "\r\n"
  16063. "text1"
  16064. "\r\n----------\r\n"
  16065. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16066. "Content-Type: text/plain\r\n"
  16067. "X-Whatever: CustomValue\r\n"
  16068. "\r\n"
  16069. "text2"
  16070. "\r\n------------\r\n"
  16071. "That should be disregarded. Not even read";
  16072. std::string response;
  16073. ASSERT_TRUE(send_request(1, req, &response));
  16074. ASSERT_EQ("200", response.substr(9, 3));
  16075. }
  16076. TEST(MultipartFormDataTest, LargeHeader) {
  16077. auto handled = false;
  16078. Server svr;
  16079. svr.Post("/test", [&](const Request &req, Response &) {
  16080. ASSERT_EQ(1u, req.form.fields.size());
  16081. const auto &text = req.form.get_field("name1");
  16082. ASSERT_EQ("text1", text);
  16083. handled = true;
  16084. });
  16085. thread t = thread([&] { svr.listen(HOST, PORT); });
  16086. auto se = detail::scope_exit([&] {
  16087. svr.stop();
  16088. t.join();
  16089. ASSERT_FALSE(svr.is_running());
  16090. ASSERT_TRUE(handled);
  16091. });
  16092. svr.wait_until_ready();
  16093. auto boundary = std::string("cpp-httplib-multipart-data");
  16094. std::string content = "--" + boundary +
  16095. "\r\n"
  16096. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16097. "\r\n"
  16098. "text1\r\n"
  16099. "--" +
  16100. boundary + "--\r\n";
  16101. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16102. "Host: localhost\r\n"
  16103. "Content-Type: multipart/form-data;boundary=" +
  16104. boundary +
  16105. "\r\n"
  16106. "Content-Length: " +
  16107. std::to_string(content.size()) +
  16108. "\r\n"
  16109. "Dummy-Header: ";
  16110. std::string header_suffix = "\r\n"
  16111. "\r\n";
  16112. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16113. size_t header_dummy_size =
  16114. read_buff_size -
  16115. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16116. auto header_dummy = std::string(header_dummy_size, '@');
  16117. auto req = header_prefix + header_dummy + header_suffix + content;
  16118. std::string response;
  16119. ASSERT_TRUE(send_request(1, req, &response));
  16120. ASSERT_EQ("200", response.substr(9, 3));
  16121. }
  16122. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16123. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16124. // (not chunked Transfer-Encoding) after the streaming refactor.
  16125. auto handled = false;
  16126. Server svr;
  16127. svr.Post("/upload", [&](const Request &req, Response &res) {
  16128. auto cl_it = req.headers.find("Content-Length");
  16129. EXPECT_TRUE(cl_it != req.headers.end());
  16130. auto te_it = req.headers.find("Transfer-Encoding");
  16131. EXPECT_TRUE(te_it == req.headers.end());
  16132. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16133. res.set_content("ok", "text/plain");
  16134. handled = true;
  16135. });
  16136. auto port = svr.bind_to_any_port(HOST);
  16137. auto t = thread([&] { svr.listen_after_bind(); });
  16138. auto se = detail::scope_exit([&] {
  16139. svr.stop();
  16140. t.join();
  16141. ASSERT_FALSE(svr.is_running());
  16142. ASSERT_TRUE(handled);
  16143. });
  16144. svr.wait_until_ready();
  16145. UploadFormDataItems items = {
  16146. {"field1", "hello", "", "text/plain"},
  16147. {"file1", "world", "test.txt", "application/octet-stream"},
  16148. };
  16149. Client cli(HOST, port);
  16150. auto res = cli.Post("/upload", {}, items);
  16151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16152. EXPECT_EQ(StatusCode::OK_200, res->status);
  16153. }
  16154. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16155. // Verify that make_multipart_content_provider coalesces many small segments
  16156. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16157. constexpr size_t kItemCount = 1000;
  16158. UploadFormDataItems items;
  16159. items.reserve(kItemCount);
  16160. for (size_t i = 0; i < kItemCount; i++) {
  16161. items.push_back(
  16162. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16163. }
  16164. const std::string boundary = "----test-boundary";
  16165. auto content_length = detail::get_multipart_content_length(items, boundary);
  16166. auto provider = detail::make_multipart_content_provider(items, boundary);
  16167. // Drive the provider the same way write_content_with_progress does
  16168. size_t write_count = 0;
  16169. size_t total_bytes = 0;
  16170. DataSink sink;
  16171. size_t offset = 0;
  16172. sink.write = [&](const char *d, size_t l) -> bool {
  16173. (void)d;
  16174. write_count++;
  16175. total_bytes += l;
  16176. offset += l;
  16177. return true;
  16178. };
  16179. sink.is_writable = []() -> bool { return true; };
  16180. while (offset < content_length) {
  16181. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16182. }
  16183. EXPECT_EQ(content_length, total_bytes);
  16184. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16185. // With buffering into 64KB blocks, write_count should be much smaller.
  16186. auto segment_count = 3 * kItemCount + 1;
  16187. EXPECT_LT(write_count, segment_count / 10);
  16188. }
  16189. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16190. // Integration test: send many UploadFormDataItems and verify the server
  16191. // receives all of them correctly (#2410).
  16192. constexpr size_t kItemCount = 500;
  16193. auto handled = false;
  16194. Server svr;
  16195. svr.Post("/upload", [&](const Request &req, Response &res) {
  16196. EXPECT_EQ(kItemCount, req.form.fields.size());
  16197. for (size_t i = 0; i < kItemCount; i++) {
  16198. auto key = "field" + std::to_string(i);
  16199. auto val = "value" + std::to_string(i);
  16200. auto it = req.form.fields.find(key);
  16201. if (it != req.form.fields.end()) {
  16202. EXPECT_EQ(val, it->second.content);
  16203. } else {
  16204. ADD_FAILURE() << "Missing field: " << key;
  16205. }
  16206. }
  16207. res.set_content("ok", "text/plain");
  16208. handled = true;
  16209. });
  16210. auto port = svr.bind_to_any_port(HOST);
  16211. auto t = thread([&] { svr.listen_after_bind(); });
  16212. auto se = detail::scope_exit([&] {
  16213. svr.stop();
  16214. t.join();
  16215. ASSERT_FALSE(svr.is_running());
  16216. ASSERT_TRUE(handled);
  16217. });
  16218. svr.wait_until_ready();
  16219. UploadFormDataItems items;
  16220. items.reserve(kItemCount);
  16221. for (size_t i = 0; i < kItemCount; i++) {
  16222. items.push_back(
  16223. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16224. }
  16225. Client cli(HOST, port);
  16226. auto res = cli.Post("/upload", items);
  16227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16228. EXPECT_EQ(StatusCode::OK_200, res->status);
  16229. }
  16230. TEST(MultipartFormDataTest, MakeFileProvider) {
  16231. // Verify make_file_provider sends a file's contents correctly.
  16232. const std::string file_content(4096, 'Z');
  16233. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16234. {
  16235. std::ofstream ofs(tmp_path, std::ios::binary);
  16236. ofs.write(file_content.data(),
  16237. static_cast<std::streamsize>(file_content.size()));
  16238. }
  16239. auto handled = false;
  16240. Server svr;
  16241. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16242. const ContentReader &content_reader) {
  16243. ASSERT_TRUE(req.is_multipart_form_data());
  16244. std::vector<FormData> items;
  16245. content_reader(
  16246. [&](const FormData &file) {
  16247. items.push_back(file);
  16248. return true;
  16249. },
  16250. [&](const char *data, size_t data_length) {
  16251. items.back().content.append(data, data_length);
  16252. return true;
  16253. });
  16254. ASSERT_EQ(1u, items.size());
  16255. EXPECT_EQ("myfile", items[0].name);
  16256. EXPECT_EQ("data.bin", items[0].filename);
  16257. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16258. EXPECT_EQ(file_content, items[0].content);
  16259. handled = true;
  16260. });
  16261. auto port = svr.bind_to_any_port(HOST);
  16262. auto t = thread([&] { svr.listen_after_bind(); });
  16263. auto se = detail::scope_exit([&] {
  16264. svr.stop();
  16265. t.join();
  16266. ASSERT_FALSE(svr.is_running());
  16267. ASSERT_TRUE(handled);
  16268. std::remove(tmp_path.c_str());
  16269. });
  16270. svr.wait_until_ready();
  16271. FormDataProviderItems providers;
  16272. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16273. "application/octet-stream"));
  16274. Client cli(HOST, port);
  16275. auto res = cli.Post("/upload", {}, {}, providers);
  16276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16277. EXPECT_EQ(StatusCode::OK_200, res->status);
  16278. }
  16279. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16280. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16281. // (100) headers is rejected with a 400 Bad Request response.
  16282. Server svr;
  16283. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16284. res.set_content("ok", "text/plain");
  16285. });
  16286. thread t = thread([&] { svr.listen(HOST, PORT); });
  16287. auto se = detail::scope_exit([&] {
  16288. svr.stop();
  16289. t.join();
  16290. ASSERT_FALSE(svr.is_running());
  16291. });
  16292. svr.wait_until_ready();
  16293. // Build a multipart part with 101 custom headers (exceeding
  16294. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16295. std::stringstream body;
  16296. body << "--simpleboundary\r\n"
  16297. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16298. for (int i = 0; i < 101; i++) {
  16299. body << "X-Custom-Header-" << i << ": value\r\n";
  16300. }
  16301. body << "\r\n"
  16302. << "value1\r\n"
  16303. << "--simpleboundary--\r\n";
  16304. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16305. Client cli(HOST, PORT);
  16306. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16308. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16309. }
  16310. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16311. // A body that never contains the declared boundary must not be accumulated
  16312. // while the parser waits for it. Buffering it would also make every read
  16313. // rescan everything seen so far, which is quadratic in the body size.
  16314. Server svr;
  16315. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16316. res.set_content("ok", "text/plain");
  16317. });
  16318. auto port = svr.bind_to_any_port(HOST);
  16319. thread t = thread([&] { svr.listen_after_bind(); });
  16320. auto se = detail::scope_exit([&] {
  16321. svr.stop();
  16322. t.join();
  16323. ASSERT_FALSE(svr.is_running());
  16324. });
  16325. svr.wait_until_ready();
  16326. Client cli(HOST, port);
  16327. cli.set_read_timeout(60, 0);
  16328. cli.set_write_timeout(60, 0);
  16329. // '-' is the worst case: it matches the first character of the boundary, so
  16330. // every position has to be checked against it.
  16331. auto post_dashes = [&](size_t size) {
  16332. const std::string body(size, '-');
  16333. auto start = std::chrono::steady_clock::now();
  16334. auto res =
  16335. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16336. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16337. std::chrono::steady_clock::now() - start)
  16338. .count();
  16339. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16340. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16341. return ms;
  16342. };
  16343. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16344. // Windows.
  16345. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16346. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16347. // Comparing the two sizes rather than checking an absolute duration keeps
  16348. // this meaningful across build types and CI load, both of which move the
  16349. // absolute numbers by more than an order of magnitude. Four times the bytes
  16350. // costs about four times the time when parsing is linear, and about sixteen
  16351. // times when the body is buffered and rescanned.
  16352. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16353. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16354. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16355. << "ms, which suggests the body is being buffered and rescanned";
  16356. }
  16357. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16358. // A boundary can only be followed by CRLF or by "--", so anything else is
  16359. // malformed no matter what comes next. The parser must say so right away
  16360. // instead of buffering the rest of the declared body.
  16361. Server svr;
  16362. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16363. res.set_content("ok", "text/plain");
  16364. });
  16365. auto port = svr.bind_to_any_port(HOST);
  16366. thread t = thread([&] { svr.listen_after_bind(); });
  16367. auto se = detail::scope_exit([&] {
  16368. svr.stop();
  16369. t.join();
  16370. ASSERT_FALSE(svr.is_running());
  16371. });
  16372. svr.wait_until_ready();
  16373. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16374. // buffers instead of failing would still be waiting for the remaining bytes.
  16375. const std::string body = "--zzzz\r\n"
  16376. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16377. "\r\n"
  16378. "text1"
  16379. "\r\n--zzzzXX";
  16380. const std::string req = "POST /post HTTP/1.1\r\n"
  16381. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16382. "Content-Length: 1048576\r\n"
  16383. "\r\n" +
  16384. body;
  16385. std::string response;
  16386. ASSERT_TRUE(send_request(3, req, &response, port));
  16387. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16388. EXPECT_EQ("400", response.substr(9, 3));
  16389. }
  16390. // Posts a multipart body split into two writes, so that the server sees the
  16391. // split at whatever offset the caller chose, and expects the single "text1"
  16392. // field to come through.
  16393. static void expect_split_multipart_ok(const std::string &body1,
  16394. const std::string &body2) {
  16395. auto handled = false;
  16396. Server svr;
  16397. svr.Post("/post", [&](const Request &req, Response &) {
  16398. EXPECT_EQ(1u, req.form.fields.size());
  16399. EXPECT_EQ("text1", req.form.get_field("text1"));
  16400. handled = true;
  16401. });
  16402. auto port = svr.bind_to_any_port(HOST);
  16403. thread t = thread([&] { svr.listen_after_bind(); });
  16404. auto se = detail::scope_exit([&] {
  16405. svr.stop();
  16406. t.join();
  16407. ASSERT_FALSE(svr.is_running());
  16408. ASSERT_TRUE(handled);
  16409. });
  16410. svr.wait_until_ready();
  16411. // "Connection: close" makes the server close once it has answered, so the
  16412. // response drain ends immediately instead of idling until the read timeout.
  16413. const std::string head =
  16414. "POST /post HTTP/1.1\r\n"
  16415. "Host: localhost\r\n"
  16416. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16417. "Connection: close\r\n"
  16418. "Content-Length: " +
  16419. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16420. std::string response;
  16421. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16422. ASSERT_GE(response.size(), 12u) << "no response";
  16423. EXPECT_EQ("200", response.substr(9, 3));
  16424. }
  16425. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16426. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16427. // ignored, including when it does not arrive in the same read as the
  16428. // close-delimiter itself.
  16429. expect_split_multipart_ok("--zzzz\r\n"
  16430. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16431. "\r\n"
  16432. "text1"
  16433. "\r\n--zzzz--",
  16434. "\r\nthis epilogue must be ignored\r\n");
  16435. }
  16436. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16437. // The initial boundary may be preceded by a preamble of any length and may
  16438. // straddle a read boundary. Discarding data while waiting for it must not
  16439. // throw away a partial boundary sitting at the end of the buffer.
  16440. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16441. "zz\r\n"
  16442. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16443. "\r\n"
  16444. "text1"
  16445. "\r\n--zzzz--\r\n");
  16446. }
  16447. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16448. // The received boundary was only checked for being non-empty, so it could be
  16449. // as long as a header is allowed to be. The parser scans the body for
  16450. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16451. // costs a nearly full comparison at nearly every position, making the
  16452. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16453. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16454. Server svr;
  16455. svr.Post("/post", [](const Request &req, Response &res) {
  16456. EXPECT_EQ(1u, req.form.fields.size());
  16457. EXPECT_EQ("text1", req.form.get_field("text1"));
  16458. res.set_content("ok", "text/plain");
  16459. });
  16460. auto port = svr.bind_to_any_port(HOST);
  16461. thread t = thread([&] { svr.listen_after_bind(); });
  16462. auto se = detail::scope_exit([&] {
  16463. svr.stop();
  16464. t.join();
  16465. ASSERT_FALSE(svr.is_running());
  16466. });
  16467. svr.wait_until_ready();
  16468. Client cli(HOST, port);
  16469. auto post_with_boundary_of_length = [&](size_t len) {
  16470. const std::string boundary(len, 'a');
  16471. const std::string body =
  16472. "--" + boundary +
  16473. "\r\n"
  16474. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16475. "\r\n"
  16476. "text1"
  16477. "\r\n--" +
  16478. boundary + "--\r\n";
  16479. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16480. };
  16481. auto res = post_with_boundary_of_length(70);
  16482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16483. EXPECT_EQ(StatusCode::OK_200, res->status);
  16484. res = post_with_boundary_of_length(71);
  16485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16486. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16487. }
  16488. TEST(MakeFileBodyTest, Basic) {
  16489. const std::string file_content(4096, 'Z');
  16490. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16491. {
  16492. std::ofstream ofs(tmp_path, std::ios::binary);
  16493. ofs.write(file_content.data(),
  16494. static_cast<std::streamsize>(file_content.size()));
  16495. }
  16496. auto handled = false;
  16497. Server svr;
  16498. svr.Post("/upload", [&](const Request &req, Response &res) {
  16499. EXPECT_EQ(file_content, req.body);
  16500. handled = true;
  16501. res.status = StatusCode::OK_200;
  16502. });
  16503. auto port = svr.bind_to_any_port(HOST);
  16504. auto t = thread([&] { svr.listen_after_bind(); });
  16505. auto se = detail::scope_exit([&] {
  16506. svr.stop();
  16507. t.join();
  16508. ASSERT_FALSE(svr.is_running());
  16509. ASSERT_TRUE(handled);
  16510. std::remove(tmp_path.c_str());
  16511. });
  16512. svr.wait_until_ready();
  16513. auto fb = make_file_body(tmp_path);
  16514. ASSERT_GT(fb.first, 0u);
  16515. Client cli(HOST, port);
  16516. auto res =
  16517. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16519. EXPECT_EQ(StatusCode::OK_200, res->status);
  16520. }
  16521. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16522. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16523. {
  16524. std::ofstream ofs(path, std::ios::binary);
  16525. const std::string content(100, 'A');
  16526. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16527. }
  16528. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16529. auto body = make_file_body(path);
  16530. ASSERT_EQ(100u, body.first);
  16531. ASSERT_TRUE(static_cast<bool>(body.second));
  16532. // Rewritten shorter after its length was measured - and, on a server, after
  16533. // that length has already gone out as Content-Length.
  16534. {
  16535. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16536. const std::string content(10, 'A');
  16537. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16538. }
  16539. std::string written;
  16540. DataSink sink;
  16541. sink.write = [&](const char *d, size_t l) {
  16542. written.append(d, l);
  16543. return true;
  16544. };
  16545. // The provider has to report failure. write_content_with_progress() advances
  16546. // its offset only by what was written, so a provider that returns true
  16547. // without completing the length it promised is called again straight away,
  16548. // and again.
  16549. EXPECT_FALSE(body.second(0, body.first, sink));
  16550. EXPECT_EQ(std::string(10, 'A'), written);
  16551. }
  16552. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16553. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16554. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16555. {
  16556. std::ofstream ofs(path, std::ios::binary);
  16557. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16558. }
  16559. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16560. auto body = make_file_body(path);
  16561. ASSERT_EQ(content.size(), body.first);
  16562. ASSERT_TRUE(static_cast<bool>(body.second));
  16563. std::string written;
  16564. DataSink sink;
  16565. sink.write = [&](const char *d, size_t l) {
  16566. written.append(d, l);
  16567. return true;
  16568. };
  16569. EXPECT_TRUE(body.second(0, body.first, sink));
  16570. EXPECT_EQ(content, written);
  16571. }
  16572. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16573. static constexpr unsigned int number_of_tasks{1000000};
  16574. std::atomic_uint count{0};
  16575. std::unique_ptr<TaskQueue> task_queue{
  16576. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16577. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16578. auto queued = task_queue->enqueue(
  16579. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16580. EXPECT_TRUE(queued);
  16581. }
  16582. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16583. task_queue->shutdown();
  16584. #else
  16585. EXPECT_NO_THROW(task_queue->shutdown());
  16586. #endif
  16587. EXPECT_EQ(number_of_tasks, count.load());
  16588. }
  16589. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16590. static constexpr unsigned int number_of_tasks{1000000};
  16591. static constexpr unsigned int qlimit{2};
  16592. unsigned int queued_count{0};
  16593. std::atomic_uint count{0};
  16594. std::unique_ptr<TaskQueue> task_queue{
  16595. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16596. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16597. if (task_queue->enqueue(
  16598. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16599. queued_count++;
  16600. }
  16601. }
  16602. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16603. task_queue->shutdown();
  16604. #else
  16605. EXPECT_NO_THROW(task_queue->shutdown());
  16606. #endif
  16607. EXPECT_EQ(queued_count, count.load());
  16608. EXPECT_TRUE(queued_count <= number_of_tasks);
  16609. EXPECT_TRUE(queued_count >= qlimit);
  16610. }
  16611. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16612. // Use a short idle timeout so a dynamic thread spawns, times out and
  16613. // exits during the test, and the pool keeps working afterwards.
  16614. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16615. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16616. /*idle_timeout_sec=*/1}};
  16617. std::atomic_uint count{0};
  16618. std::condition_variable cv;
  16619. std::mutex mtx;
  16620. bool release = false;
  16621. // Block the base thread so the second task spawns a dynamic thread.
  16622. EXPECT_TRUE(task_queue->enqueue([&] {
  16623. std::unique_lock<std::mutex> lock(mtx);
  16624. while (!release) {
  16625. cv.wait(lock);
  16626. }
  16627. count++;
  16628. }));
  16629. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16630. // Let the dynamic thread finish its task and exceed the idle timeout.
  16631. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16632. {
  16633. std::unique_lock<std::mutex> lock(mtx);
  16634. release = true;
  16635. }
  16636. cv.notify_all();
  16637. // The pool must still accept and run tasks after the dynamic thread exited.
  16638. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16639. task_queue->shutdown();
  16640. EXPECT_EQ(3u, count.load());
  16641. }
  16642. TEST(TaskQueueTest, MaxQueuedRequests) {
  16643. static constexpr unsigned int qlimit{3};
  16644. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16645. std::condition_variable sem_cv;
  16646. std::mutex sem_mtx;
  16647. int credits = 0;
  16648. bool queued;
  16649. /* Fill up the queue with tasks that will block until we give them credits to
  16650. * complete. */
  16651. for (unsigned int n = 0; n <= qlimit;) {
  16652. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16653. std::unique_lock<std::mutex> lock(sem_mtx);
  16654. while (credits <= 0) {
  16655. sem_cv.wait(lock);
  16656. }
  16657. /* Consume the credit and signal the test code if they are all gone. */
  16658. if (--credits == 0) { sem_cv.notify_one(); }
  16659. });
  16660. if (n < qlimit) {
  16661. /* The first qlimit enqueues must succeed. */
  16662. EXPECT_TRUE(queued);
  16663. } else {
  16664. /* The last one will succeed only when the worker thread
  16665. * starts and dequeues the first blocking task. Although
  16666. * not necessary for the correctness of this test, we sleep for
  16667. * a short while to avoid busy waiting. */
  16668. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16669. }
  16670. if (queued) { n++; }
  16671. }
  16672. /* Further enqueues must fail since the queue is full. */
  16673. for (auto i = 0; i < 4; i++) {
  16674. queued = task_queue->enqueue([] {});
  16675. EXPECT_FALSE(queued);
  16676. }
  16677. /* Give the credits to allow the previous tasks to complete. */
  16678. {
  16679. std::unique_lock<std::mutex> lock(sem_mtx);
  16680. credits += qlimit + 1;
  16681. }
  16682. sem_cv.notify_all();
  16683. /* Wait for all the credits to be consumed. */
  16684. {
  16685. std::unique_lock<std::mutex> lock(sem_mtx);
  16686. while (credits > 0) {
  16687. sem_cv.wait(lock);
  16688. }
  16689. }
  16690. /* Check that we are able again to enqueue at least qlimit tasks. */
  16691. for (unsigned int i = 0; i < qlimit; i++) {
  16692. queued = task_queue->enqueue([] {});
  16693. EXPECT_TRUE(queued);
  16694. }
  16695. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16696. task_queue->shutdown();
  16697. #else
  16698. EXPECT_NO_THROW(task_queue->shutdown());
  16699. #endif
  16700. }
  16701. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16702. Server svr;
  16703. std::string method;
  16704. std::string body;
  16705. auto has_content_length = false;
  16706. auto has_transfer_encoding = false;
  16707. std::atomic<int> bad_requests{0};
  16708. // Leftover body bytes get parsed as a malformed request and answered with
  16709. // 400
  16710. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16711. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16712. });
  16713. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16714. res.set_redirect("/down", StatusCode::SeeOther_303);
  16715. });
  16716. svr.Get("/down", [&](const Request &req, Response &res) {
  16717. method = req.method;
  16718. body = req.body;
  16719. has_content_length = req.has_header("Content-Length");
  16720. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16721. res.set_content("ok", "text/plain");
  16722. });
  16723. auto port = svr.bind_to_any_port(HOST);
  16724. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16725. auto se = detail::scope_exit([&] {
  16726. svr.stop();
  16727. thread.join();
  16728. ASSERT_FALSE(svr.is_running());
  16729. });
  16730. svr.wait_until_ready();
  16731. const std::string payload = "SECRET-BODY";
  16732. auto check = [&](Client &cli, const Result &res) {
  16733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16734. EXPECT_EQ(StatusCode::OK_200, res->status);
  16735. EXPECT_EQ("ok", res->body);
  16736. EXPECT_EQ("GET", method);
  16737. EXPECT_TRUE(body.empty());
  16738. EXPECT_FALSE(has_content_length);
  16739. EXPECT_FALSE(has_transfer_encoding);
  16740. // Nothing of the original body may be left on the connection
  16741. auto res2 = cli.Get("/down");
  16742. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16743. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16744. EXPECT_EQ("ok", res2->body);
  16745. EXPECT_EQ(0, bad_requests);
  16746. };
  16747. // With content length
  16748. {
  16749. Client cli(HOST, port);
  16750. cli.set_keep_alive(true);
  16751. cli.set_follow_location(true);
  16752. auto res = cli.Post(
  16753. "/up", payload.size(),
  16754. [&](size_t offset, size_t length, DataSink &sink) {
  16755. return sink.write(payload.data() + offset, length);
  16756. },
  16757. "text/plain");
  16758. check(cli, res);
  16759. }
  16760. // Without content length (chunked)
  16761. {
  16762. Client cli(HOST, port);
  16763. cli.set_keep_alive(true);
  16764. cli.set_follow_location(true);
  16765. auto res = cli.Post(
  16766. "/up",
  16767. [&](size_t /*offset*/, DataSink &sink) {
  16768. sink.write(payload.data(), payload.size());
  16769. sink.done();
  16770. return true;
  16771. },
  16772. "text/plain");
  16773. check(cli, res);
  16774. }
  16775. }
  16776. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16777. Server svr;
  16778. std::string target;
  16779. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16780. // Echo the still-encoded name back in the Location
  16781. const std::string prefix = "/start/";
  16782. res.status = StatusCode::Found_302;
  16783. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16784. });
  16785. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16786. target = req.target;
  16787. res.set_content("ok", "text/plain");
  16788. });
  16789. auto port = svr.bind_to_any_port(HOST);
  16790. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16791. auto se = detail::scope_exit([&] {
  16792. svr.stop();
  16793. thread.join();
  16794. ASSERT_FALSE(svr.is_running());
  16795. });
  16796. svr.wait_until_ready();
  16797. // Decoding the Location path would turn the first four into a path
  16798. // separator, a query delimiter, a fragment delimiter and a different
  16799. // percent-encoded octet. The rest must keep reaching the server as they are.
  16800. const std::vector<std::string> names = {
  16801. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16802. };
  16803. for (auto path_encode : {true, false}) {
  16804. Client cli(HOST, port);
  16805. cli.set_follow_location(true);
  16806. cli.set_path_encode(path_encode);
  16807. for (const auto &name : names) {
  16808. target.clear();
  16809. auto res = cli.Get("/start/" + name);
  16810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16811. EXPECT_EQ(StatusCode::OK_200, res->status);
  16812. EXPECT_EQ("/dest/" + name, target);
  16813. }
  16814. }
  16815. }
  16816. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  16817. Server svr;
  16818. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16819. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  16820. });
  16821. svr.Get("/hello", [](const Request &req, Response &res) {
  16822. res.set_content(req.get_param_value("key"), "text/plain");
  16823. });
  16824. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16825. auto se = detail::scope_exit([&] {
  16826. svr.stop();
  16827. thread.join();
  16828. ASSERT_FALSE(svr.is_running());
  16829. });
  16830. svr.wait_until_ready();
  16831. {
  16832. Client cli(HOST, PORT);
  16833. cli.set_follow_location(true);
  16834. auto res = cli.Get("/");
  16835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16836. EXPECT_EQ(StatusCode::OK_200, res->status);
  16837. EXPECT_EQ("val&key2=val2", res->body);
  16838. }
  16839. }
  16840. #endif
  16841. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  16842. Server svr;
  16843. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16844. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  16845. });
  16846. svr.Get("/hello", [](const Request &req, Response &res) {
  16847. res.set_content(req.get_param_value("key"), "text/plain");
  16848. });
  16849. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16850. auto se = detail::scope_exit([&] {
  16851. svr.stop();
  16852. thread.join();
  16853. ASSERT_FALSE(svr.is_running());
  16854. });
  16855. svr.wait_until_ready();
  16856. {
  16857. Client cli(HOST, PORT);
  16858. cli.set_follow_location(true);
  16859. auto res = cli.Get("/");
  16860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16861. EXPECT_EQ(StatusCode::OK_200, res->status);
  16862. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  16863. }
  16864. }
  16865. TEST(RedirectTest, RedirectWithPlusInPath) {
  16866. Server svr;
  16867. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16868. res.set_redirect("/a+b");
  16869. });
  16870. // Route pattern uses regex; escape + as \\+
  16871. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  16872. res.set_content(req.path, "text/plain");
  16873. });
  16874. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16875. auto se = detail::scope_exit([&] {
  16876. svr.stop();
  16877. thread.join();
  16878. ASSERT_FALSE(svr.is_running());
  16879. });
  16880. svr.wait_until_ready();
  16881. {
  16882. Client cli(HOST, PORT);
  16883. cli.set_follow_location(true);
  16884. auto res = cli.Get("/");
  16885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16886. EXPECT_EQ(StatusCode::OK_200, res->status);
  16887. EXPECT_EQ("/a+b", res->body);
  16888. }
  16889. }
  16890. TEST(RedirectTest, ResolveRelativeLocation) {
  16891. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  16892. const std::vector<std::pair<std::string, std::string>> cases = {
  16893. {"g", "/b/c/g"},
  16894. {"./g", "/b/c/g"},
  16895. {"g/", "/b/c/g/"},
  16896. {"?y", "/b/c/d;p?y"},
  16897. {"g?y", "/b/c/g?y"},
  16898. {"#s", "/b/c/d;p?q#s"},
  16899. {"g#s", "/b/c/g#s"},
  16900. {"g?y#s", "/b/c/g?y#s"},
  16901. {";x", "/b/c/;x"},
  16902. {"g;x", "/b/c/g;x"},
  16903. {".", "/b/c/"},
  16904. {"./", "/b/c/"},
  16905. {"..", "/b/"},
  16906. {"../", "/b/"},
  16907. {"../g", "/b/g"},
  16908. {"../..", "/"},
  16909. {"../../", "/"},
  16910. {"../../g", "/g"},
  16911. {"../../../g", "/g"},
  16912. {"g.", "/b/c/g."},
  16913. {".g", "/b/c/.g"},
  16914. {"g..", "/b/c/g.."},
  16915. {"..g", "/b/c/..g"},
  16916. {"./../g", "/b/g"},
  16917. {"./g/.", "/b/c/g/"},
  16918. {"g/./h", "/b/c/g/h"},
  16919. {"g/../h", "/b/c/h"},
  16920. {"g;x=1/./y", "/b/c/g;x=1/y"},
  16921. {"g;x=1/../y", "/b/c/y"},
  16922. {"g?y/./x", "/b/c/g?y/./x"},
  16923. {"g#s/../x", "/b/c/g#s/../x"},
  16924. // Not relative-path references, so left for parse_url.
  16925. {"/g", "/g"},
  16926. {"//g", "//g"},
  16927. {"http://g/x", "http://g/x"},
  16928. {"g:h", "g:h"},
  16929. };
  16930. for (const auto &c : cases) {
  16931. EXPECT_EQ(c.second,
  16932. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  16933. << c.first;
  16934. }
  16935. }
  16936. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  16937. Server svr;
  16938. svr.Get("/dir/page", [](const Request &req, Response &res) {
  16939. res.set_redirect(req.get_param_value("to"));
  16940. });
  16941. svr.Get("/dir/next", [](const Request &req, Response &res) {
  16942. res.set_content(req.target, "text/plain");
  16943. });
  16944. svr.Get("/other", [](const Request &req, Response &res) {
  16945. res.set_content(req.target, "text/plain");
  16946. });
  16947. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16948. auto se = detail::scope_exit([&] {
  16949. svr.stop();
  16950. thread.join();
  16951. ASSERT_FALSE(svr.is_running());
  16952. });
  16953. svr.wait_until_ready();
  16954. const std::vector<std::pair<std::string, std::string>> cases = {
  16955. {"next", "/dir/next"},
  16956. {"./next?x=1", "/dir/next?x=1"},
  16957. {"../other", "/other"},
  16958. };
  16959. for (const auto &c : cases) {
  16960. Client cli(HOST, PORT);
  16961. cli.set_follow_location(true);
  16962. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  16963. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  16964. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16965. EXPECT_EQ(c.second, res->body) << c.first;
  16966. }
  16967. }
  16968. #ifdef CPPHTTPLIB_SSL_ENABLED
  16969. TEST(RedirectTest, Issue2185_Online) {
  16970. SSLClient client("github.com");
  16971. client.set_follow_location(true);
  16972. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16973. "Coollab-Windows.zip");
  16974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16975. EXPECT_EQ(StatusCode::OK_200, res->status);
  16976. EXPECT_EQ(9920427U, res->body.size());
  16977. }
  16978. #endif
  16979. TEST(VulnerabilityTest, CRLFInjection) {
  16980. Server svr;
  16981. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16982. res.set_content("Hello 1", "text/plain");
  16983. });
  16984. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16985. res.set_content("Hello 2", "text/plain");
  16986. });
  16987. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16988. res.set_content("Hello 3", "text/plain");
  16989. });
  16990. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16991. res.set_content("Hello 4", "text/plain");
  16992. });
  16993. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16994. for (const auto &x : req.headers) {
  16995. auto key = x.first;
  16996. EXPECT_STRNE("evil", key.c_str());
  16997. }
  16998. });
  16999. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17000. auto se = detail::scope_exit([&] {
  17001. svr.stop();
  17002. thread.join();
  17003. ASSERT_FALSE(svr.is_running());
  17004. });
  17005. svr.wait_until_ready();
  17006. {
  17007. Client cli(HOST, PORT);
  17008. cli.Post("/test1", "A=B",
  17009. "application/x-www-form-urlencoded\r\nevil: hello1");
  17010. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17011. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17012. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17013. }
  17014. }
  17015. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17016. auto server_thread = std::thread([] {
  17017. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17018. default_socket_options(srv);
  17019. sockaddr_in addr{};
  17020. addr.sin_family = AF_INET;
  17021. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17022. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17023. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17024. ::listen(srv, 1);
  17025. sockaddr_in cli_addr{};
  17026. socklen_t cli_len = sizeof(cli_addr);
  17027. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17028. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17029. std::string buf_all;
  17030. char buf[2048];
  17031. ssize_t n;
  17032. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17033. buf_all.append(buf, static_cast<size_t>(n));
  17034. size_t pos;
  17035. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17036. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17037. auto e = request_block.find("\r\n");
  17038. if (e != std::string::npos) {
  17039. auto request_line = request_block.substr(0, e);
  17040. std::string msg =
  17041. "CRLF injection detected in request line: '" + request_line + "'";
  17042. EXPECT_FALSE(true) << msg;
  17043. }
  17044. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17045. ::send(cli,
  17046. #ifdef _WIN32
  17047. static_cast<const char *>(resp.c_str()),
  17048. static_cast<int>(resp.size()),
  17049. #else
  17050. resp.c_str(), resp.size(),
  17051. #endif
  17052. 0);
  17053. buf_all.erase(0, pos + 4);
  17054. }
  17055. }
  17056. detail::close_socket(cli);
  17057. detail::close_socket(srv);
  17058. });
  17059. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17060. auto cli = Client("127.0.0.1", PORT + 1);
  17061. auto headers = Headers{
  17062. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17063. {"Connection", "keep-alive"}};
  17064. auto res = cli.Get("/hi", headers);
  17065. EXPECT_FALSE(res);
  17066. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17067. server_thread.join();
  17068. }
  17069. // A request rejected before any byte reaches the socket must fail right away
  17070. // instead of waiting for a response the server will never send.
  17071. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17072. // The kernel completes the TCP handshake from the listen backlog, so the
  17073. // client connects, but nothing ever reads, responds or closes.
  17074. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17075. default_socket_options(srv);
  17076. sockaddr_in addr{};
  17077. addr.sin_family = AF_INET;
  17078. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17079. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17080. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17081. ASSERT_EQ(0, ::listen(srv, 8));
  17082. auto cli = Client("127.0.0.1", PORT + 1);
  17083. cli.set_read_timeout(10, 0);
  17084. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17085. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17086. std::chrono::steady_clock::now() - start)
  17087. .count();
  17088. };
  17089. {
  17090. Request req;
  17091. req.method = "GE T";
  17092. req.path = "/";
  17093. auto start = std::chrono::steady_clock::now();
  17094. auto res = cli.send(req);
  17095. EXPECT_FALSE(res);
  17096. EXPECT_EQ(Error::Write, res.error());
  17097. EXPECT_LT(elapsed_ms(start), 1000);
  17098. }
  17099. {
  17100. auto start = std::chrono::steady_clock::now();
  17101. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17102. EXPECT_FALSE(res);
  17103. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17104. EXPECT_LT(elapsed_ms(start), 1000);
  17105. }
  17106. EXPECT_FALSE(cli.is_socket_open());
  17107. detail::close_socket(srv);
  17108. }
  17109. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17110. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17111. default_socket_options(srv);
  17112. sockaddr_in addr{};
  17113. addr.sin_family = AF_INET;
  17114. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17115. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17116. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17117. ASSERT_EQ(0, ::listen(srv, 1));
  17118. std::string received;
  17119. auto server_thread = std::thread([&] {
  17120. auto sock = ::accept(srv, nullptr, nullptr);
  17121. if (sock == INVALID_SOCKET) { return; }
  17122. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17123. char buf[2048];
  17124. ssize_t n;
  17125. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17126. received.append(buf, static_cast<size_t>(n));
  17127. }
  17128. detail::close_socket(sock);
  17129. });
  17130. {
  17131. auto cli = Client("127.0.0.1", PORT + 1);
  17132. // "Z" sorts after the default headers, so writing straight to the socket
  17133. // would have sent the request line and those headers before the rejection.
  17134. auto handle =
  17135. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17136. EXPECT_FALSE(handle.is_valid());
  17137. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17138. }
  17139. server_thread.join();
  17140. detail::close_socket(srv);
  17141. EXPECT_TRUE(received.empty()) << received;
  17142. }
  17143. TEST(PathParamsTest, StaticMatch) {
  17144. const auto pattern = "/users/all";
  17145. detail::PathParamsMatcher matcher(pattern);
  17146. Request request;
  17147. request.path = "/users/all";
  17148. ASSERT_TRUE(matcher.match(request));
  17149. std::unordered_map<std::string, std::string> expected_params = {};
  17150. EXPECT_EQ(request.path_params, expected_params);
  17151. }
  17152. TEST(PathParamsTest, StaticMismatch) {
  17153. const auto pattern = "/users/all";
  17154. detail::PathParamsMatcher matcher(pattern);
  17155. Request request;
  17156. request.path = "/users/1";
  17157. ASSERT_FALSE(matcher.match(request));
  17158. }
  17159. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17160. const auto pattern = "/users/:id/subscriptions";
  17161. detail::PathParamsMatcher matcher(pattern);
  17162. Request request;
  17163. request.path = "/users/42/subscriptions";
  17164. ASSERT_TRUE(matcher.match(request));
  17165. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17166. EXPECT_EQ(request.path_params, expected_params);
  17167. }
  17168. TEST(PathParamsTest, SingleParamInTheEnd) {
  17169. const auto pattern = "/users/:id";
  17170. detail::PathParamsMatcher matcher(pattern);
  17171. Request request;
  17172. request.path = "/users/24";
  17173. ASSERT_TRUE(matcher.match(request));
  17174. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17175. EXPECT_EQ(request.path_params, expected_params);
  17176. }
  17177. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17178. const auto pattern = "/users/:id/";
  17179. detail::PathParamsMatcher matcher(pattern);
  17180. Request request;
  17181. request.path = "/users/42/";
  17182. ASSERT_TRUE(matcher.match(request));
  17183. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17184. EXPECT_EQ(request.path_params, expected_params);
  17185. }
  17186. TEST(PathParamsTest, EmptyParam) {
  17187. const auto pattern = "/users/:id/";
  17188. detail::PathParamsMatcher matcher(pattern);
  17189. Request request;
  17190. request.path = "/users//";
  17191. ASSERT_TRUE(matcher.match(request));
  17192. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17193. EXPECT_EQ(request.path_params, expected_params);
  17194. }
  17195. TEST(PathParamsTest, FragmentMismatch) {
  17196. const auto pattern = "/users/:id/";
  17197. detail::PathParamsMatcher matcher(pattern);
  17198. Request request;
  17199. request.path = "/admins/24/";
  17200. ASSERT_FALSE(matcher.match(request));
  17201. }
  17202. TEST(PathParamsTest, ExtraFragments) {
  17203. const auto pattern = "/users/:id";
  17204. detail::PathParamsMatcher matcher(pattern);
  17205. Request request;
  17206. request.path = "/users/42/subscriptions";
  17207. ASSERT_FALSE(matcher.match(request));
  17208. }
  17209. TEST(PathParamsTest, MissingTrailingParam) {
  17210. const auto pattern = "/users/:id";
  17211. detail::PathParamsMatcher matcher(pattern);
  17212. Request request;
  17213. request.path = "/users";
  17214. ASSERT_FALSE(matcher.match(request));
  17215. }
  17216. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17217. const auto pattern = "/users/:id/subscriptions";
  17218. detail::PathParamsMatcher matcher(pattern);
  17219. Request request;
  17220. request.path = "/users/subscriptions";
  17221. ASSERT_FALSE(matcher.match(request));
  17222. }
  17223. TEST(PathParamsTest, MultipleParams) {
  17224. const auto pattern = "/users/:userid/subscriptions/:subid";
  17225. detail::PathParamsMatcher matcher(pattern);
  17226. Request request;
  17227. request.path = "/users/42/subscriptions/2";
  17228. ASSERT_TRUE(matcher.match(request));
  17229. std::unordered_map<std::string, std::string> expected_params = {
  17230. {"userid", "42"}, {"subid", "2"}};
  17231. EXPECT_EQ(request.path_params, expected_params);
  17232. }
  17233. TEST(PathParamsTest, SequenceOfParams) {
  17234. const auto pattern = "/values/:x/:y/:z";
  17235. detail::PathParamsMatcher matcher(pattern);
  17236. Request request;
  17237. request.path = "/values/1/2/3";
  17238. ASSERT_TRUE(matcher.match(request));
  17239. std::unordered_map<std::string, std::string> expected_params = {
  17240. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17241. EXPECT_EQ(request.path_params, expected_params);
  17242. }
  17243. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17244. const auto pattern = "/prefix:suffix";
  17245. detail::PathParamsMatcher matcher(pattern);
  17246. Request request;
  17247. request.path = "/prefix:suffix";
  17248. ASSERT_TRUE(matcher.match(request));
  17249. const std::unordered_map<std::string, std::string> expected_params = {};
  17250. EXPECT_EQ(request.path_params, expected_params);
  17251. }
  17252. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17253. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17254. // calling thread's stack on a long enough path for a quantified pattern;
  17255. // RegexMatcher must refuse to run regex matching on paths beyond
  17256. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17257. detail::RegexMatcher matcher("/files/(.*)");
  17258. Request within_limit;
  17259. within_limit.path = "/files/" + std::string(10, 'A');
  17260. EXPECT_TRUE(matcher.match(within_limit));
  17261. Request over_limit;
  17262. over_limit.path =
  17263. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17264. EXPECT_FALSE(matcher.match(over_limit));
  17265. }
  17266. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17267. Server svr;
  17268. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17269. res.set_content("ok", "text/plain");
  17270. });
  17271. auto port = svr.bind_to_any_port(HOST);
  17272. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17273. auto se = detail::scope_exit([&] {
  17274. svr.stop();
  17275. thread.join();
  17276. ASSERT_FALSE(svr.is_running());
  17277. });
  17278. svr.wait_until_ready();
  17279. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17280. // request URI limit; this used to be able to crash the process.
  17281. std::string path =
  17282. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17283. std::string req = "GET " + path +
  17284. " HTTP/1.1\r\n"
  17285. "Host: " +
  17286. std::string(HOST) + ":" + std::to_string(port) +
  17287. "\r\n"
  17288. "Connection: close\r\n"
  17289. "\r\n";
  17290. std::string response;
  17291. ASSERT_TRUE(send_request(5, req, &response, port));
  17292. EXPECT_NE(std::string::npos, response.find("404"));
  17293. }
  17294. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17295. Server svr;
  17296. auto handler = [](const Request & /*req*/, Response &res) {
  17297. res.set_content("hit", "text/plain");
  17298. };
  17299. // No regex metacharacter, so this one is compared literally
  17300. svr.Get("/literal/route", handler);
  17301. // '.' is a regex metacharacter, so this one must keep regex semantics
  17302. svr.Get("/a.c", handler);
  17303. auto port = svr.bind_to_any_port(HOST);
  17304. std::thread t([&]() { svr.listen_after_bind(); });
  17305. auto se = detail::scope_exit([&] {
  17306. svr.stop();
  17307. t.join();
  17308. ASSERT_FALSE(svr.is_running());
  17309. });
  17310. svr.wait_until_ready();
  17311. Client cli(HOST, port);
  17312. struct {
  17313. const char *path;
  17314. int status;
  17315. } cases[] = {
  17316. {"/literal/route", StatusCode::OK_200},
  17317. {"/literal/routes", StatusCode::NotFound_404},
  17318. {"/literal/rout", StatusCode::NotFound_404},
  17319. {"/abc", StatusCode::OK_200},
  17320. {"/a.c", StatusCode::OK_200},
  17321. };
  17322. for (const auto &x : cases) {
  17323. auto res = cli.Get(x.path);
  17324. ASSERT_TRUE(res) << x.path;
  17325. EXPECT_EQ(x.status, res->status) << x.path;
  17326. }
  17327. }
  17328. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17329. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17330. // from exhausting the stack, so it must only constrain routes that actually
  17331. // run a regular expression. A literal route is matched by comparison and
  17332. // stays usable at any length.
  17333. Server svr;
  17334. const std::string pattern =
  17335. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17336. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17337. res.set_content("hit", "text/plain");
  17338. });
  17339. auto port = svr.bind_to_any_port(HOST);
  17340. std::thread t([&]() { svr.listen_after_bind(); });
  17341. auto se = detail::scope_exit([&] {
  17342. svr.stop();
  17343. t.join();
  17344. ASSERT_FALSE(svr.is_running());
  17345. });
  17346. svr.wait_until_ready();
  17347. Client cli(HOST, port);
  17348. auto res = cli.Get(pattern);
  17349. ASSERT_TRUE(res);
  17350. EXPECT_EQ(StatusCode::OK_200, res->status);
  17351. }
  17352. TEST(ParseUrlTest, VariousPatterns) {
  17353. {
  17354. detail::UrlComponents uc;
  17355. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17356. EXPECT_EQ("http", uc.scheme);
  17357. EXPECT_EQ("example.com", uc.host);
  17358. EXPECT_EQ("8080", uc.port);
  17359. EXPECT_EQ("/path", uc.path);
  17360. EXPECT_EQ("?q=1", uc.query);
  17361. }
  17362. {
  17363. detail::UrlComponents uc;
  17364. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17365. EXPECT_EQ("https", uc.scheme);
  17366. EXPECT_EQ("example.com", uc.host);
  17367. EXPECT_TRUE(uc.port.empty());
  17368. EXPECT_EQ("/path", uc.path);
  17369. }
  17370. {
  17371. detail::UrlComponents uc;
  17372. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17373. EXPECT_EQ("::1", uc.host);
  17374. EXPECT_EQ("8080", uc.port);
  17375. EXPECT_EQ("/path", uc.path);
  17376. }
  17377. {
  17378. detail::UrlComponents uc;
  17379. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17380. }
  17381. {
  17382. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17383. // the path while the connection still targets the bracketed host.
  17384. detail::UrlComponents uc;
  17385. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17386. }
  17387. {
  17388. detail::UrlComponents uc;
  17389. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17390. }
  17391. {
  17392. detail::UrlComponents uc;
  17393. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17394. EXPECT_EQ("::1", uc.host);
  17395. EXPECT_TRUE(uc.port.empty());
  17396. EXPECT_EQ("/path", uc.path);
  17397. }
  17398. {
  17399. detail::UrlComponents uc;
  17400. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17401. EXPECT_TRUE(uc.scheme.empty());
  17402. EXPECT_EQ("example.com", uc.host);
  17403. EXPECT_EQ("/path", uc.path);
  17404. EXPECT_EQ("?q=1", uc.query);
  17405. }
  17406. {
  17407. detail::UrlComponents uc;
  17408. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17409. EXPECT_TRUE(uc.host.empty());
  17410. EXPECT_EQ("/path", uc.path);
  17411. EXPECT_EQ("?q=1", uc.query);
  17412. }
  17413. {
  17414. detail::UrlComponents uc;
  17415. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17416. EXPECT_EQ("example.com", uc.host);
  17417. EXPECT_EQ("8080", uc.port);
  17418. }
  17419. {
  17420. // Unix socket path — must not be parsed as host
  17421. detail::UrlComponents uc;
  17422. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17423. EXPECT_TRUE(uc.host.empty());
  17424. }
  17425. {
  17426. detail::UrlComponents uc;
  17427. ASSERT_TRUE(detail::parse_url("", uc));
  17428. EXPECT_TRUE(uc.host.empty());
  17429. EXPECT_TRUE(uc.path.empty());
  17430. }
  17431. {
  17432. detail::UrlComponents uc;
  17433. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17434. }
  17435. {
  17436. detail::UrlComponents uc;
  17437. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17438. }
  17439. {
  17440. // Accepted by parse_url; callers restrict to http/https
  17441. detail::UrlComponents uc;
  17442. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17443. EXPECT_EQ("ftp", uc.scheme);
  17444. }
  17445. {
  17446. detail::UrlComponents uc;
  17447. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17448. }
  17449. {
  17450. detail::UrlComponents uc;
  17451. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17452. }
  17453. }
  17454. TEST(ParseUrlTest, FragmentHandling) {
  17455. {
  17456. detail::UrlComponents uc;
  17457. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17458. EXPECT_EQ("/path", uc.path);
  17459. EXPECT_TRUE(uc.query.empty());
  17460. }
  17461. {
  17462. detail::UrlComponents uc;
  17463. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17464. EXPECT_TRUE(uc.path.empty());
  17465. EXPECT_TRUE(uc.query.empty());
  17466. }
  17467. }
  17468. TEST(ParseUrlTest, UserinfoHandling) {
  17469. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17470. // parsers would see evil.com as the host.
  17471. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17472. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17473. for (auto url : urls) {
  17474. detail::UrlComponents uc;
  17475. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17476. }
  17477. }
  17478. TEST(ParseUrlTest, IPv6EdgeCases) {
  17479. {
  17480. detail::UrlComponents uc;
  17481. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17482. EXPECT_TRUE(uc.scheme.empty());
  17483. EXPECT_EQ("::1", uc.host);
  17484. EXPECT_EQ("8080", uc.port);
  17485. }
  17486. {
  17487. // Zone ID '%25' is not in [a-fA-F0-9:]
  17488. detail::UrlComponents uc;
  17489. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17490. }
  17491. }
  17492. TEST(ParseUrlTest, SchemeEdgeCases) {
  17493. {
  17494. detail::UrlComponents uc;
  17495. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17496. }
  17497. {
  17498. detail::UrlComponents uc;
  17499. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17500. }
  17501. {
  17502. detail::UrlComponents uc;
  17503. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17504. }
  17505. }
  17506. TEST(ParseUrlTest, PortEdgeCases) {
  17507. {
  17508. detail::UrlComponents uc;
  17509. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17510. EXPECT_TRUE(uc.port.empty());
  17511. EXPECT_EQ("/path", uc.path);
  17512. }
  17513. {
  17514. // parse_url accepts any port string; validation is done by parse_port
  17515. detail::UrlComponents uc;
  17516. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17517. EXPECT_EQ("abc", uc.port);
  17518. }
  17519. }
  17520. TEST(ParseUrlTest, WebSocketPatterns) {
  17521. {
  17522. detail::UrlComponents uc;
  17523. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17524. EXPECT_EQ("ws", uc.scheme);
  17525. EXPECT_EQ("echo.example.com", uc.host);
  17526. EXPECT_EQ("8080", uc.port);
  17527. EXPECT_EQ("/ws", uc.path);
  17528. }
  17529. {
  17530. detail::UrlComponents uc;
  17531. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17532. EXPECT_EQ("wss", uc.scheme);
  17533. EXPECT_EQ("echo.example.com", uc.host);
  17534. EXPECT_TRUE(uc.port.empty());
  17535. EXPECT_EQ("/ws", uc.path);
  17536. }
  17537. }
  17538. TEST(ParseUrlTest, QueryOnly) {
  17539. detail::UrlComponents uc;
  17540. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17541. EXPECT_TRUE(uc.host.empty());
  17542. EXPECT_TRUE(uc.path.empty());
  17543. EXPECT_EQ("?q=1&r=2", uc.query);
  17544. }
  17545. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17546. detail::UrlComponents uc;
  17547. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17548. EXPECT_TRUE(uc.scheme.empty());
  17549. EXPECT_EQ("example.com", uc.host);
  17550. EXPECT_EQ("443", uc.port);
  17551. EXPECT_EQ("/path", uc.path);
  17552. }
  17553. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17554. // If ipv6 regex working, regex match codepath is taken.
  17555. // else port will default to 80 in Client impl
  17556. int clientImplMagicPort = 80;
  17557. int port = 4321;
  17558. // above ports must be different to avoid false negative
  17559. EXPECT_NE(clientImplMagicPort, port);
  17560. std::string ipV6TestURL = "http://[ff06::c3]";
  17561. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17562. CLIENT_PRIVATE_KEY_FILE);
  17563. EXPECT_EQ(cli.port(), port);
  17564. }
  17565. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17566. auto file_path = "./www/dir/index.html";
  17567. auto dir_path = "./www/dir";
  17568. detail::FileStat stat_file(file_path);
  17569. EXPECT_TRUE(stat_file.is_file());
  17570. EXPECT_FALSE(stat_file.is_dir());
  17571. detail::FileStat stat_dir(dir_path);
  17572. EXPECT_FALSE(stat_dir.is_file());
  17573. EXPECT_TRUE(stat_dir.is_dir());
  17574. }
  17575. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17576. // IPv4 with default HTTP port (80)
  17577. EXPECT_EQ("example.com",
  17578. detail::make_host_and_port_string("example.com", 80, false));
  17579. // IPv4 with default HTTPS port (443)
  17580. EXPECT_EQ("example.com",
  17581. detail::make_host_and_port_string("example.com", 443, true));
  17582. // IPv4 with non-default HTTP port
  17583. EXPECT_EQ("example.com:8080",
  17584. detail::make_host_and_port_string("example.com", 8080, false));
  17585. // IPv4 with non-default HTTPS port
  17586. EXPECT_EQ("example.com:8443",
  17587. detail::make_host_and_port_string("example.com", 8443, true));
  17588. // IPv6 with default HTTP port (80)
  17589. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17590. // IPv6 with default HTTPS port (443)
  17591. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17592. // IPv6 with non-default HTTP port
  17593. EXPECT_EQ("[::1]:8080",
  17594. detail::make_host_and_port_string("::1", 8080, false));
  17595. // IPv6 with non-default HTTPS port
  17596. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17597. // IPv6 full address with default port
  17598. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17599. detail::make_host_and_port_string(
  17600. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17601. // IPv6 full address with non-default port
  17602. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17603. detail::make_host_and_port_string(
  17604. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17605. // IPv6 localhost with non-default port
  17606. EXPECT_EQ("[::1]:3000",
  17607. detail::make_host_and_port_string("::1", 3000, false));
  17608. // IPv6 with zone ID (link-local address) with default port
  17609. EXPECT_EQ("[fe80::1%eth0]",
  17610. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17611. // IPv6 with zone ID (link-local address) with non-default port
  17612. EXPECT_EQ("[fe80::1%eth0]:8080",
  17613. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17614. // Edge case: Port 443 with is_ssl=false (should add port)
  17615. EXPECT_EQ("example.com:443",
  17616. detail::make_host_and_port_string("example.com", 443, false));
  17617. // Edge case: Port 80 with is_ssl=true (should add port)
  17618. EXPECT_EQ("example.com:80",
  17619. detail::make_host_and_port_string("example.com", 80, true));
  17620. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17621. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17622. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17623. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17624. // Security fix: Already bracketed IPv6 should not get double brackets
  17625. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17626. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17627. EXPECT_EQ("[::1]:8080",
  17628. detail::make_host_and_port_string("[::1]", 8080, false));
  17629. EXPECT_EQ("[2001:db8::1]:8080",
  17630. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17631. EXPECT_EQ("[fe80::1%eth0]",
  17632. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17633. EXPECT_EQ("[fe80::1%eth0]:8080",
  17634. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17635. // Edge case: Empty host (should return as-is)
  17636. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17637. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17638. // This is a known limitation but shouldn't crash
  17639. EXPECT_EQ("[host:name]",
  17640. detail::make_host_and_port_string("host:name", 80, false));
  17641. // Port number edge cases (no validation, but should not crash)
  17642. EXPECT_EQ("example.com:0",
  17643. detail::make_host_and_port_string("example.com", 0, false));
  17644. EXPECT_EQ("example.com:-1",
  17645. detail::make_host_and_port_string("example.com", -1, false));
  17646. EXPECT_EQ("example.com:65535",
  17647. detail::make_host_and_port_string("example.com", 65535, false));
  17648. EXPECT_EQ("example.com:65536",
  17649. detail::make_host_and_port_string("example.com", 65536, false));
  17650. }
  17651. #ifdef CPPHTTPLIB_SSL_ENABLED
  17652. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17653. httplib::SSLClient cli("roblox.com", 443);
  17654. cli.set_follow_location(true);
  17655. auto res = cli.Get("/");
  17656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17657. EXPECT_EQ(StatusCode::OK_200, res->status);
  17658. }
  17659. #endif
  17660. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17661. Server svr;
  17662. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17663. EXPECT_EQ(res.status, 400);
  17664. });
  17665. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17666. auto se = detail::scope_exit([&] {
  17667. svr.stop();
  17668. thread.join();
  17669. ASSERT_FALSE(svr.is_running());
  17670. });
  17671. svr.wait_until_ready();
  17672. Client cli(HOST, PORT);
  17673. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17674. }
  17675. TEST(InvalidHeaderCharsTest, is_field_name) {
  17676. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17677. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17678. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17679. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17680. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17681. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17682. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17683. EXPECT_FALSE(detail::fields::is_field_name(""));
  17684. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17685. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17686. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17687. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17688. }
  17689. TEST(InvalidHeaderCharsTest, is_field_value) {
  17690. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17691. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17692. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17693. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17694. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17695. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17696. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17697. EXPECT_TRUE(detail::fields::is_field_value(""));
  17698. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17699. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17700. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17701. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17702. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17703. }
  17704. TEST(InvalidHeaderCharsTest, OnServer) {
  17705. Server svr;
  17706. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17707. std::string header = "Not Set";
  17708. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17709. res.set_header(header, "value");
  17710. res.set_content("Page Content Page Content", "text/plain");
  17711. });
  17712. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17713. std::string header = "Not Set";
  17714. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17715. res.set_header("X-Test", header);
  17716. res.set_content("Page Content Page Content", "text/plain");
  17717. });
  17718. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17719. auto se = detail::scope_exit([&] {
  17720. svr.stop();
  17721. thread.join();
  17722. ASSERT_FALSE(svr.is_running());
  17723. });
  17724. svr.wait_until_ready();
  17725. Client cli(HOST, PORT);
  17726. {
  17727. auto res = cli.Get(
  17728. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17730. EXPECT_EQ("Page Content Page Content", res->body);
  17731. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17732. }
  17733. {
  17734. auto res = cli.Get(
  17735. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17737. EXPECT_EQ("Page Content Page Content", res->body);
  17738. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17739. }
  17740. }
  17741. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17742. auto handled = false;
  17743. Server svr;
  17744. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17745. thread t = thread([&] { svr.listen(HOST, PORT); });
  17746. auto se = detail::scope_exit([&] {
  17747. svr.stop();
  17748. t.join();
  17749. ASSERT_FALSE(svr.is_running());
  17750. ASSERT_FALSE(handled);
  17751. });
  17752. svr.wait_until_ready();
  17753. auto req = "POST /test HTTP/1.1\r\n"
  17754. "Content-Length: x\r\n"
  17755. "\r\n";
  17756. std::string response;
  17757. ASSERT_TRUE(send_request(1, req, &response));
  17758. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17759. response.substr(0, response.find("\r\n")));
  17760. }
  17761. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17762. // case-insensitive, and a server that receives a 100-continue expectation in
  17763. // an HTTP/1.0 request MUST ignore it.
  17764. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17765. std::string response;
  17766. ASSERT_TRUE(send_request(1, req, &response, port));
  17767. *got_100 = response.find("100 Continue") != std::string::npos;
  17768. }
  17769. class ExpectTokenTest : public ::testing::Test {
  17770. protected:
  17771. void SetUp() override {
  17772. svr_.Post("/p", [](const Request &, Response &res) {
  17773. res.set_content("ok", "text/plain");
  17774. });
  17775. port_ = svr_.bind_to_any_port(HOST);
  17776. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17777. svr_.wait_until_ready();
  17778. }
  17779. void TearDown() override {
  17780. svr_.stop();
  17781. if (thread_.joinable()) { thread_.join(); }
  17782. }
  17783. std::string request(const char *version, const char *expect_value) const {
  17784. return std::string("POST /p ") + version +
  17785. "\r\n"
  17786. "Host: localhost\r\n"
  17787. "Content-Length: 2\r\n"
  17788. "Connection: close\r\n"
  17789. "Expect: " +
  17790. expect_value +
  17791. "\r\n"
  17792. "\r\n"
  17793. "hi";
  17794. }
  17795. Server svr_;
  17796. int port_ = 0;
  17797. thread thread_;
  17798. };
  17799. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  17800. bool got_100 = false;
  17801. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  17802. EXPECT_TRUE(got_100);
  17803. }
  17804. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  17805. bool got_100 = true;
  17806. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  17807. EXPECT_FALSE(got_100);
  17808. }
  17809. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  17810. bool got_100 = false;
  17811. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  17812. EXPECT_TRUE(got_100);
  17813. }
  17814. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  17815. bool got_100 = false;
  17816. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  17817. EXPECT_TRUE(got_100);
  17818. }
  17819. // `100 Continue` is sent only when the server starts reading the body, so a
  17820. // request rejected before that never invites the client to send it. The
  17821. // requests below carry the expectation but withhold the body, as a client
  17822. // waiting for `100 Continue` would.
  17823. // A POST that expects `100 Continue` and withholds its two-byte body.
  17824. static std::string expect_headers_only(const std::string &path) {
  17825. return "POST " + path +
  17826. " HTTP/1.1\r\n"
  17827. "Host: localhost\r\n"
  17828. "Content-Length: 2\r\n"
  17829. "Expect: 100-continue\r\n"
  17830. "\r\n";
  17831. }
  17832. class ExpectLazyContinueTest : public ::testing::Test {
  17833. protected:
  17834. void SetUp() override {
  17835. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  17836. if (req.path == "/pre-routing") {
  17837. res.status = StatusCode::Unauthorized_401;
  17838. return Server::HandlerResponse::Handled;
  17839. }
  17840. return Server::HandlerResponse::Unhandled;
  17841. });
  17842. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  17843. if (req.matched_route == "/pre-request") {
  17844. res.status = StatusCode::Forbidden_403;
  17845. return Server::HandlerResponse::Handled;
  17846. }
  17847. return Server::HandlerResponse::Unhandled;
  17848. });
  17849. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  17850. res.set_content("ok", "text/plain");
  17851. });
  17852. svr_.Post("/pre-request", [](const Request &, Response &res) {
  17853. res.set_content("ok", "text/plain");
  17854. });
  17855. svr_.Post("/reader-used", [](const Request &, Response &res,
  17856. const ContentReader &content_reader) {
  17857. std::string body;
  17858. content_reader([&](const char *data, size_t len) {
  17859. body.append(data, len);
  17860. return true;
  17861. });
  17862. res.set_content(body, "text/plain");
  17863. });
  17864. svr_.Post("/reader-unused",
  17865. [](const Request &, Response &res, const ContentReader &) {
  17866. res.set_content("ignored", "text/plain");
  17867. });
  17868. port_ = svr_.bind_to_any_port(HOST);
  17869. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17870. svr_.wait_until_ready();
  17871. }
  17872. void TearDown() override {
  17873. svr_.stop();
  17874. if (thread_.joinable()) { thread_.join(); }
  17875. }
  17876. // Sends `req` and reads until the server closes the connection. Returns
  17877. // false if the read had to wait for the client-side timeout instead.
  17878. bool send_until_closed(const std::string &req, std::string *resp) const {
  17879. auto start = std::chrono::steady_clock::now();
  17880. if (!send_request(3, req, resp, port_)) { return false; }
  17881. auto elapsed = std::chrono::steady_clock::now() - start;
  17882. return elapsed < std::chrono::seconds(2);
  17883. }
  17884. // The final response comes without `100 Continue`, and the server closes
  17885. // the connection since the body may or may not follow.
  17886. void expect_final_without_interim(const std::string &path,
  17887. const char *status_line) const {
  17888. std::string resp;
  17889. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  17890. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  17891. EXPECT_EQ(0u, resp.find(status_line));
  17892. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17893. }
  17894. Server svr_;
  17895. int port_ = 0;
  17896. thread thread_;
  17897. };
  17898. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  17899. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  17900. }
  17901. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  17902. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  17903. }
  17904. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  17905. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  17906. }
  17907. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  17908. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  17909. }
  17910. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  17911. // The body follows once `100 Continue` has had time to arrive.
  17912. auto req = expect_headers_only("/reader-used");
  17913. req.insert(req.size() - 2, "Connection: close\r\n");
  17914. std::string resp;
  17915. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  17916. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  17917. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  17918. EXPECT_NE(std::string::npos, resp.find("hi"));
  17919. }
  17920. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  17921. // Large enough for the client to add `Expect: 100-continue` itself.
  17922. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  17923. std::atomic<bool> body_sent{false};
  17924. Client cli(HOST, port_);
  17925. auto res = cli.Post(
  17926. "/pre-request", length,
  17927. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  17928. body_sent = true;
  17929. std::string chunk(len, 'x');
  17930. sink.write(chunk.data(), chunk.size());
  17931. return true;
  17932. },
  17933. "application/octet-stream");
  17934. ASSERT_TRUE(res);
  17935. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17936. EXPECT_FALSE(body_sent);
  17937. }
  17938. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  17939. Server svr;
  17940. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  17941. return StatusCode::ExpectationFailed_417;
  17942. });
  17943. svr.Post("/p", [](const Request &, Response &res) {
  17944. res.set_content("ok", "text/plain");
  17945. });
  17946. auto port = svr.bind_to_any_port(HOST);
  17947. thread t = thread([&] { svr.listen_after_bind(); });
  17948. auto se = detail::scope_exit([&] {
  17949. svr.stop();
  17950. t.join();
  17951. });
  17952. svr.wait_until_ready();
  17953. std::string resp;
  17954. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  17955. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  17956. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17957. // Exactly one response: the route handler must not run after the 417.
  17958. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  17959. }
  17960. #ifndef _WIN32
  17961. TEST(Expect100ContinueTest, ServerClosesConnection) {
  17962. static constexpr char reject[] = "Unauthorized";
  17963. static constexpr char accept[] = "Upload accepted";
  17964. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17965. Server svr;
  17966. svr.set_expect_100_continue_handler(
  17967. [](const Request & /*req*/, Response &res) {
  17968. res.status = StatusCode::Unauthorized_401;
  17969. res.set_content(reject, "text/plain");
  17970. return res.status;
  17971. });
  17972. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17973. res.set_content(accept, "text/plain");
  17974. });
  17975. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17976. auto se = detail::scope_exit([&] {
  17977. svr.stop();
  17978. thread.join();
  17979. ASSERT_FALSE(svr.is_running());
  17980. });
  17981. svr.wait_until_ready();
  17982. {
  17983. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17984. curl_easy_init(), &curl_easy_cleanup};
  17985. ASSERT_NE(curl, nullptr);
  17986. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17987. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17988. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17989. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17990. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17991. &curl_slist_free_all};
  17992. ASSERT_NE(list, nullptr);
  17993. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17994. struct read_data {
  17995. size_t read_size;
  17996. size_t total_size;
  17997. } data = {0, total_size};
  17998. using read_callback_t =
  17999. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18000. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18001. void *userdata) -> size_t {
  18002. read_data *d = (read_data *)userdata;
  18003. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18004. std::fill_n(ptr, size * nmemb, 'A');
  18005. d->read_size += size * nmemb;
  18006. return size * nmemb;
  18007. };
  18008. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  18009. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18010. std::vector<char> buffer;
  18011. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18012. using write_callback_t =
  18013. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18014. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18015. void *userdata) -> size_t {
  18016. std::vector<char> *buf = (std::vector<char> *)userdata;
  18017. buf->reserve(buf->size() + size * nmemb + 1);
  18018. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18019. return size * nmemb;
  18020. };
  18021. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18022. {
  18023. const auto res = curl_easy_perform(curl.get());
  18024. ASSERT_EQ(res, CURLE_OK);
  18025. }
  18026. {
  18027. auto response_code = long{};
  18028. const auto res =
  18029. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18030. ASSERT_EQ(res, CURLE_OK);
  18031. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18032. }
  18033. {
  18034. auto dl = curl_off_t{};
  18035. const auto res =
  18036. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18037. ASSERT_EQ(res, CURLE_OK);
  18038. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18039. }
  18040. {
  18041. buffer.push_back('\0');
  18042. ASSERT_STRCASEEQ(buffer.data(), reject);
  18043. }
  18044. }
  18045. }
  18046. #endif
  18047. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18048. // Regression test for #2458.
  18049. //
  18050. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18051. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18052. // ticket can make the client socket spuriously readable during the
  18053. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18054. // the client withholds the body and then blocks reading a response that never
  18055. // comes, failing with `Failed to read connection`.
  18056. //
  18057. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18058. // within the timeout. This raw OpenSSL server deliberately never sends
  18059. // `100 Continue`; the client must still deliver the body and receive 200.
  18060. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18061. signal(SIGPIPE, SIG_IGN);
  18062. const auto port = PORT + 4;
  18063. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18064. ASSERT_NE(srv, INVALID_SOCKET);
  18065. int opt = 1;
  18066. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18067. sockaddr_in addr{};
  18068. addr.sin_family = AF_INET;
  18069. addr.sin_port = htons(static_cast<uint16_t>(port));
  18070. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18071. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18072. ASSERT_EQ(0, ::listen(srv, 1));
  18073. std::atomic<size_t> server_body_bytes{0};
  18074. auto server_thread = std::thread([&] {
  18075. sockaddr_in cli_addr{};
  18076. socklen_t cli_len = sizeof(cli_addr);
  18077. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18078. if (cli == INVALID_SOCKET) { return; }
  18079. // Bound the lifetime of the server side so a buggy client (which never
  18080. // sends the body) cannot make this thread block forever on join.
  18081. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18082. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18083. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18084. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18085. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18086. SSL *ssl = SSL_new(ctx);
  18087. SSL_set_fd(ssl, static_cast<int>(cli));
  18088. if (SSL_accept(ssl) > 0) {
  18089. // Read the request headers. Reading here also flushes the TLS 1.3
  18090. // session tickets to the client. Deliberately do NOT send
  18091. // `100 Continue`.
  18092. std::string buf;
  18093. char tmp[1024];
  18094. while (buf.find("\r\n\r\n") == std::string::npos) {
  18095. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18096. if (n <= 0) { break; }
  18097. buf.append(tmp, static_cast<size_t>(n));
  18098. }
  18099. // A correct client sends the body now; count what arrives.
  18100. auto pos = buf.find("\r\n\r\n");
  18101. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18102. while (body < 4096) {
  18103. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18104. if (n <= 0) { break; }
  18105. body += static_cast<size_t>(n);
  18106. }
  18107. server_body_bytes = body;
  18108. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18109. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18110. SSL_shutdown(ssl);
  18111. }
  18112. SSL_free(ssl);
  18113. detail::close_socket(cli);
  18114. SSL_CTX_free(ctx);
  18115. });
  18116. auto se = detail::scope_exit([&] {
  18117. server_thread.join();
  18118. detail::close_socket(srv);
  18119. });
  18120. SSLClient cli("127.0.0.1", port);
  18121. cli.enable_server_certificate_verification(false);
  18122. cli.set_connection_timeout(5, 0);
  18123. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18124. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18125. std::string body(4096, 'A');
  18126. auto res = cli.Put("/api/test", body, "application/json");
  18127. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18128. EXPECT_EQ(StatusCode::OK_200, res->status);
  18129. EXPECT_EQ(body.size(), server_body_bytes.load());
  18130. }
  18131. #endif
  18132. template <typename S, typename C>
  18133. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18134. svr.Get("/stream", [&](const Request &, Response &res) {
  18135. auto data = new std::string("01234567890123456789");
  18136. res.set_content_provider(
  18137. data->size(), "text/plain",
  18138. [&, data](size_t offset, size_t length, DataSink &sink) {
  18139. const size_t DATA_CHUNK_SIZE = 4;
  18140. const auto &d = *data;
  18141. std::this_thread::sleep_for(std::chrono::seconds(1));
  18142. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18143. return true;
  18144. },
  18145. [data](bool success) {
  18146. EXPECT_FALSE(success);
  18147. delete data;
  18148. });
  18149. });
  18150. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18151. auto i = new size_t(0);
  18152. res.set_content_provider(
  18153. "text/plain",
  18154. [i](size_t, DataSink &sink) {
  18155. if (*i < 5) {
  18156. std::this_thread::sleep_for(std::chrono::seconds(1));
  18157. sink.write("abcd", 4);
  18158. (*i)++;
  18159. } else {
  18160. sink.done();
  18161. }
  18162. return true;
  18163. },
  18164. [i](bool success) {
  18165. EXPECT_FALSE(success);
  18166. delete i;
  18167. });
  18168. });
  18169. svr.Get("/chunked", [&](const Request &, Response &res) {
  18170. auto i = new size_t(0);
  18171. res.set_chunked_content_provider(
  18172. "text/plain",
  18173. [i](size_t, DataSink &sink) {
  18174. if (*i < 5) {
  18175. std::this_thread::sleep_for(std::chrono::seconds(1));
  18176. sink.os << "abcd";
  18177. (*i)++;
  18178. } else {
  18179. sink.done();
  18180. }
  18181. return true;
  18182. },
  18183. [i](bool success) {
  18184. EXPECT_FALSE(success);
  18185. delete i;
  18186. });
  18187. });
  18188. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18189. auto se = detail::scope_exit([&] {
  18190. svr.stop();
  18191. listen_thread.join();
  18192. ASSERT_FALSE(svr.is_running());
  18193. });
  18194. svr.wait_until_ready();
  18195. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18196. {
  18197. auto start = std::chrono::steady_clock::now();
  18198. auto res = cli.Get("/stream");
  18199. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18200. std::chrono::steady_clock::now() - start)
  18201. .count();
  18202. ASSERT_FALSE(res);
  18203. EXPECT_EQ(Error::Read, res.error());
  18204. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18205. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18206. }
  18207. {
  18208. auto start = std::chrono::steady_clock::now();
  18209. auto res = cli.Get("/stream_without_length");
  18210. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18211. std::chrono::steady_clock::now() - start)
  18212. .count();
  18213. ASSERT_FALSE(res);
  18214. EXPECT_EQ(Error::Read, res.error());
  18215. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18216. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18217. }
  18218. {
  18219. auto start = std::chrono::steady_clock::now();
  18220. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18221. EXPECT_EQ("abcd", string(data, data_length));
  18222. return true;
  18223. });
  18224. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18225. std::chrono::steady_clock::now() - start)
  18226. .count();
  18227. ASSERT_FALSE(res);
  18228. EXPECT_EQ(Error::Read, res.error());
  18229. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18230. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18231. }
  18232. }
  18233. TEST(MaxTimeoutTest, ContentStream) {
  18234. time_t timeout = 2000;
  18235. time_t threshold = 200;
  18236. Server svr;
  18237. Client cli("localhost", PORT);
  18238. max_timeout_test(svr, cli, timeout, threshold);
  18239. }
  18240. #ifdef CPPHTTPLIB_SSL_ENABLED
  18241. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18242. time_t timeout = 2000;
  18243. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18244. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18245. SSLClient cli("localhost", PORT);
  18246. cli.enable_server_certificate_verification(false);
  18247. max_timeout_test(svr, cli, timeout, threshold);
  18248. }
  18249. #endif
  18250. class EventDispatcher {
  18251. public:
  18252. EventDispatcher() {}
  18253. bool wait_event(DataSink *sink) {
  18254. unique_lock<mutex> lk(m_);
  18255. int id = id_;
  18256. // Wait with timeout to prevent hanging if client disconnects
  18257. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18258. [&] { return cid_ == id; })) {
  18259. return false; // Timeout occurred
  18260. }
  18261. sink->write(message_.data(), message_.size());
  18262. return true;
  18263. }
  18264. void send_event(const string &message) {
  18265. lock_guard<mutex> lk(m_);
  18266. cid_ = id_++;
  18267. message_ = message;
  18268. cv_.notify_all();
  18269. }
  18270. private:
  18271. mutex m_;
  18272. condition_variable cv_;
  18273. atomic_int id_{0};
  18274. atomic_int cid_{-1};
  18275. string message_;
  18276. };
  18277. TEST(ClientInThreadTest, Issue2068) {
  18278. EventDispatcher ed;
  18279. Server svr;
  18280. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18281. res.set_chunked_content_provider("text/event-stream",
  18282. [&](size_t /*offset*/, DataSink &sink) {
  18283. return ed.wait_event(&sink);
  18284. });
  18285. });
  18286. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18287. svr.wait_until_ready();
  18288. thread event_thread([&] {
  18289. int id = 0;
  18290. while (svr.is_running()) {
  18291. this_thread::sleep_for(chrono::milliseconds(500));
  18292. std::stringstream ss;
  18293. ss << "data: " << id << "\n\n";
  18294. ed.send_event(ss.str());
  18295. id++;
  18296. }
  18297. });
  18298. auto se = detail::scope_exit([&] {
  18299. svr.stop();
  18300. listen_thread.join();
  18301. event_thread.join();
  18302. ASSERT_FALSE(svr.is_running());
  18303. });
  18304. {
  18305. auto client = detail::make_unique<Client>(HOST, PORT);
  18306. client->set_read_timeout(std::chrono::minutes(10));
  18307. std::atomic<bool> stop{false};
  18308. std::thread t([&] {
  18309. client->Get("/event1",
  18310. [&](const char *, size_t) -> bool { return !stop; });
  18311. });
  18312. std::this_thread::sleep_for(std::chrono::seconds(2));
  18313. stop = true;
  18314. client->stop();
  18315. t.join();
  18316. // Reset client after thread has finished
  18317. client.reset();
  18318. }
  18319. }
  18320. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18321. auto handled = false;
  18322. Server svr;
  18323. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18324. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18325. auto se = detail::scope_exit([&] {
  18326. svr.stop();
  18327. t.join();
  18328. ASSERT_FALSE(svr.is_running());
  18329. ASSERT_FALSE(handled);
  18330. });
  18331. svr.wait_until_ready();
  18332. // Two Content-Length headers with different values — must be rejected
  18333. auto req = "POST /test HTTP/1.1\r\n"
  18334. "Content-Length: 5\r\n"
  18335. "Content-Length: 10\r\n"
  18336. "\r\n"
  18337. "hello";
  18338. std::string response;
  18339. ASSERT_TRUE(send_request(1, req, &response));
  18340. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18341. response.substr(0, response.find("\r\n")));
  18342. }
  18343. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18344. auto handled = false;
  18345. Server svr;
  18346. svr.Post("/test", [&](const Request &, Response &res) {
  18347. handled = true;
  18348. res.set_content("ok", "text/plain");
  18349. });
  18350. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18351. auto se = detail::scope_exit([&] {
  18352. svr.stop();
  18353. t.join();
  18354. ASSERT_FALSE(svr.is_running());
  18355. ASSERT_TRUE(handled);
  18356. });
  18357. svr.wait_until_ready();
  18358. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18359. auto req = "POST /test HTTP/1.1\r\n"
  18360. "Host: localhost\r\n"
  18361. "Content-Length: 5\r\n"
  18362. "Content-Length: 5\r\n"
  18363. "\r\n"
  18364. "hello";
  18365. std::string response;
  18366. ASSERT_TRUE(send_request(1, req, &response));
  18367. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18368. }
  18369. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18370. Server svr;
  18371. svr.Get("/test", [](const Request &, Response &res) {
  18372. res.set_content("ok", "text/plain");
  18373. });
  18374. auto port = svr.bind_to_any_port(HOST);
  18375. thread t = thread([&] { svr.listen_after_bind(); });
  18376. auto se = detail::scope_exit([&] {
  18377. svr.stop();
  18378. t.join();
  18379. ASSERT_FALSE(svr.is_running());
  18380. });
  18381. svr.wait_until_ready();
  18382. auto status_line = [&](const std::string &host_lines) {
  18383. std::string res;
  18384. send_request(
  18385. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18386. &res, port);
  18387. return res.substr(0, res.find("\r\n"));
  18388. };
  18389. const char *accepted[] = {
  18390. "Host: localhost\r\n",
  18391. "Host: a.example:8080\r\n",
  18392. "Host: my_service\r\n",
  18393. "Host: [::1]:8080\r\n",
  18394. "Host: [fe80::1%25eth0]\r\n",
  18395. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18396. };
  18397. for (auto host_lines : accepted) {
  18398. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18399. }
  18400. const char *rejected[] = {
  18401. "Host: a.example\r\nHost: b.example\r\n",
  18402. "Host: a.example\r\nHost: a.example\r\n",
  18403. "Host: a@b.example\r\n",
  18404. "Host: a.example/b\r\n",
  18405. "Host: a.example\\b\r\n",
  18406. "Host: a.example?b\r\n",
  18407. "Host: a.example#b\r\n",
  18408. "Host: a.example b.example\r\n",
  18409. };
  18410. for (auto host_lines : rejected) {
  18411. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18412. << host_lines;
  18413. }
  18414. }
  18415. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18416. Server svr;
  18417. svr.Get("/", [](const Request &req, Response &res) {
  18418. EXPECT_EQ(2U, req.trailers.size());
  18419. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18420. // Denied
  18421. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18422. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18423. // Accepted
  18424. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18425. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18426. EXPECT_TRUE(req.has_trailer("X-World"));
  18427. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18428. res.set_content("ok", "text/plain");
  18429. });
  18430. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18431. auto se = detail::scope_exit([&] {
  18432. svr.stop();
  18433. t.join();
  18434. ASSERT_FALSE(svr.is_running());
  18435. });
  18436. svr.wait_until_ready();
  18437. const std::string req = "GET / HTTP/1.1\r\n"
  18438. "Transfer-Encoding: chunked\r\n"
  18439. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18440. "\r\n"
  18441. "0\r\n"
  18442. "Content-Length: 10\r\n"
  18443. "Host: internal.local\r\n"
  18444. "Content-Type: malicious/content\r\n"
  18445. "Cookie: any\r\n"
  18446. "Set-Cookie: any\r\n"
  18447. "X-Forwarded-For: attacker.com\r\n"
  18448. "X-Real-Ip: 1.1.1.1\r\n"
  18449. "X-Hello: hello\r\n"
  18450. "X-World: world\r\n"
  18451. "\r\n";
  18452. std::string res;
  18453. ASSERT_TRUE(send_request(1, req, &res));
  18454. }
  18455. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18456. // several field lines, and the combined value is what has to be parsed. A
  18457. // Trailer field split across lines therefore declares every name it lists;
  18458. // reading only the first line silently drops the trailers the later lines
  18459. // declare. The prohibited-trailer filter still applies to every line.
  18460. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18461. Server svr;
  18462. size_t observed_trailer_count = 0;
  18463. std::string observed_hello;
  18464. std::string observed_world;
  18465. bool observed_content_length = true;
  18466. svr.Get("/", [&](const Request &req, Response &res) {
  18467. observed_trailer_count = req.trailers.size();
  18468. observed_hello = req.get_trailer_value("X-Hello");
  18469. observed_world = req.get_trailer_value("X-World");
  18470. observed_content_length = req.has_trailer("Content-Length");
  18471. res.set_content("ok", "text/plain");
  18472. });
  18473. auto port = svr.bind_to_any_port(HOST);
  18474. thread t = thread([&]() { svr.listen_after_bind(); });
  18475. auto se = detail::scope_exit([&] {
  18476. svr.stop();
  18477. t.join();
  18478. ASSERT_FALSE(svr.is_running());
  18479. });
  18480. svr.wait_until_ready();
  18481. const std::string req = "GET / HTTP/1.1\r\n"
  18482. "Host: localhost\r\n"
  18483. "Transfer-Encoding: chunked\r\n"
  18484. "Trailer: X-Hello\r\n"
  18485. "Trailer: X-World, Content-Length\r\n"
  18486. "\r\n"
  18487. "0\r\n"
  18488. "X-Hello: hello\r\n"
  18489. "X-World: world\r\n"
  18490. "Content-Length: 10\r\n"
  18491. "\r\n";
  18492. std::string res;
  18493. ASSERT_TRUE(send_request(1, req, &res, port));
  18494. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18495. // Accepted: both field lines contribute to the declared set
  18496. EXPECT_EQ(2U, observed_trailer_count);
  18497. EXPECT_EQ(observed_hello, "hello");
  18498. EXPECT_EQ(observed_world, "world");
  18499. // Denied: a prohibited name stays prohibited on a later field line
  18500. EXPECT_FALSE(observed_content_length);
  18501. }
  18502. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18503. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18504. // unbounded run of fields that are never declared, because the counter would
  18505. // only advance for declared fields.
  18506. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18507. Server svr;
  18508. bool handler_called = false;
  18509. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18510. handler_called = true;
  18511. res.set_content("ok", "text/plain");
  18512. });
  18513. auto port = svr.bind_to_any_port(HOST);
  18514. thread t = thread([&]() { svr.listen_after_bind(); });
  18515. auto se = detail::scope_exit([&] {
  18516. svr.stop();
  18517. t.join();
  18518. ASSERT_FALSE(svr.is_running());
  18519. });
  18520. svr.wait_until_ready();
  18521. // Declare nothing, then send far more undeclared trailer fields than the
  18522. // header-count limit. Parsing must stop and reject the request rather than
  18523. // read every line.
  18524. std::string req = "GET / HTTP/1.1\r\n"
  18525. "Transfer-Encoding: chunked\r\n"
  18526. "\r\n"
  18527. "0\r\n";
  18528. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18529. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18530. }
  18531. req += "\r\n";
  18532. std::string res;
  18533. ASSERT_TRUE(send_request(1, req, &res, port));
  18534. // The request is rejected before the handler runs.
  18535. EXPECT_FALSE(handler_called);
  18536. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18537. }
  18538. // The set of declared trailer names is capped so a peer cannot grow it without
  18539. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18540. // declared past the cap is not honored, even if the field is actually sent.
  18541. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18542. Server svr;
  18543. // One name inside the cap and one past it, so the test tracks the cap rather
  18544. // than a fixed count.
  18545. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18546. const std::string within_cap_name = "X-T-0";
  18547. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18548. bool observed_within_cap = false;
  18549. bool observed_past_cap = false;
  18550. svr.Get("/", [&](const Request &req, Response &res) {
  18551. observed_within_cap = req.has_trailer(within_cap_name);
  18552. observed_past_cap = req.has_trailer(past_cap_name);
  18553. res.set_content("ok", "text/plain");
  18554. });
  18555. auto port = svr.bind_to_any_port(HOST);
  18556. thread t = thread([&]() { svr.listen_after_bind(); });
  18557. auto se = detail::scope_exit([&] {
  18558. svr.stop();
  18559. t.join();
  18560. ASSERT_FALSE(svr.is_running());
  18561. });
  18562. svr.wait_until_ready();
  18563. // Declare more trailer names than the cap in a single Trailer field, then
  18564. // actually send the first (within the cap) and the last (past it).
  18565. std::string trailer_decl = "Trailer: ";
  18566. for (int i = 0; i < declared_count; i++) {
  18567. if (i != 0) { trailer_decl += ", "; }
  18568. trailer_decl += "X-T-" + std::to_string(i);
  18569. }
  18570. trailer_decl += "\r\n";
  18571. const std::string req = "GET / HTTP/1.1\r\n"
  18572. "Host: localhost\r\n"
  18573. "Transfer-Encoding: chunked\r\n" +
  18574. trailer_decl +
  18575. "\r\n"
  18576. "0\r\n" +
  18577. within_cap_name + ": a\r\n" + past_cap_name +
  18578. ": b\r\n"
  18579. "\r\n";
  18580. std::string res;
  18581. ASSERT_TRUE(send_request(1, req, &res, port));
  18582. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18583. // A name within the cap is honored; one declared past the cap is dropped.
  18584. EXPECT_TRUE(observed_within_cap);
  18585. EXPECT_FALSE(observed_past_cap);
  18586. }
  18587. // A direct client that is not listed in trusted_proxies must not be able to
  18588. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18589. // the peer address on the actual TCP connection determines whether the
  18590. // header is honored.
  18591. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18592. Server svr;
  18593. // Deliberately does NOT include the loopback address the test client
  18594. // actually connects from, so the direct connection is not a trusted proxy.
  18595. svr.set_trusted_proxies({"203.0.113.66"});
  18596. std::string observed_remote_addr;
  18597. svr.Get("/ip", [&](const Request &req, Response &res) {
  18598. observed_remote_addr = req.remote_addr;
  18599. res.set_content("ok", "text/plain");
  18600. });
  18601. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18602. auto se = detail::scope_exit([&] {
  18603. svr.stop();
  18604. t.join();
  18605. ASSERT_FALSE(svr.is_running());
  18606. });
  18607. svr.wait_until_ready();
  18608. Client cli(HOST, PORT);
  18609. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18611. EXPECT_EQ(StatusCode::OK_200, res->status);
  18612. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18613. // ignored entirely and the real connection-level address retained.
  18614. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18615. observed_remote_addr == "127.0.0.1");
  18616. }
  18617. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18618. Server svr;
  18619. std::string observed_remote_addr;
  18620. std::string observed_xff;
  18621. svr.Get("/ip", [&](const Request &req, Response &res) {
  18622. observed_remote_addr = req.remote_addr;
  18623. observed_xff = req.get_header_value("X-Forwarded-For");
  18624. res.set_content("ok", "text/plain");
  18625. });
  18626. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18627. auto se = detail::scope_exit([&] {
  18628. svr.stop();
  18629. t.join();
  18630. ASSERT_FALSE(svr.is_running());
  18631. });
  18632. svr.wait_until_ready();
  18633. Client cli(HOST, PORT);
  18634. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18636. EXPECT_EQ(StatusCode::OK_200, res->status);
  18637. EXPECT_EQ(observed_xff, "203.0.113.66");
  18638. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18639. observed_remote_addr == "127.0.0.1");
  18640. }
  18641. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18642. Server svr;
  18643. svr.set_trusted_proxies({"203.0.113.66"});
  18644. std::string observed_remote_addr;
  18645. std::string observed_xff;
  18646. svr.Get("/ip", [&](const Request &req, Response &res) {
  18647. observed_remote_addr = req.remote_addr;
  18648. observed_xff = req.get_header_value("X-Forwarded-For");
  18649. res.set_content("ok", "text/plain");
  18650. });
  18651. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18652. auto se = detail::scope_exit([&] {
  18653. svr.stop();
  18654. t.join();
  18655. ASSERT_FALSE(svr.is_running());
  18656. });
  18657. svr.wait_until_ready();
  18658. Client cli(HOST, PORT);
  18659. auto res = cli.Get("/ip");
  18660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18661. EXPECT_EQ(StatusCode::OK_200, res->status);
  18662. EXPECT_EQ(observed_xff, "");
  18663. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18664. observed_remote_addr == "127.0.0.1");
  18665. }
  18666. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18667. Server svr;
  18668. // Include the loopback address the test client actually connects from, so
  18669. // the direct connection itself is recognized as the trusted proxy hop.
  18670. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18671. std::string observed_remote_addr;
  18672. std::string observed_xff;
  18673. svr.Get("/ip", [&](const Request &req, Response &res) {
  18674. observed_remote_addr = req.remote_addr;
  18675. observed_xff = req.get_header_value("X-Forwarded-For");
  18676. res.set_content("ok", "text/plain");
  18677. });
  18678. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18679. auto se = detail::scope_exit([&] {
  18680. svr.stop();
  18681. t.join();
  18682. ASSERT_FALSE(svr.is_running());
  18683. });
  18684. svr.wait_until_ready();
  18685. Client cli(HOST, PORT);
  18686. auto res = cli.Get(
  18687. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18689. EXPECT_EQ(StatusCode::OK_200, res->status);
  18690. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18691. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18692. }
  18693. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18694. Server svr;
  18695. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  18696. std::string observed_remote_addr;
  18697. std::string observed_xff;
  18698. svr.Get("/ip", [&](const Request &req, Response &res) {
  18699. observed_remote_addr = req.remote_addr;
  18700. observed_xff = req.get_header_value("X-Forwarded-For");
  18701. res.set_content("ok", "text/plain");
  18702. });
  18703. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18704. auto se = detail::scope_exit([&] {
  18705. svr.stop();
  18706. t.join();
  18707. ASSERT_FALSE(svr.is_running());
  18708. });
  18709. svr.wait_until_ready();
  18710. Client cli(HOST, PORT);
  18711. auto res = cli.Get(
  18712. "/ip",
  18713. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18715. EXPECT_EQ(StatusCode::OK_200, res->status);
  18716. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18717. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18718. }
  18719. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18720. Server svr;
  18721. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18722. std::string observed_remote_addr;
  18723. std::string observed_xff;
  18724. svr.Get("/ip", [&](const Request &req, Response &res) {
  18725. observed_remote_addr = req.remote_addr;
  18726. observed_xff = req.get_header_value("X-Forwarded-For");
  18727. res.set_content("ok", "text/plain");
  18728. });
  18729. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18730. auto se = detail::scope_exit([&] {
  18731. svr.stop();
  18732. t.join();
  18733. ASSERT_FALSE(svr.is_running());
  18734. });
  18735. svr.wait_until_ready();
  18736. Client cli(HOST, PORT);
  18737. auto res = cli.Get(
  18738. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18740. EXPECT_EQ(StatusCode::OK_200, res->status);
  18741. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18742. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18743. // and must not be selected.
  18744. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18745. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18746. }
  18747. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18748. Server svr;
  18749. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18750. std::string observed_remote_addr;
  18751. svr.Get("/ip", [&](const Request &req, Response &res) {
  18752. observed_remote_addr = req.remote_addr;
  18753. res.set_content("ok", "text/plain");
  18754. });
  18755. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18756. auto se = detail::scope_exit([&] {
  18757. svr.stop();
  18758. t.join();
  18759. ASSERT_FALSE(svr.is_running());
  18760. });
  18761. svr.wait_until_ready();
  18762. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  18763. // a forged address and the trusted proxy's own address; the forged value must
  18764. // not win over the address the trusted proxy actually recorded.
  18765. Client cli(HOST, PORT);
  18766. auto res = cli.Get(
  18767. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  18768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18769. EXPECT_EQ(StatusCode::OK_200, res->status);
  18770. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  18771. }
  18772. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  18773. Server svr;
  18774. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18775. std::string observed_remote_addr;
  18776. std::string observed_xff;
  18777. svr.Get("/ip", [&](const Request &req, Response &res) {
  18778. observed_remote_addr = req.remote_addr;
  18779. observed_xff = req.get_header_value("X-Forwarded-For");
  18780. res.set_content("ok", "text/plain");
  18781. });
  18782. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18783. auto se = detail::scope_exit([&] {
  18784. svr.stop();
  18785. t.join();
  18786. ASSERT_FALSE(svr.is_running());
  18787. });
  18788. svr.wait_until_ready();
  18789. Client cli(HOST, PORT);
  18790. auto res = cli.Get(
  18791. "/ip",
  18792. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18794. EXPECT_EQ(StatusCode::OK_200, res->status);
  18795. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18796. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18797. }
  18798. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  18799. Server svr;
  18800. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18801. std::string observed_remote_addr;
  18802. std::string observed_xff;
  18803. svr.Get("/ip", [&](const Request &req, Response &res) {
  18804. observed_remote_addr = req.remote_addr;
  18805. observed_xff = req.get_header_value("X-Forwarded-For");
  18806. res.set_content("ok", "text/plain");
  18807. });
  18808. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18809. auto se = detail::scope_exit([&] {
  18810. svr.stop();
  18811. t.join();
  18812. ASSERT_FALSE(svr.is_running());
  18813. });
  18814. svr.wait_until_ready();
  18815. std::string raw_req =
  18816. "GET /ip HTTP/1.1\r\n"
  18817. "Host: localhost\r\n"
  18818. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  18819. "Connection: close\r\n"
  18820. "\r\n";
  18821. std::string out;
  18822. ASSERT_TRUE(send_request(5, raw_req, &out));
  18823. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18824. // Header parser trims surrounding whitespace of the header value
  18825. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  18826. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18827. }
  18828. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  18829. // one comma-joined value, in the order received. Proxies such as HAProxy append
  18830. // their own X-Forwarded-For as a separate field line rather than extending the
  18831. // one the client sent, so every occurrence has to be taken into account.
  18832. // Reading only the first one hands back the address the client chose.
  18833. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  18834. Server svr;
  18835. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18836. std::string observed_remote_addr;
  18837. size_t observed_xff_count = 0;
  18838. svr.Get("/ip", [&](const Request &req, Response &res) {
  18839. observed_remote_addr = req.remote_addr;
  18840. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  18841. res.set_content("ok", "text/plain");
  18842. });
  18843. auto port = svr.bind_to_any_port(HOST);
  18844. thread t = thread([&]() { svr.listen_after_bind(); });
  18845. auto se = detail::scope_exit([&] {
  18846. svr.stop();
  18847. t.join();
  18848. ASSERT_FALSE(svr.is_running());
  18849. });
  18850. svr.wait_until_ready();
  18851. // The client supplies the first field line; the trusted proxy appends the
  18852. // address it observed as a second one.
  18853. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  18854. "Host: localhost\r\n"
  18855. "X-Forwarded-For: 1.2.3.4\r\n"
  18856. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  18857. "Connection: close\r\n"
  18858. "\r\n";
  18859. std::string out;
  18860. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18861. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18862. EXPECT_EQ(observed_xff_count, 2U);
  18863. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18864. // The same chain spread over one field line per hop derives the same client
  18865. // address, i.e. the split and the comma-joined representations agree.
  18866. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  18867. "Host: localhost\r\n"
  18868. "X-Forwarded-For: 1.2.3.4\r\n"
  18869. "X-Forwarded-For: 198.51.100.23\r\n"
  18870. "X-Forwarded-For: 192.0.2.45\r\n"
  18871. "Connection: close\r\n"
  18872. "\r\n";
  18873. out.clear();
  18874. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  18875. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18876. EXPECT_EQ(observed_xff_count, 3U);
  18877. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18878. }
  18879. // An X-Forwarded-For header whose value parses to zero IP segments must not
  18880. // crash the server (it used to call front() on an empty vector inside
  18881. // get_client_ip). The connection-level remote address must be retained instead.
  18882. static void run_malformed_xff_test(const std::string &xff_value) {
  18883. Server svr;
  18884. svr.set_trusted_proxies({"192.0.2.45"});
  18885. std::string observed_remote_addr;
  18886. svr.Get("/ip", [&](const Request &req, Response &res) {
  18887. observed_remote_addr = req.remote_addr;
  18888. res.set_content("ok", "text/plain");
  18889. });
  18890. int port = 0;
  18891. thread t = thread([&]() {
  18892. port = svr.bind_to_any_port(HOST);
  18893. svr.listen_after_bind();
  18894. });
  18895. auto se = detail::scope_exit([&] {
  18896. svr.stop();
  18897. t.join();
  18898. ASSERT_FALSE(svr.is_running());
  18899. });
  18900. svr.wait_until_ready();
  18901. Client cli(HOST, port);
  18902. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  18903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18904. EXPECT_EQ(StatusCode::OK_200, res->status);
  18905. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18906. observed_remote_addr == "127.0.0.1");
  18907. }
  18908. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  18909. run_malformed_xff_test("");
  18910. }
  18911. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  18912. run_malformed_xff_test(",");
  18913. }
  18914. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  18915. run_malformed_xff_test(", , ,");
  18916. }
  18917. // The same rule applies to Accept: a request whose acceptable types are spread
  18918. // over several field lines must be negotiated against all of them.
  18919. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  18920. // case-insensitive connection options. Comparing the whole field value against
  18921. // one option misses a client that sends several of them, and misses every
  18922. // casing but the one written in the comparison.
  18923. //
  18924. // Sends req, reads the response, then reuses the same socket for a second
  18925. // request to find out whether the server kept the connection.
  18926. static void probe_connection_reuse(int port, const std::string &req,
  18927. bool *announced_close, bool *reusable) {
  18928. auto error = Error::Success;
  18929. auto sock = detail::create_client_socket(
  18930. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18931. /*connection_timeout_sec=*/5, 0,
  18932. /*read_timeout_sec=*/1, 0,
  18933. /*write_timeout_sec=*/5, 0, std::string(), error);
  18934. ASSERT_NE(sock, INVALID_SOCKET);
  18935. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  18936. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  18937. "Host: localhost\r\n"
  18938. "Connection: close\r\n"
  18939. "\r\n";
  18940. std::string first_response;
  18941. std::string second_response;
  18942. detail::process_client_socket(
  18943. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  18944. [&](Stream &strm) {
  18945. if (strm.write(req.data(), req.size()) !=
  18946. static_cast<ssize_t>(req.size())) {
  18947. return false;
  18948. }
  18949. char buf[512];
  18950. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  18951. // Headers plus the two-byte body of the handler below
  18952. while (reader.getline()) {
  18953. first_response += reader.ptr();
  18954. if (first_response.find("ok") != std::string::npos) { break; }
  18955. }
  18956. if (strm.write(second.data(), second.size()) !=
  18957. static_cast<ssize_t>(second.size())) {
  18958. return true;
  18959. }
  18960. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  18961. while (reader2.getline()) {
  18962. second_response += reader2.ptr();
  18963. if (second_response.find("ok") != std::string::npos) { break; }
  18964. }
  18965. return true;
  18966. });
  18967. *announced_close =
  18968. first_response.find("Connection: close") != std::string::npos;
  18969. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18970. }
  18971. class ConnectionTokenTest : public ::testing::Test {
  18972. protected:
  18973. void SetUp() override {
  18974. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18975. res.set_content("ok", "text/plain");
  18976. });
  18977. port_ = svr_.bind_to_any_port(HOST);
  18978. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18979. svr_.wait_until_ready();
  18980. }
  18981. void TearDown() override {
  18982. svr_.stop();
  18983. if (thread_.joinable()) { thread_.join(); }
  18984. }
  18985. Server svr_;
  18986. int port_ = 0;
  18987. thread thread_;
  18988. };
  18989. // "close" alongside another option still closes the connection, and the
  18990. // response says so rather than leaving the peer to discover it.
  18991. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18992. bool announced_close = false;
  18993. bool reusable = true;
  18994. probe_connection_reuse(port_,
  18995. "GET /keepalive HTTP/1.1\r\n"
  18996. "Host: localhost\r\n"
  18997. "Connection: keep-alive, close\r\n"
  18998. "\r\n",
  18999. &announced_close, &reusable);
  19000. EXPECT_TRUE(announced_close);
  19001. EXPECT_FALSE(reusable);
  19002. }
  19003. // "close" split over two field lines is the same list, so it is honored too.
  19004. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19005. bool announced_close = false;
  19006. bool reusable = true;
  19007. probe_connection_reuse(port_,
  19008. "GET /keepalive HTTP/1.1\r\n"
  19009. "Host: localhost\r\n"
  19010. "Connection: keep-alive\r\n"
  19011. "Connection: close\r\n"
  19012. "\r\n",
  19013. &announced_close, &reusable);
  19014. EXPECT_TRUE(announced_close);
  19015. EXPECT_FALSE(reusable);
  19016. }
  19017. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19018. // keep-alive in the spelling everyone actually sends keeps its connection.
  19019. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19020. bool announced_close = false;
  19021. bool reusable = false;
  19022. probe_connection_reuse(port_,
  19023. "GET /keepalive HTTP/1.0\r\n"
  19024. "Host: localhost\r\n"
  19025. "Connection: keep-alive\r\n"
  19026. "\r\n",
  19027. &announced_close, &reusable);
  19028. EXPECT_FALSE(announced_close);
  19029. EXPECT_TRUE(reusable);
  19030. }
  19031. // A token the value merely contains is not the token itself.
  19032. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19033. bool announced_close = false;
  19034. bool reusable = false;
  19035. probe_connection_reuse(port_,
  19036. "GET /keepalive HTTP/1.1\r\n"
  19037. "Host: localhost\r\n"
  19038. "Connection: notclose\r\n"
  19039. "\r\n",
  19040. &announced_close, &reusable);
  19041. EXPECT_FALSE(announced_close);
  19042. EXPECT_TRUE(reusable);
  19043. }
  19044. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19045. Server svr;
  19046. std::vector<std::string> observed_types;
  19047. svr.Get("/", [&](const Request &req, Response &res) {
  19048. observed_types = req.accept_content_types;
  19049. res.set_content("ok", "text/plain");
  19050. });
  19051. auto port = svr.bind_to_any_port(HOST);
  19052. thread t = thread([&]() { svr.listen_after_bind(); });
  19053. auto se = detail::scope_exit([&] {
  19054. svr.stop();
  19055. t.join();
  19056. ASSERT_FALSE(svr.is_running());
  19057. });
  19058. svr.wait_until_ready();
  19059. Client cli(HOST, port);
  19060. Headers headers;
  19061. headers.emplace("Accept", "text/plain;q=0.5");
  19062. headers.emplace("Accept", "application/json");
  19063. auto res = cli.Get("/", headers);
  19064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19065. EXPECT_EQ(StatusCode::OK_200, res->status);
  19066. // Sorted by q-value, so the second field line's type comes first
  19067. ASSERT_EQ(2U, observed_types.size());
  19068. EXPECT_EQ("application/json", observed_types[0]);
  19069. EXPECT_EQ("text/plain", observed_types[1]);
  19070. }
  19071. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19072. // empty field line must not contribute a bare comma to the combined value.
  19073. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19074. Server svr;
  19075. std::vector<std::string> observed_types;
  19076. svr.Get("/", [&](const Request &req, Response &res) {
  19077. observed_types = req.accept_content_types;
  19078. res.set_content("ok", "text/plain");
  19079. });
  19080. auto port = svr.bind_to_any_port(HOST);
  19081. thread t = thread([&]() { svr.listen_after_bind(); });
  19082. auto se = detail::scope_exit([&] {
  19083. svr.stop();
  19084. t.join();
  19085. ASSERT_FALSE(svr.is_running());
  19086. });
  19087. svr.wait_until_ready();
  19088. // Empty first field line, then a real one
  19089. std::string raw_req = "GET / HTTP/1.1\r\n"
  19090. "Host: localhost\r\n"
  19091. "Accept:\r\n"
  19092. "Accept: application/json\r\n"
  19093. "Connection: close\r\n"
  19094. "\r\n";
  19095. std::string out;
  19096. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19097. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19098. ASSERT_EQ(1U, observed_types.size());
  19099. EXPECT_EQ("application/json", observed_types[0]);
  19100. }
  19101. // The skip in get_combined_header_value() is what keeps an empty field line
  19102. // from contributing a bare comma. Only a trailing empty field line exercises
  19103. // it: a leading one is already covered by the "combined is still empty" check,
  19104. // and parse_accept_header() now ignores the empty element either way, so the
  19105. // request-level test above can no longer tell the two apart.
  19106. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19107. Headers headers;
  19108. headers.emplace("Accept", "text/html");
  19109. headers.emplace("Accept", "");
  19110. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19111. headers.clear();
  19112. headers.emplace("Accept", "");
  19113. headers.emplace("Accept", "application/json");
  19114. EXPECT_EQ("application/json",
  19115. detail::get_combined_header_value(headers, "Accept"));
  19116. }
  19117. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19118. // An encoding offered on a later Accept-Encoding field line is still offered.
  19119. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19120. Server svr;
  19121. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19122. res.set_content(std::string(1024, 'x'), "text/plain");
  19123. });
  19124. auto port = svr.bind_to_any_port(HOST);
  19125. thread t = thread([&]() { svr.listen_after_bind(); });
  19126. auto se = detail::scope_exit([&] {
  19127. svr.stop();
  19128. t.join();
  19129. ASSERT_FALSE(svr.is_running());
  19130. });
  19131. svr.wait_until_ready();
  19132. Client cli(HOST, port);
  19133. cli.set_decompress(false);
  19134. Headers headers;
  19135. headers.emplace("Accept-Encoding", "identity");
  19136. headers.emplace("Accept-Encoding", "gzip");
  19137. auto res = cli.Get("/", headers);
  19138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19139. EXPECT_EQ(StatusCode::OK_200, res->status);
  19140. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19141. }
  19142. #endif
  19143. #ifndef _WIN32
  19144. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19145. Server svr;
  19146. svr.Post("/post", [&](const Request &req, Response &res) {
  19147. res.set_content(req.body, "text/plain");
  19148. });
  19149. svr.Put("/put", [&](const Request &req, Response &res) {
  19150. res.set_content(req.body, "text/plain");
  19151. });
  19152. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19153. res.set_content(req.body, "text/plain");
  19154. });
  19155. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19156. res.set_content(req.body, "text/plain");
  19157. });
  19158. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19159. auto se = detail::scope_exit([&] {
  19160. svr.stop();
  19161. t.join();
  19162. ASSERT_FALSE(svr.is_running());
  19163. });
  19164. svr.wait_until_ready();
  19165. std::string resp;
  19166. // POST without Content-Length
  19167. ASSERT_TRUE(send_request(5,
  19168. "POST /post HTTP/1.1\r\n"
  19169. "Host: localhost\r\n"
  19170. "Connection: close\r\n"
  19171. "\r\n",
  19172. &resp));
  19173. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19174. // PUT without Content-Length
  19175. resp.clear();
  19176. ASSERT_TRUE(send_request(5,
  19177. "PUT /put HTTP/1.1\r\n"
  19178. "Host: localhost\r\n"
  19179. "Connection: close\r\n"
  19180. "\r\n",
  19181. &resp));
  19182. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19183. // PATCH without Content-Length
  19184. resp.clear();
  19185. ASSERT_TRUE(send_request(5,
  19186. "PATCH /patch HTTP/1.1\r\n"
  19187. "Host: localhost\r\n"
  19188. "Connection: close\r\n"
  19189. "\r\n",
  19190. &resp));
  19191. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19192. // DELETE without Content-Length
  19193. resp.clear();
  19194. ASSERT_TRUE(send_request(5,
  19195. "DELETE /delete HTTP/1.1\r\n"
  19196. "Host: localhost\r\n"
  19197. "Connection: close\r\n"
  19198. "\r\n",
  19199. &resp));
  19200. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19201. }
  19202. #endif
  19203. //==============================================================================
  19204. // open_stream() Tests
  19205. //==============================================================================
  19206. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19207. std::string result;
  19208. char buf[8192];
  19209. ssize_t n;
  19210. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19211. result.append(buf, static_cast<size_t>(n));
  19212. }
  19213. return result;
  19214. }
  19215. // Mock stream for unit tests
  19216. class MockStream : public Stream {
  19217. public:
  19218. std::string data;
  19219. size_t pos = 0;
  19220. ssize_t error_after = -1; // -1 = no error
  19221. explicit MockStream(const std::string &d, ssize_t err = -1)
  19222. : data(d), error_after(err) {}
  19223. bool is_readable() const override { return true; }
  19224. bool wait_readable() const override { return true; }
  19225. bool wait_writable() const override { return true; }
  19226. ssize_t read(char *ptr, size_t size) override {
  19227. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19228. if (pos >= data.size()) return 0;
  19229. size_t limit =
  19230. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19231. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19232. std::memcpy(ptr, data.data() + pos, to_read);
  19233. pos += to_read;
  19234. return static_cast<ssize_t>(to_read);
  19235. }
  19236. ssize_t write(const char *, size_t) override { return -1; }
  19237. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19238. ip = "127.0.0.1";
  19239. port = 0;
  19240. }
  19241. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19242. ip = "127.0.0.1";
  19243. port = 0;
  19244. }
  19245. socket_t socket() const override { return INVALID_SOCKET; }
  19246. time_t duration() const override { return 0; }
  19247. };
  19248. TEST(StreamHandleTest, Basic) {
  19249. ClientImpl::StreamHandle handle;
  19250. EXPECT_FALSE(handle.is_valid());
  19251. handle.response = detail::make_unique<Response>();
  19252. handle.error = Error::Connection;
  19253. EXPECT_FALSE(handle.is_valid());
  19254. handle.error = Error::Success;
  19255. EXPECT_TRUE(handle.is_valid());
  19256. }
  19257. TEST(BodyReaderTest, Basic) {
  19258. MockStream stream("Hello, World!");
  19259. detail::BodyReader reader;
  19260. reader.stream = &stream;
  19261. reader.content_length = 13;
  19262. char buf[32];
  19263. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19264. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19265. EXPECT_TRUE(reader.eof);
  19266. }
  19267. TEST(BodyReaderTest, NoStream) {
  19268. detail::BodyReader reader;
  19269. char buf[32];
  19270. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19271. EXPECT_EQ(Error::Connection, reader.last_error);
  19272. }
  19273. TEST(BodyReaderTest, Error) {
  19274. MockStream stream("Hello, World!", 5);
  19275. detail::BodyReader reader;
  19276. reader.stream = &stream;
  19277. reader.content_length = 13;
  19278. char buf[32];
  19279. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19280. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19281. EXPECT_EQ(Error::Read, reader.last_error);
  19282. }
  19283. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19284. // Mock-based StreamHandle tests relying on private internals are removed.
  19285. class OpenStreamTest : public ::testing::Test {
  19286. protected:
  19287. void SetUp() override {
  19288. svr_.Get("/hello", [](const Request &, Response &res) {
  19289. res.set_content("Hello World!", "text/plain");
  19290. });
  19291. svr_.Get("/large", [](const Request &, Response &res) {
  19292. res.set_content(std::string(10000, 'X'), "text/plain");
  19293. });
  19294. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19295. res.set_content("Hello World!", "image/jpeg");
  19296. res.set_header("Content-Encoding", "UTF-8");
  19297. });
  19298. svr_.Get("/chunked", [](const Request &, Response &res) {
  19299. res.set_chunked_content_provider("text/plain",
  19300. [](size_t offset, DataSink &sink) {
  19301. if (offset < 15) {
  19302. sink.write("chunk", 5);
  19303. return true;
  19304. }
  19305. sink.done();
  19306. return true;
  19307. });
  19308. });
  19309. svr_.Get("/compressible", [](const Request &, Response &res) {
  19310. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19311. DataSink &sink) {
  19312. if (offset < 100 * 1024) {
  19313. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19314. sink.write(chunk.data(), chunk.size());
  19315. return true;
  19316. }
  19317. sink.done();
  19318. return true;
  19319. });
  19320. });
  19321. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19322. [](const Request & /*req*/, Response &res) {
  19323. auto i = new int(0);
  19324. res.set_header("Trailer", "Content-Length, X-Allowed");
  19325. res.set_chunked_content_provider(
  19326. "text/plain",
  19327. [i](size_t /*offset*/, DataSink &sink) {
  19328. switch (*i) {
  19329. case 0: sink.os << "123"; break;
  19330. case 1: sink.os << "456"; break;
  19331. case 2: sink.os << "789"; break;
  19332. case 3: {
  19333. sink.done_with_trailer(
  19334. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19335. } break;
  19336. }
  19337. (*i)++;
  19338. return true;
  19339. },
  19340. [i](bool success) {
  19341. EXPECT_TRUE(success);
  19342. delete i;
  19343. });
  19344. });
  19345. // Echo headers endpoint for header-related tests
  19346. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19347. std::string body;
  19348. for (const auto &h : req.headers) {
  19349. body.append(h.first);
  19350. body.push_back(':');
  19351. body.append(h.second);
  19352. body.push_back('\n');
  19353. }
  19354. res.set_content(body, "text/plain");
  19355. });
  19356. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19357. std::string body;
  19358. for (const auto &h : req.headers) {
  19359. body.append(h.first);
  19360. body.push_back(':');
  19361. body.append(h.second);
  19362. body.push_back('\n');
  19363. }
  19364. res.set_content(body, "text/plain");
  19365. });
  19366. port_ = svr_.bind_to_any_port("127.0.0.1");
  19367. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19368. svr_.wait_until_ready();
  19369. }
  19370. void TearDown() override {
  19371. svr_.stop();
  19372. if (thread_.joinable()) thread_.join();
  19373. }
  19374. Server svr_;
  19375. std::thread thread_;
  19376. int port_ = 0;
  19377. };
  19378. TEST_F(OpenStreamTest, Basic) {
  19379. Client cli("127.0.0.1", port_);
  19380. auto handle = cli.open_stream("GET", "/hello");
  19381. EXPECT_TRUE(handle.is_valid());
  19382. EXPECT_EQ("Hello World!", read_all(handle));
  19383. }
  19384. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19385. Client cli("127.0.0.1", port_);
  19386. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19387. ASSERT_TRUE(handle.is_valid());
  19388. EXPECT_EQ("Hello World!", read_all(handle));
  19389. }
  19390. TEST_F(OpenStreamTest, SmallBuffer) {
  19391. Client cli("127.0.0.1", port_);
  19392. auto handle = cli.open_stream("GET", "/hello");
  19393. std::string result;
  19394. char buf[4];
  19395. ssize_t n;
  19396. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19397. result.append(buf, static_cast<size_t>(n));
  19398. EXPECT_EQ("Hello World!", result);
  19399. }
  19400. TEST_F(OpenStreamTest, DefaultHeaders) {
  19401. Client cli("127.0.0.1", port_);
  19402. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19403. {
  19404. auto handle = cli.open_stream("GET", "/echo-headers");
  19405. ASSERT_TRUE(handle.is_valid());
  19406. auto body = read_all(handle);
  19407. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19408. std::string::npos);
  19409. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19410. std::string::npos);
  19411. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19412. }
  19413. // open_stream POST with body and no explicit content_type should NOT add
  19414. // text/plain Content-Type (behavior differs from non-streaming path), but
  19415. // should include Content-Length
  19416. {
  19417. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19418. ASSERT_TRUE(handle.is_valid());
  19419. auto body = read_all(handle);
  19420. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19421. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19422. }
  19423. // open_stream POST with explicit Content-Type should preserve it
  19424. {
  19425. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19426. {{"Content-Type", "application/custom"}},
  19427. "{}", "application/custom");
  19428. ASSERT_TRUE(handle.is_valid());
  19429. auto body = read_all(handle);
  19430. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19431. }
  19432. // User-specified User-Agent must not be overwritten for stream API
  19433. {
  19434. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19435. {{"User-Agent", "MyAgent/1.2"}});
  19436. ASSERT_TRUE(handle.is_valid());
  19437. auto body = read_all(handle);
  19438. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19439. }
  19440. }
  19441. TEST_F(OpenStreamTest, Large) {
  19442. Client cli("127.0.0.1", port_);
  19443. auto handle = cli.open_stream("GET", "/large");
  19444. EXPECT_EQ(10000u, read_all(handle).size());
  19445. }
  19446. TEST_F(OpenStreamTest, ConnectionError) {
  19447. Client cli("127.0.0.1", 9999);
  19448. auto handle = cli.open_stream("GET", "/hello");
  19449. EXPECT_FALSE(handle.is_valid());
  19450. }
  19451. TEST_F(OpenStreamTest, Chunked) {
  19452. Client cli("127.0.0.1", port_);
  19453. auto handle = cli.open_stream("GET", "/chunked");
  19454. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19455. "Transfer-Encoding") == "chunked");
  19456. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19457. }
  19458. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19459. Client cli("127.0.0.1", port_);
  19460. auto handle =
  19461. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19462. ASSERT_TRUE(handle.is_valid());
  19463. // Consume body to allow trailers to be received/parsed
  19464. auto body = read_all(handle);
  19465. // Explicitly parse trailers (ensure trailers are available for assertion)
  19466. handle.parse_trailers_if_needed();
  19467. EXPECT_EQ(std::string("123456789"), body);
  19468. // The response should include a Trailer header declaring both names
  19469. ASSERT_TRUE(handle.response);
  19470. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19471. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19472. handle.response->get_header_value("Trailer"));
  19473. // Prohibited trailer must not be present
  19474. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19475. // Allowed trailer should be present
  19476. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19477. EXPECT_EQ(std::string("yes"),
  19478. handle.response->get_trailer_value("X-Allowed"));
  19479. // Verify trailers are NOT present as regular headers
  19480. EXPECT_EQ(std::string(""),
  19481. handle.response->get_header_value("Content-Length"));
  19482. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19483. }
  19484. // Accepts one connection on an OS-assigned port, which it hands over through
  19485. // port_promise, reads the request head and sends back response. after_send,
  19486. // if given, runs on the connection before it is closed.
  19487. static std::thread
  19488. serve_single_response(std::promise<int> &port_promise,
  19489. const std::string &response,
  19490. std::function<void(socket_t)> after_send = nullptr) {
  19491. return std::thread([&port_promise, response, after_send] {
  19492. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19493. default_socket_options(srv);
  19494. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19495. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19496. sockaddr_in addr{};
  19497. addr.sin_family = AF_INET;
  19498. addr.sin_port = htons(0); // Let OS assign a free port
  19499. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19500. int opt = 1;
  19501. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19502. #ifdef _WIN32
  19503. reinterpret_cast<const char *>(&opt),
  19504. #else
  19505. &opt,
  19506. #endif
  19507. sizeof(opt));
  19508. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19509. ::listen(srv, 1) != 0) {
  19510. port_promise.set_value(-1);
  19511. detail::close_socket(srv);
  19512. return;
  19513. }
  19514. socklen_t addr_len = sizeof(addr);
  19515. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19516. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19517. sockaddr_in cli_addr{};
  19518. socklen_t cli_len = sizeof(cli_addr);
  19519. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19520. if (cli != INVALID_SOCKET) {
  19521. // Read the complete HTTP request (until the blank line that terminates
  19522. // headers) before sending the response. If the server closes the socket
  19523. // while the client's request data is still unread in the kernel receive
  19524. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19525. // connection on both sides: it discards the client's receive buffer
  19526. // (which already holds our response) and causes any in-progress write on
  19527. // the client to fail with ECONNRESET. Reading all request data first
  19528. // ensures close() emits a graceful FIN.
  19529. {
  19530. char rbuf[256];
  19531. std::string req;
  19532. while (req.find("\r\n\r\n") == std::string::npos) {
  19533. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19534. if (n <= 0) { break; }
  19535. req.append(rbuf, static_cast<size_t>(n));
  19536. }
  19537. }
  19538. ::send(cli,
  19539. #ifdef _WIN32
  19540. static_cast<const char *>(response.c_str()),
  19541. static_cast<int>(response.size()),
  19542. #else
  19543. response.c_str(), response.size(),
  19544. #endif
  19545. 0);
  19546. if (after_send) { after_send(cli); }
  19547. detail::close_socket(cli);
  19548. }
  19549. detail::close_socket(srv);
  19550. });
  19551. }
  19552. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19553. #ifndef _WIN32
  19554. signal(SIGPIPE, SIG_IGN);
  19555. #endif
  19556. std::promise<int> port_promise;
  19557. auto port_future = port_promise.get_future();
  19558. auto server_thread =
  19559. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19560. "Content-Type: text/plain\r\n"
  19561. "Content-Length: not-a-number\r\n"
  19562. "Connection: close\r\n"
  19563. "\r\n"
  19564. "hello");
  19565. auto port = port_future.get();
  19566. ASSERT_GT(port, 0);
  19567. Client cli("127.0.0.1", port);
  19568. auto handle = cli.open_stream("GET", "/");
  19569. EXPECT_FALSE(handle.is_valid());
  19570. server_thread.join();
  19571. }
  19572. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19573. #ifndef _WIN32
  19574. signal(SIGPIPE, SIG_IGN);
  19575. #endif
  19576. std::promise<int> port_promise;
  19577. auto port_future = port_promise.get_future();
  19578. auto server_thread = serve_single_response(
  19579. port_promise, "HTTP/1.1 200 OK\r\n"
  19580. "Content-Type: text/plain\r\n"
  19581. "Content-Length: 99999999999999999999999999\r\n"
  19582. "Connection: close\r\n"
  19583. "\r\n"
  19584. "hello");
  19585. auto port = port_future.get();
  19586. ASSERT_GT(port, 0);
  19587. // Historically std::stoull would throw std::out_of_range here and crash
  19588. // the process, then parsing silently clamped to a bogus framing length and
  19589. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19590. // so the stream fails to open, matching the not-a-number case above. The
  19591. // process still must NOT terminate.
  19592. Client cli("127.0.0.1", port);
  19593. auto handle = cli.open_stream("GET", "/");
  19594. EXPECT_FALSE(handle.is_valid());
  19595. server_thread.join();
  19596. }
  19597. // Serves `response` to the single request `fn` makes with a fresh client.
  19598. template <typename Fn>
  19599. static void with_single_response(const std::string &response, Fn fn) {
  19600. #ifndef _WIN32
  19601. signal(SIGPIPE, SIG_IGN);
  19602. #endif
  19603. std::promise<int> port_promise;
  19604. auto port_future = port_promise.get_future();
  19605. auto server_thread = serve_single_response(port_promise, response);
  19606. auto se = detail::scope_exit([&] { server_thread.join(); });
  19607. auto port = port_future.get();
  19608. ASSERT_GT(port, 0);
  19609. Client cli("127.0.0.1", port);
  19610. fn(cli);
  19611. }
  19612. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19613. const char *responses[] = {
  19614. "HTTP/1.1 103 Early Hints\r\n"
  19615. "Link: </style.css>; rel=preload\r\n"
  19616. "\r\n"
  19617. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19618. "HTTP/1.1 100 Continue\r\n"
  19619. "X-Note: interim\r\n"
  19620. "\r\n"
  19621. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19622. };
  19623. for (auto response : responses) {
  19624. with_single_response(response, [](Client &cli) {
  19625. auto res = cli.Get("/");
  19626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19627. EXPECT_EQ(StatusCode::OK_200, res->status);
  19628. EXPECT_EQ("ok", res->body);
  19629. });
  19630. }
  19631. }
  19632. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  19633. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  19634. const std::string final_response =
  19635. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19636. std::string interims;
  19637. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  19638. interims += interim;
  19639. }
  19640. with_single_response(interims + final_response, [](Client &cli) {
  19641. auto res = cli.Get("/");
  19642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19643. EXPECT_EQ("ok", res->body);
  19644. });
  19645. with_single_response(interims + interim + final_response, [](Client &cli) {
  19646. auto res = cli.Get("/");
  19647. ASSERT_FALSE(res);
  19648. EXPECT_EQ(Error::Read, res.error());
  19649. });
  19650. }
  19651. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19652. #ifndef _WIN32
  19653. signal(SIGPIPE, SIG_IGN);
  19654. #endif
  19655. // The server answers the head without asking for the body. Bytes it then
  19656. // reads on the connection would be taken for the body the request declared.
  19657. auto closed_by_client = false;
  19658. std::promise<int> port_promise;
  19659. auto server_thread = serve_single_response(
  19660. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  19661. [&](socket_t sock) {
  19662. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19663. char buf[256];
  19664. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  19665. });
  19666. Client cli("127.0.0.1", port_promise.get_future().get());
  19667. cli.set_keep_alive(true);
  19668. cli.set_read_timeout(1, 0);
  19669. // Long enough for the client to send Expect: 100-continue.
  19670. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19672. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19673. cli.Get("/second");
  19674. server_thread.join();
  19675. EXPECT_TRUE(closed_by_client);
  19676. }
  19677. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  19678. // Long enough for the client to send Expect: 100-continue
  19679. with_single_response(
  19680. "HTTP/1.1 103 Early Hints\r\n"
  19681. "Link: </style.css>; rel=preload\r\n"
  19682. "\r\n"
  19683. "HTTP/1.1 401 Unauthorized\r\n"
  19684. "Content-Length: 0\r\n\r\n",
  19685. [](Client &cli) {
  19686. cli.set_read_timeout(2, 0);
  19687. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19689. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19690. });
  19691. }
  19692. #ifdef CPPHTTPLIB_SSL_ENABLED
  19693. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  19694. #ifndef _WIN32
  19695. signal(SIGPIPE, SIG_IGN);
  19696. #endif
  19697. auto reused = false;
  19698. std::promise<int> port_promise;
  19699. auto server_thread = serve_single_response(
  19700. port_promise,
  19701. "HTTP/1.1 401 Unauthorized\r\n"
  19702. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  19703. "Content-Length: 0\r\n\r\n",
  19704. [&](socket_t sock) {
  19705. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19706. char buf[256];
  19707. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  19708. });
  19709. Client cli("127.0.0.1", port_promise.get_future().get());
  19710. cli.set_keep_alive(true);
  19711. cli.set_digest_auth("user", "pass");
  19712. cli.set_read_timeout(1, 0);
  19713. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19714. server_thread.join();
  19715. EXPECT_FALSE(reused);
  19716. }
  19717. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  19718. // Any other answer to CONNECT would read as the origin's response.
  19719. struct {
  19720. const char *response;
  19721. bool passed_on;
  19722. } cases[] = {
  19723. {"HTTP/1.1 201 Created\r\n"
  19724. "Set-Cookie: session=from-proxy\r\n"
  19725. "Content-Length: 0\r\n\r\n",
  19726. false},
  19727. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  19728. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  19729. "Content-Length: 0\r\n\r\n",
  19730. true},
  19731. };
  19732. for (const auto &c : cases) {
  19733. std::promise<int> port_promise;
  19734. auto server_thread = serve_single_response(port_promise, c.response);
  19735. SSLClient cli("example.com", 443);
  19736. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  19737. auto res = cli.Get("/");
  19738. server_thread.join();
  19739. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  19740. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  19741. if (res) {
  19742. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19743. }
  19744. }
  19745. }
  19746. #endif
  19747. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  19748. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  19749. // the chunked coding and drop Content-Length, so a front-end that trusts
  19750. // Content-Length would disagree about where the body ends (response
  19751. // smuggling). The client must reject such a response.
  19752. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19753. for (const char *te : {"chunked", "gzip, chunked"}) {
  19754. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  19755. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  19756. "\r\n" + "Connection: close\r\n" + "\r\n" +
  19757. "5\r\nhello\r\n0\r\n\r\n";
  19758. with_single_response(response, [&](Client &cli) {
  19759. auto res = cli.Get("/");
  19760. EXPECT_FALSE(static_cast<bool>(res)) << te;
  19761. EXPECT_EQ(Error::Read, res.error()) << te;
  19762. });
  19763. with_single_response(response, [&](Client &cli) {
  19764. auto handle = cli.open_stream("GET", "/");
  19765. EXPECT_FALSE(handle.is_valid()) << te;
  19766. EXPECT_EQ(Error::Read, handle.error) << te;
  19767. });
  19768. }
  19769. }
  19770. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  19771. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  19772. // closing the connection (unlike a request, which must be rejected).
  19773. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  19774. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19775. "Transfer-Encoding: chunked\r\n"
  19776. "Connection: close\r\n"
  19777. "\r\n"
  19778. "5\r\nhello\r\n0\r\n\r\n",
  19779. "HTTP/1.1 200 OK\r\n"
  19780. "Transfer-Encoding: gzip\r\n"
  19781. "Connection: close\r\n"
  19782. "\r\n"
  19783. "hello"}) {
  19784. with_single_response(response, [&](Client &cli) {
  19785. auto res = cli.Get("/");
  19786. ASSERT_TRUE(static_cast<bool>(res)) << response;
  19787. EXPECT_EQ("hello", res->body);
  19788. });
  19789. with_single_response(response, [&](Client &cli) {
  19790. auto handle = cli.open_stream("GET", "/");
  19791. ASSERT_TRUE(handle.is_valid()) << response;
  19792. EXPECT_EQ("hello", read_all(handle));
  19793. });
  19794. }
  19795. }
  19796. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  19797. // framing headers describe nothing to read and must not be rejected.
  19798. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  19799. const std::string framing = "Content-Length: 5\r\n"
  19800. "Transfer-Encoding: chunked\r\n"
  19801. "Connection: close\r\n"
  19802. "\r\n";
  19803. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19804. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  19805. });
  19806. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19807. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  19808. });
  19809. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  19810. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  19811. with_single_response(response, [&](Client &cli) {
  19812. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  19813. });
  19814. with_single_response(response, [&](Client &cli) {
  19815. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  19816. });
  19817. }
  19818. }
  19819. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  19820. // response, is faulty framing, so the connection is not reused after it.
  19821. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  19822. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19823. "Content-Length: 0\r\n"
  19824. "Transfer-Encoding: chunked\r\n"
  19825. "\r\n"
  19826. "5\r\nhello\r\n0\r\n\r\n",
  19827. "HTTP/1.0 200 Connection established\r\n"
  19828. "Connection: keep-alive\r\n"
  19829. "Transfer-Encoding: chunked\r\n"
  19830. "\r\n"
  19831. "5\r\nhello\r\n0\r\n\r\n"}) {
  19832. with_single_response(response, [&](Client &cli) {
  19833. cli.set_keep_alive(true);
  19834. auto res = cli.Get("/");
  19835. ASSERT_TRUE(res) << response;
  19836. EXPECT_EQ("hello", res->body);
  19837. EXPECT_FALSE(cli.is_socket_open()) << response;
  19838. });
  19839. }
  19840. }
  19841. // A payload max length of 0 means no limit, however the body is framed.
  19842. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  19843. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19844. "Transfer-Encoding: chunked\r\n"
  19845. "\r\n"
  19846. "5\r\nhello\r\n0\r\n\r\n",
  19847. "HTTP/1.1 200 OK\r\n"
  19848. "Connection: close\r\n"
  19849. "\r\n"
  19850. "hello"}) {
  19851. with_single_response(response, [&](Client &cli) {
  19852. cli.set_payload_max_length(0);
  19853. auto res = cli.Get("/");
  19854. ASSERT_TRUE(res) << response;
  19855. EXPECT_EQ("hello", res->body) << response;
  19856. });
  19857. }
  19858. }
  19859. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  19860. Server svr;
  19861. svr.set_payload_max_length(0);
  19862. svr.Post("/echo", [](const Request &req, Response &res) {
  19863. res.set_content(req.body, "text/plain");
  19864. });
  19865. auto port = svr.bind_to_any_port(HOST);
  19866. thread t = thread([&] { svr.listen_after_bind(); });
  19867. auto se = detail::scope_exit([&] {
  19868. svr.stop();
  19869. t.join();
  19870. ASSERT_FALSE(svr.is_running());
  19871. });
  19872. svr.wait_until_ready();
  19873. Client cli(HOST, port);
  19874. auto res = cli.Post(
  19875. "/echo",
  19876. [](size_t /*offset*/, DataSink &sink) {
  19877. sink.write("hello", 5);
  19878. sink.done();
  19879. return true;
  19880. },
  19881. "text/plain");
  19882. ASSERT_TRUE(res);
  19883. EXPECT_EQ(StatusCode::OK_200, res->status);
  19884. EXPECT_EQ("hello", res->body);
  19885. }
  19886. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19887. TEST_F(OpenStreamTest, Gzip) {
  19888. Client cli("127.0.0.1", port_);
  19889. auto handle = cli.open_stream("GET", "/compressible", {},
  19890. {{"Accept-Encoding", "gzip"}});
  19891. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  19892. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19893. }
  19894. #endif
  19895. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19896. TEST_F(OpenStreamTest, Brotli) {
  19897. Client cli("127.0.0.1", port_);
  19898. auto handle =
  19899. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  19900. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  19901. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19902. }
  19903. #endif
  19904. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19905. TEST_F(OpenStreamTest, Zstd) {
  19906. Client cli("127.0.0.1", port_);
  19907. auto handle = cli.open_stream("GET", "/compressible", {},
  19908. {{"Accept-Encoding", "zstd"}});
  19909. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  19910. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19911. }
  19912. #endif
  19913. #ifdef CPPHTTPLIB_SSL_ENABLED
  19914. class SSLOpenStreamTest : public ::testing::Test {
  19915. protected:
  19916. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  19917. void SetUp() override {
  19918. svr_.Get("/hello", [](const Request &, Response &res) {
  19919. res.set_content("Hello SSL World!", "text/plain");
  19920. });
  19921. svr_.Get("/chunked", [](const Request &, Response &res) {
  19922. res.set_chunked_content_provider("text/plain",
  19923. [](size_t offset, DataSink &sink) {
  19924. if (offset < 15) {
  19925. sink.write("chunk", 5);
  19926. return true;
  19927. }
  19928. sink.done();
  19929. return true;
  19930. });
  19931. });
  19932. svr_.Post("/echo", [](const Request &req, Response &res) {
  19933. res.set_content(req.body, req.get_header_value("Content-Type"));
  19934. });
  19935. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  19936. std::string body = req.body;
  19937. res.set_chunked_content_provider(
  19938. "text/plain", [body](size_t offset, DataSink &sink) {
  19939. if (offset < body.size()) {
  19940. sink.write(body.data() + offset, body.size() - offset);
  19941. }
  19942. sink.done();
  19943. return true;
  19944. });
  19945. });
  19946. port_ = svr_.bind_to_any_port("127.0.0.1");
  19947. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19948. svr_.wait_until_ready();
  19949. }
  19950. void TearDown() override {
  19951. svr_.stop();
  19952. if (thread_.joinable()) thread_.join();
  19953. }
  19954. SSLServer svr_;
  19955. std::thread thread_;
  19956. int port_ = 0;
  19957. };
  19958. TEST_F(SSLOpenStreamTest, Basic) {
  19959. SSLClient cli("127.0.0.1", port_);
  19960. cli.enable_server_certificate_verification(false);
  19961. auto handle = cli.open_stream("GET", "/hello");
  19962. ASSERT_TRUE(handle.is_valid());
  19963. EXPECT_EQ("Hello SSL World!", read_all(handle));
  19964. }
  19965. TEST_F(SSLOpenStreamTest, Chunked) {
  19966. SSLClient cli("127.0.0.1", port_);
  19967. cli.enable_server_certificate_verification(false);
  19968. auto handle = cli.open_stream("GET", "/chunked");
  19969. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19970. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19971. "Transfer-Encoding") == "chunked");
  19972. auto body = read_all(handle);
  19973. EXPECT_EQ("chunkchunkchunk", body);
  19974. }
  19975. TEST_F(SSLOpenStreamTest, Post) {
  19976. SSLClient cli("127.0.0.1", port_);
  19977. cli.enable_server_certificate_verification(false);
  19978. auto handle =
  19979. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  19980. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19981. EXPECT_EQ(200, handle.response->status);
  19982. auto body = read_all(handle);
  19983. EXPECT_EQ("Hello SSL POST", body);
  19984. }
  19985. TEST_F(SSLOpenStreamTest, PostChunked) {
  19986. SSLClient cli("127.0.0.1", port_);
  19987. cli.enable_server_certificate_verification(false);
  19988. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  19989. "Chunked SSL Data", "text/plain");
  19990. ASSERT_TRUE(handle.is_valid());
  19991. EXPECT_EQ(200, handle.response->status);
  19992. auto body = read_all(handle);
  19993. EXPECT_EQ("Chunked SSL Data", body);
  19994. }
  19995. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  19996. // Content-Length is terminated by the server closing the connection. When the
  19997. // SSL peer sends a close_notify after the body, the client must treat it as a
  19998. // clean EOF and return a successful response rather than an error.
  19999. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  20000. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20001. ASSERT_TRUE(svr.is_valid());
  20002. svr.set_keep_alive_max_count(1);
  20003. const std::string expected_body = "Hello from connection-close response!";
  20004. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  20005. res.set_content_provider("text/plain",
  20006. [&](size_t offset, DataSink &sink) -> bool {
  20007. if (offset < expected_body.size()) {
  20008. sink.write(expected_body.data() + offset,
  20009. expected_body.size() - offset);
  20010. }
  20011. sink.done();
  20012. return true;
  20013. });
  20014. });
  20015. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20016. auto se = detail::scope_exit([&] {
  20017. svr.stop();
  20018. listen_thread.join();
  20019. ASSERT_FALSE(svr.is_running());
  20020. });
  20021. svr.wait_until_ready();
  20022. SSLClient cli(HOST, PORT);
  20023. cli.enable_server_certificate_verification(false);
  20024. auto res = cli.Get("/no-content-length");
  20025. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20026. EXPECT_EQ(StatusCode::OK_200, res->status);
  20027. EXPECT_EQ(expected_body, res->body);
  20028. }
  20029. #endif // CPPHTTPLIB_SSL_ENABLED
  20030. //==============================================================================
  20031. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20032. // results for various scenarios.
  20033. //==============================================================================
  20034. TEST(ParityTest, GetVsOpenStream) {
  20035. Server svr;
  20036. const std::string path = "/parity";
  20037. const std::string content = "Parity test content: hello world";
  20038. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20039. res.set_content(content, "text/plain");
  20040. });
  20041. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20042. auto se = detail::scope_exit([&] {
  20043. svr.stop();
  20044. t.join();
  20045. ASSERT_FALSE(svr.is_running());
  20046. });
  20047. svr.wait_until_ready();
  20048. Client cli(HOST, PORT);
  20049. // Non-stream path
  20050. auto r1 = cli.Get(path);
  20051. ASSERT_TRUE(r1);
  20052. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20053. // Stream path
  20054. auto h = cli.open_stream("GET", path);
  20055. ASSERT_TRUE(h.is_valid());
  20056. EXPECT_EQ(r1->body, read_all(h));
  20057. }
  20058. // Helper to compress data with provided compressor type T
  20059. template <typename Compressor>
  20060. static std::string compress_payload_for_parity(const std::string &in) {
  20061. std::string out;
  20062. Compressor compressor;
  20063. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  20064. [&](const char *data, size_t n) {
  20065. out.append(data, n);
  20066. return true;
  20067. });
  20068. EXPECT_TRUE(ok);
  20069. return out;
  20070. }
  20071. // Helper function for compression parity tests
  20072. template <typename Compressor>
  20073. static void test_compression_parity(const std::string &original,
  20074. const std::string &path,
  20075. const std::string &encoding) {
  20076. const std::string compressed =
  20077. compress_payload_for_parity<Compressor>(original);
  20078. Server svr;
  20079. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20080. res.set_content(compressed, "application/octet-stream");
  20081. res.set_header("Content-Encoding", encoding);
  20082. });
  20083. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  20084. auto se = detail::scope_exit([&] {
  20085. svr.stop();
  20086. t.join();
  20087. ASSERT_FALSE(svr.is_running());
  20088. });
  20089. svr.wait_until_ready();
  20090. Client cli(HOST, PORT);
  20091. // Non-streaming
  20092. {
  20093. auto res = cli.Get(path);
  20094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20095. EXPECT_EQ(StatusCode::OK_200, res->status);
  20096. EXPECT_EQ(original, res->body);
  20097. }
  20098. // Streaming
  20099. {
  20100. auto h = cli.open_stream("GET", path);
  20101. ASSERT_TRUE(h.is_valid());
  20102. EXPECT_EQ(original, read_all(h));
  20103. }
  20104. }
  20105. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20106. TEST(ParityTest, Gzip) {
  20107. test_compression_parity<detail::gzip_compressor>(
  20108. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  20109. }
  20110. #endif
  20111. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20112. TEST(ParityTest, Brotli) {
  20113. test_compression_parity<detail::brotli_compressor>(
  20114. "Hello, brotli parity test payload", "/parity-br", "br");
  20115. }
  20116. #endif
  20117. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20118. TEST(ParityTest, Zstd) {
  20119. test_compression_parity<detail::zstd_compressor>(
  20120. "Zstandard parity test payload", "/parity-zstd", "zstd");
  20121. }
  20122. #endif
  20123. //==============================================================================
  20124. // New Stream API Tests
  20125. //==============================================================================
  20126. inline std::string read_body(httplib::stream::Result &result) {
  20127. std::string body;
  20128. while (result.next()) {
  20129. body.append(result.data(), result.size());
  20130. }
  20131. return body;
  20132. }
  20133. TEST(ClientConnectionTest, Basic) {
  20134. httplib::ClientConnection conn;
  20135. EXPECT_FALSE(conn.is_open());
  20136. conn.sock = 1;
  20137. EXPECT_TRUE(conn.is_open());
  20138. httplib::ClientConnection conn2(std::move(conn));
  20139. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  20140. conn2.sock = INVALID_SOCKET;
  20141. }
  20142. // Unified test server for all stream::* tests
  20143. class StreamApiTest : public ::testing::Test {
  20144. protected:
  20145. void SetUp() override {
  20146. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20147. res.set_content("Hello World!", "text/plain");
  20148. });
  20149. svr_.Get("/echo-params",
  20150. [](const httplib::Request &req, httplib::Response &res) {
  20151. std::string r;
  20152. for (const auto &p : req.params) {
  20153. if (!r.empty()) r += "&";
  20154. r += p.first + "=" + p.second;
  20155. }
  20156. res.set_content(r, "text/plain");
  20157. });
  20158. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20159. res.set_content(req.body, req.get_header_value("Content-Type"));
  20160. });
  20161. svr_.Post("/echo-headers",
  20162. [](const httplib::Request &req, httplib::Response &res) {
  20163. std::string r;
  20164. for (const auto &h : req.headers)
  20165. r += h.first + ": " + h.second + "\n";
  20166. res.set_content(r, "text/plain");
  20167. });
  20168. svr_.Post("/echo-params",
  20169. [](const httplib::Request &req, httplib::Response &res) {
  20170. std::string r = "params:";
  20171. for (const auto &p : req.params)
  20172. r += p.first + "=" + p.second + ";";
  20173. res.set_content(r + " body:" + req.body, "text/plain");
  20174. });
  20175. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20176. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20177. });
  20178. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20179. res.set_content("PUT:" + req.body, "text/plain");
  20180. });
  20181. svr_.Patch("/echo",
  20182. [](const httplib::Request &req, httplib::Response &res) {
  20183. res.set_content("PATCH:" + req.body, "text/plain");
  20184. });
  20185. svr_.Delete(
  20186. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  20187. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  20188. "text/plain");
  20189. });
  20190. svr_.Get("/head-test",
  20191. [](const httplib::Request &, httplib::Response &res) {
  20192. res.set_content("body for HEAD", "text/plain");
  20193. });
  20194. svr_.Options("/options",
  20195. [](const httplib::Request &, httplib::Response &res) {
  20196. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  20197. });
  20198. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  20199. svr_.wait_until_ready();
  20200. }
  20201. void TearDown() override {
  20202. svr_.stop();
  20203. if (thread_.joinable()) thread_.join();
  20204. }
  20205. httplib::Server svr_;
  20206. std::thread thread_;
  20207. };
  20208. // stream::Get tests
  20209. TEST_F(StreamApiTest, GetBasic) {
  20210. httplib::Client cli(HOST, PORT);
  20211. auto result = httplib::stream::Get(cli, "/hello");
  20212. ASSERT_TRUE(result.is_valid());
  20213. EXPECT_EQ(200, result.status());
  20214. EXPECT_EQ("Hello World!", read_body(result));
  20215. }
  20216. TEST_F(StreamApiTest, GetWithParams) {
  20217. httplib::Client cli(HOST, PORT);
  20218. httplib::Params params{{"foo", "bar"}};
  20219. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20220. ASSERT_TRUE(result.is_valid());
  20221. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20222. }
  20223. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20224. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20225. httplib::Client cli(HOST, PORT);
  20226. cli.set_payload_max_length(0);
  20227. auto result = httplib::stream::Get(cli, "/hello");
  20228. ASSERT_TRUE(result.is_valid());
  20229. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20230. EXPECT_EQ("Hello World!", read_body(result));
  20231. }
  20232. #endif
  20233. TEST_F(StreamApiTest, GetConnectionError) {
  20234. httplib::Client cli(HOST, 9999);
  20235. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  20236. }
  20237. TEST_F(StreamApiTest, Get404) {
  20238. httplib::Client cli(HOST, PORT);
  20239. auto result = httplib::stream::Get(cli, "/nonexistent");
  20240. EXPECT_TRUE(result.is_valid());
  20241. EXPECT_EQ(404, result.status());
  20242. }
  20243. // stream::Post tests
  20244. TEST_F(StreamApiTest, PostBasic) {
  20245. httplib::Client cli(HOST, PORT);
  20246. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  20247. "application/json");
  20248. ASSERT_TRUE(result.is_valid());
  20249. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  20250. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  20251. }
  20252. TEST_F(StreamApiTest, PostWithHeaders) {
  20253. httplib::Client cli(HOST, PORT);
  20254. httplib::Headers headers{{"X-Custom", "value"}};
  20255. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  20256. "text/plain");
  20257. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  20258. }
  20259. TEST_F(StreamApiTest, PostWithParams) {
  20260. httplib::Client cli(HOST, PORT);
  20261. httplib::Params params{{"k", "v"}};
  20262. auto result =
  20263. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  20264. auto body = read_body(result);
  20265. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  20266. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  20267. }
  20268. TEST_F(StreamApiTest, PostLarge) {
  20269. httplib::Client cli(HOST, PORT);
  20270. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  20271. size_t total = 0;
  20272. while (result.next()) {
  20273. total += result.size();
  20274. }
  20275. EXPECT_EQ(100u * 1024u, total);
  20276. }
  20277. // stream::Put/Patch tests
  20278. TEST_F(StreamApiTest, PutAndPatch) {
  20279. httplib::Client cli(HOST, PORT);
  20280. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  20281. EXPECT_EQ("PUT:test", read_body(put));
  20282. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  20283. EXPECT_EQ("PATCH:test", read_body(patch));
  20284. }
  20285. // stream::Delete tests
  20286. TEST_F(StreamApiTest, Delete) {
  20287. httplib::Client cli(HOST, PORT);
  20288. auto del1 = httplib::stream::Delete(cli, "/resource");
  20289. EXPECT_EQ("Deleted", read_body(del1));
  20290. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  20291. EXPECT_EQ("Deleted:data", read_body(del2));
  20292. }
  20293. // stream::Head/Options tests
  20294. TEST_F(StreamApiTest, HeadAndOptions) {
  20295. httplib::Client cli(HOST, PORT);
  20296. auto head = httplib::stream::Head(cli, "/head-test");
  20297. EXPECT_TRUE(head.is_valid());
  20298. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  20299. auto opts = httplib::stream::Options(cli, "/options");
  20300. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  20301. }
  20302. // SSL stream::* tests
  20303. #ifdef CPPHTTPLIB_SSL_ENABLED
  20304. class SSLStreamApiTest : public ::testing::Test {
  20305. protected:
  20306. void SetUp() override {
  20307. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20308. res.set_content("Hello SSL!", "text/plain");
  20309. });
  20310. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20311. res.set_content(req.body, "text/plain");
  20312. });
  20313. port_ = svr_.bind_to_any_port("127.0.0.1");
  20314. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20315. svr_.wait_until_ready();
  20316. }
  20317. void TearDown() override {
  20318. svr_.stop();
  20319. if (thread_.joinable()) thread_.join();
  20320. }
  20321. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  20322. std::thread thread_;
  20323. int port_ = 0;
  20324. };
  20325. TEST_F(SSLStreamApiTest, GetAndPost) {
  20326. httplib::SSLClient cli("127.0.0.1", port_);
  20327. cli.enable_server_certificate_verification(false);
  20328. auto get = httplib::stream::Get(cli, "/hello");
  20329. EXPECT_EQ("Hello SSL!", read_body(get));
  20330. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  20331. EXPECT_EQ("test", read_body(post));
  20332. }
  20333. #endif
  20334. // Tests for Error::Timeout and Error::ConnectionClosed error types
  20335. // These errors are set in SocketStream/SSLSocketStream and propagated through
  20336. // BodyReader
  20337. TEST(ErrorHandlingTest, StreamReadTimeout) {
  20338. // Test that read timeout during streaming is detected
  20339. // Use a large content-length response where server delays mid-stream
  20340. Server svr;
  20341. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20342. // Send a large response with delay in the middle
  20343. res.set_content_provider(
  20344. 1000, // content_length
  20345. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  20346. if (offset < 100) {
  20347. // Send first 100 bytes immediately
  20348. std::string data(100, 'A');
  20349. sink.write(data.c_str(), data.size());
  20350. return true;
  20351. }
  20352. // Then delay longer than client timeout
  20353. std::this_thread::sleep_for(std::chrono::seconds(3));
  20354. std::string data(900, 'B');
  20355. sink.write(data.c_str(), data.size());
  20356. return true;
  20357. });
  20358. });
  20359. auto port = 8091;
  20360. std::thread t([&]() { svr.listen("localhost", port); });
  20361. svr.wait_until_ready();
  20362. Client cli("localhost", port);
  20363. cli.set_read_timeout(1, 0); // 1 second timeout
  20364. auto handle = cli.open_stream("GET", "/slow-stream");
  20365. ASSERT_TRUE(handle.is_valid());
  20366. char buf[256];
  20367. ssize_t total = 0;
  20368. ssize_t n;
  20369. bool got_error = false;
  20370. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20371. total += n;
  20372. }
  20373. if (n < 0) {
  20374. got_error = true;
  20375. // Should be timeout or read error
  20376. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20377. handle.get_read_error() == Error::Read)
  20378. << "Actual error: " << to_string(handle.get_read_error());
  20379. }
  20380. // Either we got an error, or we got less data than expected
  20381. EXPECT_TRUE(got_error || total < 1000)
  20382. << "Expected timeout but got all " << total << " bytes";
  20383. svr.stop();
  20384. t.join();
  20385. }
  20386. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  20387. // Test connection closed detection via BodyReader
  20388. Server svr;
  20389. std::atomic<bool> close_now{false};
  20390. svr.Get("/will-close", [&](const Request &, Response &res) {
  20391. res.set_content_provider(
  20392. 10000, // Large content_length that we won't fully send
  20393. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20394. if (offset < 100) {
  20395. std::string data(100, 'X');
  20396. sink.write(data.c_str(), data.size());
  20397. return true;
  20398. }
  20399. // Wait for signal then abort
  20400. while (!close_now) {
  20401. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20402. }
  20403. return false; // Abort - server will close connection
  20404. });
  20405. });
  20406. auto port = 8092;
  20407. std::thread t([&]() { svr.listen("localhost", port); });
  20408. svr.wait_until_ready();
  20409. Client cli("localhost", port);
  20410. auto handle = cli.open_stream("GET", "/will-close");
  20411. ASSERT_TRUE(handle.is_valid());
  20412. char buf[256];
  20413. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20414. EXPECT_GT(n, 0) << "First read should succeed";
  20415. // Signal server to close
  20416. close_now = true;
  20417. // Keep reading until error or EOF
  20418. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20419. // Keep reading
  20420. }
  20421. // Should get an error since content_length wasn't satisfied
  20422. if (n < 0) {
  20423. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20424. handle.get_read_error() == Error::Read)
  20425. << "Actual error: " << to_string(handle.get_read_error());
  20426. }
  20427. svr.stop();
  20428. t.join();
  20429. }
  20430. #ifdef CPPHTTPLIB_SSL_ENABLED
  20431. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  20432. // Test that read timeout during SSL streaming is detected
  20433. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20434. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20435. res.set_content_provider(
  20436. 1000, "text/plain",
  20437. [](size_t offset, size_t /*length*/, DataSink &sink) {
  20438. if (offset < 100) {
  20439. std::string data(100, 'A');
  20440. sink.write(data.c_str(), data.size());
  20441. return true;
  20442. }
  20443. std::this_thread::sleep_for(std::chrono::seconds(3));
  20444. std::string data(900, 'B');
  20445. sink.write(data.c_str(), data.size());
  20446. return true;
  20447. });
  20448. });
  20449. auto port = 8093;
  20450. std::thread t([&]() { svr.listen("localhost", port); });
  20451. svr.wait_until_ready();
  20452. SSLClient cli("localhost", port);
  20453. cli.enable_server_certificate_verification(false);
  20454. cli.set_read_timeout(1, 0); // 1 second timeout
  20455. auto handle = cli.open_stream("GET", "/slow-stream");
  20456. ASSERT_TRUE(handle.is_valid());
  20457. char buf[256];
  20458. ssize_t total = 0;
  20459. ssize_t n;
  20460. bool got_error = false;
  20461. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20462. total += n;
  20463. }
  20464. if (n < 0) {
  20465. got_error = true;
  20466. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20467. handle.get_read_error() == Error::Read)
  20468. << "Actual error: " << to_string(handle.get_read_error());
  20469. }
  20470. EXPECT_TRUE(got_error || total < 1000)
  20471. << "Expected timeout but got all " << total << " bytes";
  20472. svr.stop();
  20473. t.join();
  20474. }
  20475. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  20476. // Test SSL connection closed detection
  20477. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20478. std::atomic<bool> close_now{false};
  20479. svr.Get("/will-close", [&](const Request &, Response &res) {
  20480. res.set_content_provider(
  20481. 10000, "text/plain",
  20482. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20483. if (offset < 100) {
  20484. std::string data(100, 'X');
  20485. sink.write(data.c_str(), data.size());
  20486. return true;
  20487. }
  20488. while (!close_now) {
  20489. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20490. }
  20491. return false;
  20492. });
  20493. });
  20494. auto port = 8094;
  20495. std::thread t([&]() { svr.listen("localhost", port); });
  20496. svr.wait_until_ready();
  20497. SSLClient cli("localhost", port);
  20498. cli.enable_server_certificate_verification(false);
  20499. auto handle = cli.open_stream("GET", "/will-close");
  20500. ASSERT_TRUE(handle.is_valid());
  20501. char buf[256];
  20502. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20503. EXPECT_GT(n, 0);
  20504. // Signal server to close
  20505. close_now = true;
  20506. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20507. // Keep reading
  20508. }
  20509. if (n < 0) {
  20510. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20511. handle.get_read_error() == Error::Read)
  20512. << "Actual error: " << to_string(handle.get_read_error());
  20513. }
  20514. svr.stop();
  20515. t.join();
  20516. }
  20517. #endif
  20518. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  20519. using namespace httplib;
  20520. // Create a test file
  20521. const char *fname = "etag_testfile.txt";
  20522. const char *content = "etag-content";
  20523. {
  20524. std::ofstream ofs(fname);
  20525. ofs << content;
  20526. ASSERT_TRUE(ofs.good());
  20527. }
  20528. Server svr;
  20529. svr.set_mount_point("/static", ".");
  20530. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20531. svr.wait_until_ready();
  20532. Client cli(HOST, PORT);
  20533. // First request: should get 200 with ETag header
  20534. auto res1 = cli.Get("/static/etag_testfile.txt");
  20535. ASSERT_TRUE(res1);
  20536. ASSERT_EQ(200, res1->status);
  20537. ASSERT_TRUE(res1->has_header("ETag"));
  20538. std::string etag = res1->get_header_value("ETag");
  20539. EXPECT_FALSE(etag.empty());
  20540. // Verify ETag format: W/"hex-hex"
  20541. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  20542. EXPECT_EQ('W', etag[0]);
  20543. EXPECT_EQ('/', etag[1]);
  20544. EXPECT_EQ('"', etag[2]);
  20545. EXPECT_EQ('"', etag.back());
  20546. // Exact match: expect 304 Not Modified
  20547. Headers h2 = {{"If-None-Match", etag}};
  20548. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  20549. ASSERT_TRUE(res2);
  20550. EXPECT_EQ(304, res2->status);
  20551. // Wildcard match: expect 304 Not Modified
  20552. Headers h3 = {{"If-None-Match", "*"}};
  20553. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  20554. ASSERT_TRUE(res3);
  20555. EXPECT_EQ(304, res3->status);
  20556. // Non-matching ETag: expect 200
  20557. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  20558. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  20559. ASSERT_TRUE(res4);
  20560. EXPECT_EQ(200, res4->status);
  20561. // Multiple ETags with one matching: expect 304
  20562. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  20563. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  20564. ASSERT_TRUE(res5);
  20565. EXPECT_EQ(304, res5->status);
  20566. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  20567. // that equivalent to the single comma-separated list above, so the match on
  20568. // the second line must still be found.
  20569. Headers h6;
  20570. h6.emplace("If-None-Match", "W/\"other\"");
  20571. h6.emplace("If-None-Match", etag);
  20572. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  20573. ASSERT_TRUE(res6);
  20574. EXPECT_EQ(304, res6->status);
  20575. svr.stop();
  20576. t.join();
  20577. std::remove(fname);
  20578. }
  20579. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  20580. using namespace httplib;
  20581. Server svr;
  20582. svr.set_mount_point("/static", ".");
  20583. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20584. svr.wait_until_ready();
  20585. Client cli(HOST, PORT);
  20586. // Send If-None-Match: * to a non-existent file
  20587. Headers h = {{"If-None-Match", "*"}};
  20588. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  20589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20590. EXPECT_EQ(404, res->status);
  20591. svr.stop();
  20592. t.join();
  20593. }
  20594. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  20595. using namespace httplib;
  20596. // Create a test file
  20597. const char *fname = "etag_boundary_testfile.txt";
  20598. const char *content = "boundary-test";
  20599. {
  20600. std::ofstream ofs(fname);
  20601. ofs << content;
  20602. ASSERT_TRUE(ofs.good());
  20603. }
  20604. Server svr;
  20605. svr.set_mount_point("/static", ".");
  20606. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20607. svr.wait_until_ready();
  20608. Client cli(HOST, PORT);
  20609. // Get the actual ETag
  20610. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  20611. ASSERT_TRUE(res1);
  20612. ASSERT_EQ(200, res1->status);
  20613. ASSERT_TRUE(res1->has_header("ETag"));
  20614. std::string etag = res1->get_header_value("ETag");
  20615. // Test 1: Very long ETag value (longer than actual ETag)
  20616. // Should NOT match and return 200 (not trigger out-of-bounds read)
  20617. Headers h1 = {{"If-None-Match", "W/"
  20618. "\"very-long-etag-value-that-is-much-longer-"
  20619. "than-the-actual-etag-value\""}};
  20620. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  20621. ASSERT_TRUE(res2);
  20622. EXPECT_EQ(200, res2->status); // Should not match
  20623. // Test 2: Long string followed by wildcard
  20624. // Should match on "*" and return 304 (without out-of-bounds read on the long
  20625. // string)
  20626. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  20627. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  20628. ASSERT_TRUE(res3);
  20629. EXPECT_EQ(304, res3->status); // Should match on "*"
  20630. // Test 3: Wildcard followed by long string
  20631. // Should match on "*" immediately and return 304
  20632. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  20633. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  20634. ASSERT_TRUE(res4);
  20635. EXPECT_EQ(304, res4->status); // Should match on "*"
  20636. // Test 4: Multiple long non-matching values
  20637. // Should NOT match and return 200 (test that all comparisons are safe)
  20638. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  20639. "W/\"second-long-non-matching-value\", "
  20640. "W/\"third-long-non-matching-value\""}};
  20641. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  20642. ASSERT_TRUE(res5);
  20643. EXPECT_EQ(200, res5->status); // Should not match
  20644. // Test 5: Single character that is not "*" (edge case)
  20645. Headers h5 = {{"If-None-Match", "X"}};
  20646. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  20647. ASSERT_TRUE(res6);
  20648. EXPECT_EQ(200, res6->status); // Should not match
  20649. svr.stop();
  20650. t.join();
  20651. std::remove(fname);
  20652. }
  20653. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  20654. using namespace httplib;
  20655. // Create a test file
  20656. const char *fname = "ims_testfile.txt";
  20657. const char *content = "if-modified-since-test";
  20658. {
  20659. std::ofstream ofs(fname);
  20660. ofs << content;
  20661. ASSERT_TRUE(ofs.good());
  20662. }
  20663. Server svr;
  20664. svr.set_mount_point("/static", ".");
  20665. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20666. svr.wait_until_ready();
  20667. Client cli(HOST, PORT);
  20668. // First request: should get 200 with Last-Modified header
  20669. auto res1 = cli.Get("/static/ims_testfile.txt");
  20670. ASSERT_TRUE(res1);
  20671. ASSERT_EQ(200, res1->status);
  20672. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20673. std::string last_modified = res1->get_header_value("Last-Modified");
  20674. EXPECT_FALSE(last_modified.empty());
  20675. // If-Modified-Since with same time: expect 304
  20676. Headers h2 = {{"If-Modified-Since", last_modified}};
  20677. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  20678. ASSERT_TRUE(res2);
  20679. EXPECT_EQ(304, res2->status);
  20680. // If-Modified-Since with future time: expect 304
  20681. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20682. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  20683. ASSERT_TRUE(res3);
  20684. EXPECT_EQ(304, res3->status);
  20685. // If-Modified-Since with past time: expect 200
  20686. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20687. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  20688. ASSERT_TRUE(res4);
  20689. EXPECT_EQ(200, res4->status);
  20690. // If-None-Match takes precedence over If-Modified-Since
  20691. // (send matching ETag with old If-Modified-Since -> should still be 304)
  20692. ASSERT_TRUE(res1->has_header("ETag"));
  20693. std::string etag = res1->get_header_value("ETag");
  20694. Headers h5 = {{"If-None-Match", etag},
  20695. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20696. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  20697. ASSERT_TRUE(res5);
  20698. EXPECT_EQ(304, res5->status);
  20699. svr.stop();
  20700. t.join();
  20701. std::remove(fname);
  20702. }
  20703. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  20704. using namespace httplib;
  20705. Server svr;
  20706. // Endpoint that returns compressible content
  20707. svr.Get("/compressible", [](const Request &, Response &res) {
  20708. // Return a large enough body to trigger compression
  20709. std::string body(1000, 'a');
  20710. res.set_content(body, "text/plain");
  20711. });
  20712. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20713. svr.wait_until_ready();
  20714. Client cli(HOST, PORT);
  20715. // Request with gzip support: should get Vary header when compressed
  20716. cli.set_compress(true);
  20717. auto res1 = cli.Get("/compressible");
  20718. ASSERT_TRUE(res1);
  20719. EXPECT_EQ(200, res1->status);
  20720. // If Content-Encoding is set, Vary should also be set
  20721. if (res1->has_header("Content-Encoding")) {
  20722. EXPECT_TRUE(res1->has_header("Vary"));
  20723. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  20724. }
  20725. // Request without Accept-Encoding header: should not have compression
  20726. Headers h_no_compress;
  20727. auto res2 = cli.Get("/compressible", h_no_compress);
  20728. ASSERT_TRUE(res2);
  20729. EXPECT_EQ(200, res2->status);
  20730. // Verify Vary header is present when compression is applied
  20731. // (the exact behavior depends on server configuration)
  20732. svr.stop();
  20733. t.join();
  20734. }
  20735. TEST(ETagTest, IfRangeWithETag) {
  20736. using namespace httplib;
  20737. // Create a test file with known content
  20738. const char *fname = "if_range_testfile.txt";
  20739. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  20740. {
  20741. std::ofstream ofs(fname);
  20742. ofs << content;
  20743. ASSERT_TRUE(ofs.good());
  20744. }
  20745. Server svr;
  20746. svr.set_mount_point("/static", ".");
  20747. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20748. svr.wait_until_ready();
  20749. Client cli(HOST, PORT);
  20750. // First request: get ETag
  20751. auto res1 = cli.Get("/static/if_range_testfile.txt");
  20752. ASSERT_TRUE(res1);
  20753. ASSERT_EQ(200, res1->status);
  20754. ASSERT_TRUE(res1->has_header("ETag"));
  20755. std::string etag = res1->get_header_value("ETag");
  20756. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  20757. // Since our server generates weak ETags (W/"..."), If-Range with our
  20758. // ETag should NOT result in partial content - it should return full content.
  20759. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  20760. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  20761. ASSERT_TRUE(res2);
  20762. // Weak ETag in If-Range -> full content (200), not partial (206)
  20763. EXPECT_EQ(200, res2->status);
  20764. EXPECT_EQ(content, res2->body);
  20765. EXPECT_FALSE(res2->has_header("Content-Range"));
  20766. // Range request with non-matching If-Range (ETag): should get 200 (full
  20767. // content)
  20768. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  20769. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  20770. ASSERT_TRUE(res3);
  20771. EXPECT_EQ(200, res3->status);
  20772. EXPECT_EQ(content, res3->body);
  20773. EXPECT_FALSE(res3->has_header("Content-Range"));
  20774. // Range request with strong ETag (hypothetical - our server doesn't generate
  20775. // strong ETags, but if client sends a strong ETag that doesn't match, it
  20776. // should return full content)
  20777. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  20778. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  20779. ASSERT_TRUE(res4);
  20780. EXPECT_EQ(200, res4->status);
  20781. EXPECT_EQ(content, res4->body);
  20782. EXPECT_FALSE(res4->has_header("Content-Range"));
  20783. svr.stop();
  20784. t.join();
  20785. std::remove(fname);
  20786. }
  20787. TEST(ETagTest, IfRangeWithDate) {
  20788. using namespace httplib;
  20789. // Create a test file
  20790. const char *fname = "if_range_date_testfile.txt";
  20791. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  20792. {
  20793. std::ofstream ofs(fname);
  20794. ofs << content;
  20795. ASSERT_TRUE(ofs.good());
  20796. }
  20797. Server svr;
  20798. svr.set_mount_point("/static", ".");
  20799. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20800. svr.wait_until_ready();
  20801. Client cli(HOST, PORT);
  20802. // First request: get Last-Modified
  20803. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  20804. ASSERT_TRUE(res1);
  20805. ASSERT_EQ(200, res1->status);
  20806. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20807. std::string last_modified = res1->get_header_value("Last-Modified");
  20808. // Range request with matching If-Range (date): should get 206
  20809. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  20810. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  20811. ASSERT_TRUE(res2);
  20812. EXPECT_EQ(206, res2->status);
  20813. EXPECT_EQ("FGHIJ", res2->body);
  20814. // Range request with old If-Range date: should get 200 (full content)
  20815. Headers h3 = {{"Range", "bytes=5-9"},
  20816. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20817. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  20818. ASSERT_TRUE(res3);
  20819. EXPECT_EQ(200, res3->status);
  20820. EXPECT_EQ(content, res3->body);
  20821. // Range request with future If-Range date: should get 206
  20822. Headers h4 = {{"Range", "bytes=0-4"},
  20823. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20824. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  20825. ASSERT_TRUE(res4);
  20826. EXPECT_EQ(206, res4->status);
  20827. EXPECT_EQ("ABCDE", res4->body);
  20828. svr.stop();
  20829. t.join();
  20830. std::remove(fname);
  20831. }
  20832. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  20833. using namespace httplib;
  20834. const char *fname = "etag_malformed.txt";
  20835. const char *content = "malformed-etag";
  20836. {
  20837. std::ofstream ofs(fname);
  20838. ofs << content;
  20839. ASSERT_TRUE(ofs.good());
  20840. }
  20841. Server svr;
  20842. svr.set_mount_point("/static", ".");
  20843. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20844. svr.wait_until_ready();
  20845. Client cli(HOST, PORT);
  20846. // baseline: should get 200 and an ETag
  20847. auto res1 = cli.Get("/static/etag_malformed.txt");
  20848. ASSERT_TRUE(res1);
  20849. ASSERT_EQ(200, res1->status);
  20850. ASSERT_TRUE(res1->has_header("ETag"));
  20851. // Malformed ETag value (missing quotes) should be treated as non-matching
  20852. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  20853. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  20854. ASSERT_TRUE(res_bad);
  20855. EXPECT_EQ(200, res_bad->status);
  20856. // Whitespace-only header value should be considered invalid / non-matching
  20857. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  20858. "Host: localhost\r\n"
  20859. "If-None-Match: \r\n"
  20860. "Connection: close\r\n"
  20861. "\r\n";
  20862. std::string out;
  20863. ASSERT_TRUE(send_request(5, raw_req, &out));
  20864. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20865. svr.stop();
  20866. t.join();
  20867. std::remove(fname);
  20868. }
  20869. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  20870. using namespace httplib;
  20871. const char *fname = "ims_invalid_format.txt";
  20872. const char *content = "ims-bad-format";
  20873. {
  20874. std::ofstream ofs(fname);
  20875. ofs << content;
  20876. ASSERT_TRUE(ofs.good());
  20877. }
  20878. Server svr;
  20879. svr.set_mount_point("/static", ".");
  20880. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20881. svr.wait_until_ready();
  20882. Client cli(HOST, PORT);
  20883. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  20884. ASSERT_TRUE(res1);
  20885. ASSERT_EQ(200, res1->status);
  20886. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20887. // If-Modified-Since with invalid format should not result in 304
  20888. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  20889. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  20890. ASSERT_TRUE(res_bad);
  20891. EXPECT_EQ(200, res_bad->status);
  20892. // If-Range with invalid date format should be treated as mismatch -> full
  20893. // content (200)
  20894. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  20895. {"If-Range", "invalid-date"}};
  20896. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  20897. ASSERT_TRUE(res_ifrange);
  20898. EXPECT_EQ(200, res_ifrange->status);
  20899. svr.stop();
  20900. t.join();
  20901. std::remove(fname);
  20902. }
  20903. TEST(ETagTest, IfRangeWithMalformedETag) {
  20904. using namespace httplib;
  20905. const char *fname = "ifrange_malformed.txt";
  20906. const std::string content = "0123456789";
  20907. {
  20908. std::ofstream ofs(fname);
  20909. ofs << content;
  20910. ASSERT_TRUE(ofs.good());
  20911. }
  20912. Server svr;
  20913. svr.set_mount_point("/static", ".");
  20914. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20915. svr.wait_until_ready();
  20916. Client cli(HOST, PORT);
  20917. // First request: get ETag
  20918. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  20919. ASSERT_TRUE(res1);
  20920. ASSERT_EQ(200, res1->status);
  20921. ASSERT_TRUE(res1->has_header("ETag"));
  20922. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  20923. // full content (200)
  20924. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  20925. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  20926. ASSERT_TRUE(res2);
  20927. EXPECT_EQ(200, res2->status);
  20928. EXPECT_EQ(content, res2->body);
  20929. svr.stop();
  20930. t.join();
  20931. std::remove(fname);
  20932. }
  20933. TEST(ETagTest, ExtremeLargeDateValues) {
  20934. using namespace httplib;
  20935. const char *fname = "ims_extreme_date.txt";
  20936. const char *content = "ims-extreme-date";
  20937. {
  20938. std::ofstream ofs(fname);
  20939. ofs << content;
  20940. ASSERT_TRUE(ofs.good());
  20941. }
  20942. Server svr;
  20943. svr.set_mount_point("/static", ".");
  20944. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20945. svr.wait_until_ready();
  20946. Client cli(HOST, PORT);
  20947. auto res1 = cli.Get(std::string("/static/") + fname);
  20948. ASSERT_TRUE(res1);
  20949. ASSERT_EQ(200, res1->status);
  20950. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20951. // Extremely large year that may overflow date parsing routines.
  20952. Headers h_large_date = {
  20953. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20954. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  20955. ASSERT_TRUE(res_bad);
  20956. // Expect server to treat this as invalid/mismatch and return full content
  20957. EXPECT_EQ(200, res_bad->status);
  20958. // If-Range with extremely large date should be treated as mismatch -> full
  20959. // content (200)
  20960. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  20961. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20962. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  20963. ASSERT_TRUE(res_ifrange);
  20964. EXPECT_EQ(200, res_ifrange->status);
  20965. svr.stop();
  20966. t.join();
  20967. std::remove(fname);
  20968. }
  20969. TEST(ETagTest, NegativeFileModificationTime) {
  20970. using namespace httplib;
  20971. const char *fname = "ims_negative_mtime.txt";
  20972. const std::string content = "negative-mtime";
  20973. {
  20974. std::ofstream ofs(fname);
  20975. ofs << content;
  20976. ASSERT_TRUE(ofs.good());
  20977. }
  20978. // Try to set file mtime to a negative value. This may fail on some
  20979. // platforms/filesystems; if it fails, the test will still verify server
  20980. // behaves safely by performing a regular conditional request.
  20981. #if defined(__APPLE__) || defined(__linux__)
  20982. bool set_negative = false;
  20983. do {
  20984. struct timeval times[2];
  20985. // access time: now
  20986. times[0].tv_sec = time(nullptr);
  20987. times[0].tv_usec = 0;
  20988. // modification time: negative (e.g., -1)
  20989. times[1].tv_sec = -1;
  20990. times[1].tv_usec = 0;
  20991. if (utimes(fname, times) == 0) { set_negative = true; }
  20992. } while (0);
  20993. #else
  20994. bool set_negative = false;
  20995. #endif
  20996. Server svr;
  20997. svr.set_mount_point("/static", ".");
  20998. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20999. svr.wait_until_ready();
  21000. Client cli(HOST, PORT);
  21001. auto res1 = cli.Get(std::string("/static/") + fname);
  21002. ASSERT_TRUE(res1);
  21003. ASSERT_EQ(200, res1->status);
  21004. bool has_last_modified = res1->has_header("Last-Modified");
  21005. std::string last_modified;
  21006. if (has_last_modified) {
  21007. last_modified = res1->get_header_value("Last-Modified");
  21008. }
  21009. if (set_negative) {
  21010. // If we successfully set a negative mtime, ensure server returns a
  21011. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  21012. // with an old date and ensure server handles it without crash.
  21013. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21014. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21015. ASSERT_TRUE(res2);
  21016. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21017. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21018. } else {
  21019. // Could not set negative mtime on this platform; fall back to verifying
  21020. // that normal invalid/malformed dates are treated safely (non-304).
  21021. Headers h_bad_date = {
  21022. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21023. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21024. ASSERT_TRUE(res_bad);
  21025. EXPECT_EQ(200, res_bad->status);
  21026. }
  21027. svr.stop();
  21028. t.join();
  21029. std::remove(fname);
  21030. }
  21031. //==============================================================================
  21032. // Integration Tests with Server
  21033. //==============================================================================
  21034. class SSEIntegrationTest : public ::testing::Test {
  21035. protected:
  21036. void SetUp() override {
  21037. stop_server_.store(false);
  21038. events_.clear();
  21039. server_ = httplib::detail::make_unique<Server>();
  21040. setup_server();
  21041. start_server();
  21042. }
  21043. void TearDown() override {
  21044. stop_server_.store(true);
  21045. event_cv_.notify_all();
  21046. server_->stop();
  21047. if (server_thread_.joinable()) { server_thread_.join(); }
  21048. }
  21049. void setup_server() {
  21050. // Simple SSE endpoint
  21051. server_->Get("/events", [this](const Request &req, Response &res) {
  21052. auto last_id = req.get_header_value("Last-Event-ID");
  21053. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21054. res.set_chunked_content_provider(
  21055. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21056. std::unique_lock<std::mutex> lock(event_mutex_);
  21057. if (event_cv_.wait_for(
  21058. lock, std::chrono::milliseconds(200), [this] {
  21059. return !events_.empty() || stop_server_.load();
  21060. })) {
  21061. if (stop_server_.load()) { return false; }
  21062. if (!events_.empty()) {
  21063. std::string event = events_.front();
  21064. events_.erase(events_.begin());
  21065. sink.write(event.data(), event.size());
  21066. return true;
  21067. }
  21068. }
  21069. return !stop_server_.load();
  21070. });
  21071. });
  21072. // Endpoint that returns error
  21073. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  21074. res.status = 500;
  21075. res.set_content("Internal Server Error", "text/plain");
  21076. });
  21077. // Endpoint for custom event types
  21078. server_->Get("/custom-events", [](const Request &, Response &res) {
  21079. res.set_chunked_content_provider(
  21080. "text/event-stream", [](size_t offset, DataSink &sink) {
  21081. if (offset == 0) {
  21082. std::string event = "event: update\ndata: updated\n\n"
  21083. "event: delete\ndata: deleted\n\n";
  21084. sink.write(event.data(), event.size());
  21085. }
  21086. return false; // End stream after sending
  21087. });
  21088. });
  21089. }
  21090. void start_server() {
  21091. port_ = server_->bind_to_any_port(HOST);
  21092. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21093. // Wait for server to start
  21094. while (!server_->is_running()) {
  21095. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21096. }
  21097. }
  21098. int get_port() const { return port_; }
  21099. void send_event(const std::string &event) {
  21100. std::lock_guard<std::mutex> lock(event_mutex_);
  21101. events_.push_back(event);
  21102. event_cv_.notify_all();
  21103. }
  21104. std::unique_ptr<Server> server_;
  21105. std::thread server_thread_;
  21106. std::mutex event_mutex_;
  21107. std::condition_variable event_cv_;
  21108. std::vector<std::string> events_;
  21109. std::atomic<bool> stop_server_{false};
  21110. std::string last_received_event_id_;
  21111. int port_ = 0;
  21112. };
  21113. //==============================================================================
  21114. // SSE Parsing Tests
  21115. //==============================================================================
  21116. class SSEParsingTest : public SSEIntegrationTest {
  21117. protected:
  21118. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  21119. // A trailing sentinel event tells when the whole stream has been parsed.
  21120. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  21121. auto body = stream + "event: end\ndata: end\n\n";
  21122. server_->Get("/parse", [body](const Request &, Response &res) {
  21123. res.set_content(body, "text/event-stream");
  21124. });
  21125. return collect("/parse");
  21126. }
  21127. // Runs SSEClient against path until an "end" event arrives and returns the
  21128. // messages dispatched before it
  21129. std::vector<sse::SSEMessage> collect(const std::string &path) {
  21130. Client client(HOST, get_port());
  21131. sse::SSEClient sse(client, path);
  21132. std::mutex mutex;
  21133. std::condition_variable cv;
  21134. std::vector<sse::SSEMessage> messages;
  21135. auto done = false;
  21136. sse.on_message([&](const sse::SSEMessage &msg) {
  21137. std::lock_guard<std::mutex> lock(mutex);
  21138. // Ignore a replay from a reconnect that races with stop()
  21139. if (!done) { messages.push_back(msg); }
  21140. });
  21141. sse.on_event("end", [&](const sse::SSEMessage &) {
  21142. std::lock_guard<std::mutex> lock(mutex);
  21143. done = true;
  21144. cv.notify_all();
  21145. });
  21146. sse.set_reconnect_interval(100);
  21147. sse.start_async();
  21148. {
  21149. std::unique_lock<std::mutex> lock(mutex);
  21150. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21151. }
  21152. sse.stop();
  21153. EXPECT_TRUE(done);
  21154. return messages;
  21155. }
  21156. };
  21157. TEST_F(SSEParsingTest, SingleLineData) {
  21158. auto msgs = parse("data: hello\n\n");
  21159. ASSERT_EQ(msgs.size(), 1u);
  21160. EXPECT_EQ(msgs[0].data, "hello");
  21161. EXPECT_EQ(msgs[0].event, "message");
  21162. }
  21163. TEST_F(SSEParsingTest, MultiLineData) {
  21164. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21165. ASSERT_EQ(msgs.size(), 1u);
  21166. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21167. }
  21168. TEST_F(SSEParsingTest, CustomEventType) {
  21169. auto msgs = parse("event: update\ndata: payload\n\n");
  21170. ASSERT_EQ(msgs.size(), 1u);
  21171. EXPECT_EQ(msgs[0].event, "update");
  21172. EXPECT_EQ(msgs[0].data, "payload");
  21173. }
  21174. TEST_F(SSEParsingTest, EventIdHandling) {
  21175. auto msgs = parse("id: 12345\ndata: test\n\n");
  21176. ASSERT_EQ(msgs.size(), 1u);
  21177. EXPECT_EQ(msgs[0].id, "12345");
  21178. }
  21179. TEST_F(SSEParsingTest, EmptyEventId) {
  21180. auto msgs = parse("id:\ndata: test\n\n");
  21181. ASSERT_EQ(msgs.size(), 1u);
  21182. EXPECT_EQ(msgs[0].id, "");
  21183. }
  21184. TEST_F(SSEParsingTest, CommentsIgnored) {
  21185. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  21186. ASSERT_EQ(msgs.size(), 1u);
  21187. EXPECT_EQ(msgs[0].data, "hello");
  21188. EXPECT_EQ(msgs[0].event, "message");
  21189. }
  21190. TEST_F(SSEParsingTest, ColonInValue) {
  21191. auto msgs = parse("data: hello:world:test\n\n");
  21192. ASSERT_EQ(msgs.size(), 1u);
  21193. EXPECT_EQ(msgs[0].data, "hello:world:test");
  21194. }
  21195. TEST_F(SSEParsingTest, FieldNameOnly) {
  21196. // A line without a colon is a field name with an empty value
  21197. auto msgs = parse("data\n\n");
  21198. ASSERT_EQ(msgs.size(), 1u);
  21199. EXPECT_EQ(msgs[0].data, "");
  21200. }
  21201. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  21202. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  21203. ASSERT_EQ(msgs.size(), 1u);
  21204. EXPECT_EQ(msgs[0].event, "update");
  21205. EXPECT_EQ(msgs[0].data, "hello");
  21206. }
  21207. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21208. auto msgs = parse("data\r\n\r\n");
  21209. ASSERT_EQ(msgs.size(), 1u);
  21210. EXPECT_EQ(msgs[0].data, "");
  21211. }
  21212. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21213. auto msgs = parse("event: update\rdata: hello\r\r");
  21214. ASSERT_EQ(msgs.size(), 1u);
  21215. EXPECT_EQ(msgs[0].event, "update");
  21216. EXPECT_EQ(msgs[0].data, "hello");
  21217. }
  21218. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21219. // Chunk boundaries fall inside every \r\n and right before the first one
  21220. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21221. "\n\r", "\nevent: end\ndata: end\n\n"};
  21222. server_->Get("/split", [chunks](const Request &, Response &res) {
  21223. auto i = std::make_shared<size_t>(0);
  21224. res.set_chunked_content_provider(
  21225. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21226. if (*i == chunks.size()) {
  21227. sink.done();
  21228. } else {
  21229. sink.write(chunks[*i].data(), chunks[*i].size());
  21230. (*i)++;
  21231. }
  21232. return true;
  21233. });
  21234. });
  21235. auto msgs = collect("/split");
  21236. ASSERT_EQ(msgs.size(), 1u);
  21237. EXPECT_EQ(msgs[0].event, "update");
  21238. EXPECT_EQ(msgs[0].data, "hello");
  21239. }
  21240. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  21241. // Only a BOM at the start of the stream is ignored
  21242. auto msgs = parse("\xEF\xBB\xBF"
  21243. "data: first\n\n"
  21244. "\xEF\xBB\xBF"
  21245. "data: second\n\n");
  21246. ASSERT_EQ(msgs.size(), 1u);
  21247. EXPECT_EQ(msgs[0].data, "first");
  21248. }
  21249. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  21250. auto msgs = parse("unknown: value\ndata: hello\n\n");
  21251. ASSERT_EQ(msgs.size(), 1u);
  21252. EXPECT_EQ(msgs[0].data, "hello");
  21253. EXPECT_EQ(msgs[0].event, "message");
  21254. }
  21255. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  21256. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  21257. ASSERT_EQ(msgs.size(), 2u);
  21258. EXPECT_EQ(msgs[0].data, "hello");
  21259. EXPECT_EQ(msgs[1].data, "hello");
  21260. }
  21261. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  21262. // An event without data is not dispatched, and its type must not leak
  21263. // into the next event
  21264. auto msgs = parse("event: update\n\ndata: hello\n\n");
  21265. ASSERT_EQ(msgs.size(), 1u);
  21266. EXPECT_EQ(msgs[0].event, "message");
  21267. EXPECT_EQ(msgs[0].data, "hello");
  21268. }
  21269. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  21270. // The first connection sends only an id; the second echoes back the
  21271. // Last-Event-ID it was reconnected with
  21272. std::atomic<int> connection_count{0};
  21273. server_->Get("/id-only", [&](const Request &req, Response &res) {
  21274. if (connection_count++ == 0) {
  21275. res.set_content("id: 42\n\n", "text/event-stream");
  21276. } else {
  21277. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21278. "\n\nevent: end\ndata: end\n\n",
  21279. "text/event-stream");
  21280. }
  21281. });
  21282. auto msgs = collect("/id-only");
  21283. ASSERT_EQ(msgs.size(), 1u);
  21284. EXPECT_EQ(msgs[0].data, "42");
  21285. }
  21286. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  21287. // The first connection sets an id and then clears it with an empty one; the
  21288. // second reports whether it was reconnected with a Last-Event-ID
  21289. std::atomic<int> connection_count{0};
  21290. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  21291. if (connection_count++ == 0) {
  21292. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  21293. "text/event-stream");
  21294. } else {
  21295. res.set_content(
  21296. std::string("data: ") +
  21297. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  21298. "\n\nevent: end\ndata: end\n\n",
  21299. "text/event-stream");
  21300. }
  21301. });
  21302. auto msgs = collect("/id-clear");
  21303. ASSERT_EQ(msgs.size(), 3u);
  21304. EXPECT_EQ(msgs[0].id, "1");
  21305. EXPECT_EQ(msgs[1].id, "");
  21306. EXPECT_EQ(msgs[2].data, "not sent");
  21307. }
  21308. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  21309. // The first connection sets an id and then sends ids that cannot be carried
  21310. // in a header; the second echoes back the Last-Event-ID it was reconnected
  21311. // with
  21312. std::atomic<int> connection_count{0};
  21313. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  21314. if (connection_count++ == 0) {
  21315. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  21316. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  21317. "text/event-stream");
  21318. } else {
  21319. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21320. "\n\nevent: end\ndata: end\n\n",
  21321. "text/event-stream");
  21322. }
  21323. });
  21324. auto msgs = collect("/id-unsendable");
  21325. ASSERT_EQ(msgs.size(), 1u);
  21326. EXPECT_EQ(msgs[0].data, "42");
  21327. }
  21328. TEST_F(SSEParsingTest, CompleteEventParsing) {
  21329. auto msgs = parse("event: notification\nid: evt-42\n"
  21330. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  21331. ASSERT_EQ(msgs.size(), 1u);
  21332. EXPECT_EQ(msgs[0].event, "notification");
  21333. EXPECT_EQ(msgs[0].id, "evt-42");
  21334. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  21335. }
  21336. TEST(SSEMessageTest, Clear) {
  21337. sse::SSEMessage msg;
  21338. msg.event = "custom";
  21339. msg.data = "some data";
  21340. msg.id = "123";
  21341. msg.clear();
  21342. EXPECT_EQ(msg.event, "message");
  21343. EXPECT_EQ(msg.data, "");
  21344. EXPECT_EQ(msg.id, "");
  21345. }
  21346. //==============================================================================
  21347. // SSE Integration Tests
  21348. //==============================================================================
  21349. // Test: Successful connection and on_open callback
  21350. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21351. // Add a simple endpoint that sends one event and closes
  21352. server_->Get("/simple-event", [](const Request &, Response &res) {
  21353. res.set_chunked_content_provider(
  21354. "text/event-stream", [](size_t offset, DataSink &sink) {
  21355. if (offset == 0) {
  21356. std::string event = "data: hello\n\n";
  21357. sink.write(event.data(), event.size());
  21358. }
  21359. return false; // Close stream after sending
  21360. });
  21361. });
  21362. Client client("localhost", get_port());
  21363. sse::SSEClient sse(client, "/simple-event");
  21364. std::atomic<bool> open_called{false};
  21365. std::atomic<bool> message_received{false};
  21366. sse.on_open([&open_called]() { open_called.store(true); });
  21367. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  21368. if (msg.data == "hello") { message_received.store(true); }
  21369. });
  21370. sse.set_reconnect_interval(100);
  21371. sse.set_max_reconnect_attempts(1);
  21372. // Start async
  21373. sse.start_async();
  21374. // Wait for message to be processed
  21375. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21376. sse.stop();
  21377. EXPECT_TRUE(open_called.load());
  21378. EXPECT_TRUE(message_received.load());
  21379. }
  21380. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  21381. // A data line that never ends.
  21382. server_->Get("/endless-line", [](const Request &, Response &res) {
  21383. res.set_chunked_content_provider(
  21384. "text/event-stream", [](size_t offset, DataSink &sink) {
  21385. if (offset == 0) { sink.write("data: ", 6); }
  21386. std::string chunk(64 * 1024, 'A');
  21387. return sink.write(chunk.data(), chunk.size());
  21388. });
  21389. });
  21390. Client client("localhost", get_port());
  21391. sse::SSEClient sse(client, "/endless-line");
  21392. std::atomic<bool> too_long{false};
  21393. sse.on_error([&](Error err) {
  21394. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  21395. });
  21396. sse.set_max_reconnect_attempts(1);
  21397. sse.start_async();
  21398. for (int i = 0; i < 500 && !too_long; i++) {
  21399. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21400. }
  21401. sse.stop();
  21402. EXPECT_TRUE(too_long);
  21403. }
  21404. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  21405. // Far more in all than the client's payload limit below.
  21406. server_->Get("/many-events", [](const Request &, Response &res) {
  21407. res.set_chunked_content_provider(
  21408. "text/event-stream", [](size_t offset, DataSink &sink) {
  21409. if (offset == 0) {
  21410. std::string events;
  21411. for (int i = 0; i < 1000; i++) {
  21412. events += "data: message\n\n";
  21413. }
  21414. sink.write(events.data(), events.size());
  21415. }
  21416. return false;
  21417. });
  21418. });
  21419. Client client("localhost", get_port());
  21420. client.set_payload_max_length(1024);
  21421. sse::SSEClient sse(client, "/many-events");
  21422. std::atomic<int> messages{0};
  21423. std::atomic<bool> too_large{false};
  21424. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  21425. sse.on_error([&](Error err) {
  21426. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  21427. });
  21428. sse.set_max_reconnect_attempts(1);
  21429. sse.start_async();
  21430. for (int i = 0; i < 500 && messages < 1000; i++) {
  21431. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21432. }
  21433. sse.stop();
  21434. EXPECT_GE(messages.load(), 1000);
  21435. EXPECT_FALSE(too_large);
  21436. }
  21437. // Test: on_message callback
  21438. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  21439. // Endpoint that sends multiple events then closes
  21440. server_->Get("/multi-event", [](const Request &, Response &res) {
  21441. res.set_chunked_content_provider(
  21442. "text/event-stream", [](size_t offset, DataSink &sink) {
  21443. if (offset == 0) {
  21444. std::string events = "data: message1\n\ndata: message2\n\n";
  21445. sink.write(events.data(), events.size());
  21446. }
  21447. return false;
  21448. });
  21449. });
  21450. Client client("localhost", get_port());
  21451. sse::SSEClient sse(client, "/multi-event");
  21452. std::vector<std::string> received_messages;
  21453. std::mutex messages_mutex;
  21454. sse.on_message([&](const sse::SSEMessage &msg) {
  21455. std::lock_guard<std::mutex> lock(messages_mutex);
  21456. received_messages.push_back(msg.data);
  21457. });
  21458. sse.set_reconnect_interval(100);
  21459. sse.set_max_reconnect_attempts(1);
  21460. sse.start_async();
  21461. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21462. sse.stop();
  21463. std::lock_guard<std::mutex> lock(messages_mutex);
  21464. EXPECT_GE(received_messages.size(), 2u);
  21465. if (received_messages.size() >= 2) {
  21466. EXPECT_EQ(received_messages[0], "message1");
  21467. EXPECT_EQ(received_messages[1], "message2");
  21468. }
  21469. }
  21470. // Test: on_event for specific types
  21471. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  21472. Client client("localhost", get_port());
  21473. sse::SSEClient sse(client, "/custom-events");
  21474. std::atomic<bool> update_received{false};
  21475. std::atomic<bool> delete_received{false};
  21476. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  21477. if (msg.data == "updated") { update_received.store(true); }
  21478. });
  21479. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  21480. if (msg.data == "deleted") { delete_received.store(true); }
  21481. });
  21482. sse.set_max_reconnect_attempts(1);
  21483. sse.start_async();
  21484. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  21485. sse.stop();
  21486. EXPECT_TRUE(update_received.load());
  21487. EXPECT_TRUE(delete_received.load());
  21488. }
  21489. // Test: on_error callback on connection failure
  21490. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  21491. // Connect to a non-existent port
  21492. Client client("localhost", 59999);
  21493. sse::SSEClient sse(client, "/events");
  21494. std::atomic<bool> error_called{false};
  21495. Error received_error = Error::Success;
  21496. sse.on_error([&](Error err) {
  21497. error_called.store(true);
  21498. received_error = err;
  21499. });
  21500. sse.set_reconnect_interval(50);
  21501. sse.set_max_reconnect_attempts(1);
  21502. sse.start_async();
  21503. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21504. sse.stop();
  21505. EXPECT_TRUE(error_called.load());
  21506. EXPECT_NE(received_error, Error::Success);
  21507. }
  21508. // Test: Last-Event-ID header sent on reconnect
  21509. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  21510. // Endpoint that sends event with ID
  21511. server_->Get("/event-with-id", [](const Request &, Response &res) {
  21512. res.set_chunked_content_provider(
  21513. "text/event-stream", [](size_t offset, DataSink &sink) {
  21514. if (offset == 0) {
  21515. std::string event = "id: evt-123\ndata: test\n\n";
  21516. sink.write(event.data(), event.size());
  21517. }
  21518. return false;
  21519. });
  21520. });
  21521. Client client("localhost", get_port());
  21522. sse::SSEClient sse(client, "/event-with-id");
  21523. std::atomic<bool> id_received{false};
  21524. sse.on_message([&](const sse::SSEMessage &msg) {
  21525. if (!msg.id.empty()) { id_received.store(true); }
  21526. });
  21527. sse.set_reconnect_interval(100);
  21528. sse.set_max_reconnect_attempts(1);
  21529. sse.start_async();
  21530. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21531. sse.stop();
  21532. EXPECT_TRUE(id_received.load());
  21533. EXPECT_EQ(sse.last_event_id(), "evt-123");
  21534. }
  21535. // Test: Manual stop
  21536. TEST_F(SSEIntegrationTest, ManualStop) {
  21537. // Endpoint that sends one event and stays open briefly
  21538. std::atomic<bool> handler_running{true};
  21539. server_->Get("/stay-open", [&handler_running](const Request &,
  21540. Response &res) {
  21541. res.set_chunked_content_provider(
  21542. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  21543. if (offset == 0) {
  21544. std::string event = "data: connected\n\n";
  21545. sink.write(event.data(), event.size());
  21546. }
  21547. // Keep connection open while handler_running is true
  21548. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  21549. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21550. }
  21551. return false;
  21552. });
  21553. });
  21554. Client client("localhost", get_port());
  21555. sse::SSEClient sse(client, "/stay-open");
  21556. std::atomic<bool> connected{false};
  21557. sse.on_open([&connected]() { connected.store(true); });
  21558. sse.set_reconnect_interval(100);
  21559. sse.set_max_reconnect_attempts(1);
  21560. sse.start_async();
  21561. // Wait for connection to establish
  21562. for (int i = 0; i < 20 && !connected.load(); ++i) {
  21563. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21564. }
  21565. EXPECT_TRUE(connected.load());
  21566. EXPECT_TRUE(sse.is_connected());
  21567. // Signal handler to stop
  21568. handler_running.store(false);
  21569. // Stop SSE client
  21570. sse.stop();
  21571. EXPECT_FALSE(sse.is_connected());
  21572. }
  21573. // Test: SSEClient with custom headers
  21574. TEST_F(SSEIntegrationTest, CustomHeaders) {
  21575. // Setup a server endpoint that checks for custom header
  21576. std::atomic<bool> header_received{false};
  21577. server_->Get("/header-check", [&](const Request &req, Response &res) {
  21578. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  21579. header_received.store(true);
  21580. }
  21581. res.set_chunked_content_provider("text/event-stream",
  21582. [](size_t, DataSink &) { return false; });
  21583. });
  21584. Client client("localhost", get_port());
  21585. Headers headers = {{"X-Custom-Header", "custom-value"}};
  21586. sse::SSEClient sse(client, "/header-check", headers);
  21587. sse.set_max_reconnect_attempts(1);
  21588. sse.start_async();
  21589. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21590. sse.stop();
  21591. EXPECT_TRUE(header_received.load());
  21592. }
  21593. // Test: Reconnect interval configuration
  21594. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  21595. Client client("localhost", get_port());
  21596. sse::SSEClient sse(client, "/events");
  21597. auto &result = sse.set_reconnect_interval(500);
  21598. // Builder pattern should return reference to self
  21599. EXPECT_EQ(&result, &sse);
  21600. }
  21601. // Test: Max reconnect attempts
  21602. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  21603. // Connect to non-existent port to force reconnects
  21604. Client client("localhost", 59998);
  21605. sse::SSEClient sse(client, "/events");
  21606. std::atomic<int> error_count{0};
  21607. sse.on_error([&](Error) { error_count.fetch_add(1); });
  21608. sse.set_reconnect_interval(50);
  21609. sse.set_max_reconnect_attempts(2);
  21610. auto start = std::chrono::steady_clock::now();
  21611. sse.start(); // Blocking call
  21612. auto end = std::chrono::steady_clock::now();
  21613. // Should have stopped after 2 failed attempts
  21614. EXPECT_GE(error_count.load(), 2);
  21615. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  21616. auto duration =
  21617. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  21618. #ifdef _WIN32
  21619. // Windows is much slower for socket connection failures
  21620. EXPECT_LT(duration.count(), 7000);
  21621. #else
  21622. EXPECT_LT(duration.count(), 1000);
  21623. #endif
  21624. }
  21625. // Test: Multi-line data in integration
  21626. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  21627. // Endpoint with multi-line data
  21628. server_->Get("/multiline-data", [](const Request &, Response &res) {
  21629. res.set_chunked_content_provider(
  21630. "text/event-stream", [](size_t offset, DataSink &sink) {
  21631. if (offset == 0) {
  21632. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  21633. sink.write(event.data(), event.size());
  21634. }
  21635. return false;
  21636. });
  21637. });
  21638. Client client("localhost", get_port());
  21639. sse::SSEClient sse(client, "/multiline-data");
  21640. std::string received_data;
  21641. std::mutex data_mutex;
  21642. sse.on_message([&](const sse::SSEMessage &msg) {
  21643. std::lock_guard<std::mutex> lock(data_mutex);
  21644. received_data = msg.data;
  21645. });
  21646. sse.set_reconnect_interval(100);
  21647. sse.set_max_reconnect_attempts(1);
  21648. sse.start_async();
  21649. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21650. sse.stop();
  21651. std::lock_guard<std::mutex> lock(data_mutex);
  21652. EXPECT_EQ(received_data, "line1\nline2\nline3");
  21653. }
  21654. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  21655. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  21656. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  21657. DataSink &sink) {
  21658. if (offset == 0) {
  21659. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  21660. sink.write(events.data(), events.size());
  21661. }
  21662. return false;
  21663. });
  21664. });
  21665. Client client("localhost", get_port());
  21666. sse::SSEClient sse(client, "/empty-data-lines");
  21667. std::mutex mutex;
  21668. std::condition_variable cv;
  21669. std::vector<std::string> received;
  21670. sse.on_message([&](const sse::SSEMessage &msg) {
  21671. std::lock_guard<std::mutex> lock(mutex);
  21672. received.push_back(msg.data);
  21673. cv.notify_all();
  21674. });
  21675. sse.set_max_reconnect_attempts(1);
  21676. sse.start_async();
  21677. {
  21678. std::unique_lock<std::mutex> lock(mutex);
  21679. cv.wait_for(lock, std::chrono::seconds(2),
  21680. [&] { return received.size() >= 3; });
  21681. }
  21682. sse.stop();
  21683. ASSERT_GE(received.size(), 3u);
  21684. EXPECT_EQ(received[0], "");
  21685. EXPECT_EQ(received[1], "\nhello");
  21686. EXPECT_EQ(received[2], "");
  21687. }
  21688. // Test: Auto-reconnect after server disconnection
  21689. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  21690. std::atomic<int> connection_count{0};
  21691. std::atomic<int> message_count{0};
  21692. // Endpoint that sends one event and closes, forcing reconnect
  21693. server_->Get("/reconnect-test",
  21694. [&connection_count](const Request &, Response &res) {
  21695. connection_count.fetch_add(1);
  21696. res.set_chunked_content_provider(
  21697. "text/event-stream", [](size_t offset, DataSink &sink) {
  21698. if (offset == 0) {
  21699. std::string event = "data: hello\n\n";
  21700. sink.write(event.data(), event.size());
  21701. }
  21702. return false; // Close connection after sending
  21703. });
  21704. });
  21705. Client client("localhost", get_port());
  21706. sse::SSEClient sse(client, "/reconnect-test");
  21707. sse.on_message([&message_count](const sse::SSEMessage &) {
  21708. message_count.fetch_add(1);
  21709. });
  21710. sse.set_reconnect_interval(100);
  21711. sse.set_max_reconnect_attempts(3);
  21712. sse.start_async();
  21713. // Wait long enough for multiple reconnects
  21714. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21715. sse.stop();
  21716. // Should have connected multiple times (initial + reconnects)
  21717. EXPECT_GE(connection_count.load(), 2);
  21718. // Should have received messages from multiple connections
  21719. EXPECT_GE(message_count.load(), 2);
  21720. }
  21721. // Test: A retry field that is not all ASCII digits is ignored
  21722. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  21723. std::atomic<int> connection_count{0};
  21724. server_->Get("/bad-retry",
  21725. [&connection_count](const Request &, Response &res) {
  21726. connection_count.fetch_add(1);
  21727. res.set_chunked_content_provider(
  21728. "text/event-stream", [](size_t offset, DataSink &sink) {
  21729. if (offset == 0) {
  21730. std::string event = "retry: -1\ndata: hello\n\n";
  21731. sink.write(event.data(), event.size());
  21732. }
  21733. return false;
  21734. });
  21735. });
  21736. Client client("localhost", get_port());
  21737. sse::SSEClient sse(client, "/bad-retry");
  21738. sse.set_reconnect_interval(10000);
  21739. sse.start_async();
  21740. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21741. sse.stop();
  21742. EXPECT_EQ(connection_count.load(), 1);
  21743. }
  21744. // Test: A retry field of all ASCII digits sets the reconnection time
  21745. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  21746. std::mutex mutex;
  21747. std::condition_variable cv;
  21748. std::vector<std::chrono::steady_clock::time_point> connected_at;
  21749. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  21750. {
  21751. std::lock_guard<std::mutex> lock(mutex);
  21752. connected_at.push_back(std::chrono::steady_clock::now());
  21753. cv.notify_all();
  21754. }
  21755. res.set_chunked_content_provider(
  21756. "text/event-stream", [](size_t offset, DataSink &sink) {
  21757. if (offset == 0) {
  21758. std::string event = "retry: 0\ndata: hello\n\n";
  21759. sink.write(event.data(), event.size());
  21760. }
  21761. return false;
  21762. });
  21763. });
  21764. Client client("localhost", get_port());
  21765. sse::SSEClient sse(client, "/zero-retry");
  21766. sse.set_reconnect_interval(10000);
  21767. sse.start_async();
  21768. {
  21769. std::unique_lock<std::mutex> lock(mutex);
  21770. cv.wait_for(lock, std::chrono::seconds(5),
  21771. [&] { return connected_at.size() >= 2; });
  21772. }
  21773. sse.stop();
  21774. // The server-supplied interval is applied, but never below 100ms, so
  21775. // "retry: 0" does not cause a busy reconnect loop
  21776. std::lock_guard<std::mutex> lock(mutex);
  21777. ASSERT_GE(connected_at.size(), 2u);
  21778. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  21779. connected_at[1] - connected_at[0])
  21780. .count();
  21781. EXPECT_GE(interval_ms, 100);
  21782. }
  21783. // Test: Last-Event-ID sent on reconnect
  21784. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  21785. std::atomic<int> connection_count{0};
  21786. std::vector<std::string> received_last_event_ids;
  21787. std::mutex id_mutex;
  21788. // Endpoint that checks Last-Event-ID header and sends event with ID
  21789. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  21790. int conn = connection_count.fetch_add(1);
  21791. // Capture the Last-Event-ID header from each connection
  21792. {
  21793. std::lock_guard<std::mutex> lock(id_mutex);
  21794. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  21795. }
  21796. res.set_chunked_content_provider(
  21797. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  21798. if (offset == 0) {
  21799. std::string event =
  21800. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  21801. sink.write(event.data(), event.size());
  21802. }
  21803. return false;
  21804. });
  21805. });
  21806. Client client("localhost", get_port());
  21807. sse::SSEClient sse(client, "/reconnect-with-id");
  21808. sse.set_reconnect_interval(100);
  21809. sse.set_max_reconnect_attempts(3);
  21810. sse.start_async();
  21811. // Wait for at least 2 connections
  21812. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21813. sse.stop();
  21814. // Verify behavior
  21815. std::lock_guard<std::mutex> lock(id_mutex);
  21816. EXPECT_GE(received_last_event_ids.size(), 2u);
  21817. // First connection should have no Last-Event-ID
  21818. if (!received_last_event_ids.empty()) {
  21819. EXPECT_EQ(received_last_event_ids[0], "");
  21820. }
  21821. // Second connection should have Last-Event-ID from first connection
  21822. if (received_last_event_ids.size() >= 2) {
  21823. EXPECT_EQ(received_last_event_ids[1], "event-0");
  21824. }
  21825. }
  21826. // Test: set_headers updates headers used on reconnect
  21827. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  21828. std::vector<std::string> received_tokens;
  21829. std::mutex token_mutex;
  21830. // Endpoint that captures Authorization header
  21831. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  21832. {
  21833. std::lock_guard<std::mutex> lock(token_mutex);
  21834. received_tokens.push_back(req.get_header_value("Authorization"));
  21835. }
  21836. res.set_chunked_content_provider(
  21837. "text/event-stream", [](size_t offset, DataSink &sink) {
  21838. if (offset == 0) {
  21839. std::string event = "data: hello\n\n";
  21840. sink.write(event.data(), event.size());
  21841. }
  21842. return false; // Close connection to trigger reconnect
  21843. });
  21844. });
  21845. Client client("localhost", get_port());
  21846. Headers headers = {{"Authorization", "Bearer old-token"}};
  21847. sse::SSEClient sse(client, "/auth-check", headers);
  21848. // Update headers on each successful connection
  21849. sse.on_open(
  21850. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  21851. sse.set_reconnect_interval(100);
  21852. sse.set_max_reconnect_attempts(3);
  21853. sse.start_async();
  21854. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21855. sse.stop();
  21856. std::lock_guard<std::mutex> lock(token_mutex);
  21857. ASSERT_GE(received_tokens.size(), 2u);
  21858. // First connection uses original header
  21859. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  21860. // Second connection uses updated header from set_headers
  21861. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  21862. }
  21863. // Test: 401 allows reconnection (so on_error can refresh headers)
  21864. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  21865. std::atomic<int> connection_count{0};
  21866. // Endpoint: returns 401 on first attempt, 200 on second
  21867. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  21868. int conn = connection_count.fetch_add(1);
  21869. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  21870. res.status = StatusCode::Unauthorized_401;
  21871. res.set_content("Unauthorized", "text/plain");
  21872. return;
  21873. }
  21874. res.set_chunked_content_provider(
  21875. "text/event-stream", [](size_t offset, DataSink &sink) {
  21876. if (offset == 0) {
  21877. std::string event = "data: authenticated\n\n";
  21878. sink.write(event.data(), event.size());
  21879. }
  21880. return false;
  21881. });
  21882. });
  21883. Client client("localhost", get_port());
  21884. Headers headers = {{"Authorization", "Bearer expired"}};
  21885. sse::SSEClient sse(client, "/auth-retry", headers);
  21886. std::atomic<bool> message_received{false};
  21887. // Refresh token on error
  21888. sse.on_error(
  21889. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  21890. sse.on_message([&](const sse::SSEMessage &msg) {
  21891. if (msg.data == "authenticated") { message_received.store(true); }
  21892. });
  21893. sse.set_reconnect_interval(100);
  21894. sse.set_max_reconnect_attempts(3);
  21895. sse.start_async();
  21896. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21897. sse.stop();
  21898. // Should have reconnected after 401 and succeeded with new token
  21899. EXPECT_GE(connection_count.load(), 2);
  21900. EXPECT_TRUE(message_received.load());
  21901. }
  21902. TEST(Issue2318Test, EmptyHostString) {
  21903. {
  21904. httplib::Client cli_empty("", PORT);
  21905. auto res = cli_empty.Get("/");
  21906. ASSERT_FALSE(res);
  21907. EXPECT_EQ(httplib::Error::Connection, res.error());
  21908. }
  21909. {
  21910. httplib::Client cli(" ", PORT);
  21911. auto res = cli.Get("/");
  21912. ASSERT_FALSE(res);
  21913. EXPECT_EQ(httplib::Error::Connection, res.error());
  21914. }
  21915. }
  21916. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21917. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  21918. Server svr;
  21919. // Set a small payload limit (1KB)
  21920. svr.set_payload_max_length(1024);
  21921. svr.Post("/test", [&](const Request &req, Response &res) {
  21922. res.set_content("Body size: " + std::to_string(req.body.size()),
  21923. "text/plain");
  21924. });
  21925. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  21926. auto se = detail::scope_exit([&] {
  21927. svr.stop();
  21928. listen_thread.join();
  21929. });
  21930. svr.wait_until_ready();
  21931. // Create data that compresses well but exceeds limit when decompressed
  21932. // 8KB of repeated null bytes compresses to a very small size
  21933. std::string original_data(8 * 1024, '\0');
  21934. // Compress the data using gzip
  21935. std::string compressed_data;
  21936. detail::gzip_compressor compressor;
  21937. compressor.compress(original_data.data(), original_data.size(), true,
  21938. [&](const char *data, size_t size) {
  21939. compressed_data.append(data, size);
  21940. return true;
  21941. });
  21942. // Verify compression worked (compressed should be much smaller)
  21943. ASSERT_LT(compressed_data.size(), original_data.size());
  21944. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  21945. // Send compressed data with Content-Encoding: gzip
  21946. Client cli(HOST, PORT);
  21947. Headers headers = {{"Content-Encoding", "gzip"}};
  21948. auto res =
  21949. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  21950. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  21951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21952. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  21953. }
  21954. #endif
  21955. // ============================================================================
  21956. // OpenSSL-Specific Tests
  21957. // ============================================================================
  21958. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21959. X509 *readCertificate(const std::string &strFileName) {
  21960. std::ifstream inStream(strFileName);
  21961. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  21962. std::istreambuf_iterator<char>());
  21963. if (strCertPEM.empty()) return (nullptr);
  21964. BIO *pbCert = BIO_new(BIO_s_mem());
  21965. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  21966. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  21967. BIO_free(pbCert);
  21968. return (pCert);
  21969. }
  21970. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  21971. std::ifstream inStream(strFileName);
  21972. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  21973. std::istreambuf_iterator<char>());
  21974. if (strPrivateKeyPEM.empty()) return (nullptr);
  21975. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  21976. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  21977. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  21978. BIO_free(pbPrivKey);
  21979. return (pPrivateKey);
  21980. }
  21981. TEST(BindServerTest, UpdateCerts) {
  21982. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21983. int port = svr.bind_to_any_port("0.0.0.0");
  21984. ASSERT_TRUE(svr.is_valid());
  21985. ASSERT_TRUE(port > 0);
  21986. X509 *cert = readCertificate(SERVER_CERT_FILE);
  21987. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  21988. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  21989. ASSERT_TRUE(cert != nullptr);
  21990. ASSERT_TRUE(ca_cert != nullptr);
  21991. ASSERT_TRUE(key != nullptr);
  21992. X509_STORE *cert_store = X509_STORE_new();
  21993. X509_STORE_add_cert(cert_store, ca_cert);
  21994. // svr.update_certs(cert, key, cert_store); // deprecated
  21995. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21996. CLIENT_CA_CERT_FILE);
  21997. ASSERT_TRUE(svr.is_valid());
  21998. svr.stop();
  21999. X509_STORE_free(cert_store);
  22000. X509_free(cert);
  22001. X509_free(ca_cert);
  22002. EVP_PKEY_free(key);
  22003. }
  22004. // Test that update_certs() updates client CA list correctly
  22005. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  22006. // Start with file-based constructor
  22007. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22008. ASSERT_TRUE(svr.is_valid());
  22009. // Initially no client CA list should be set
  22010. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22011. ASSERT_TRUE(ssl_ctx != nullptr);
  22012. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  22013. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  22014. EXPECT_EQ(0, count_before);
  22015. // Now update with client CA (PEM string)
  22016. std::string cert_pem, key_pem, ca_pem;
  22017. read_file(SERVER_CERT_FILE, cert_pem);
  22018. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  22019. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  22020. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  22021. ASSERT_TRUE(svr.is_valid());
  22022. // Now client CA list should be set
  22023. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  22024. ASSERT_TRUE(ca_list_after != nullptr);
  22025. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  22026. }
  22027. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  22028. // Test that the file-path SSLServer constructor properly sets the client CA
  22029. // list that is sent to clients during the TLS handshake (CertificateRequest)
  22030. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22031. ASSERT_TRUE(svr.is_valid());
  22032. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22033. ASSERT_TRUE(ssl_ctx != nullptr);
  22034. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  22035. ASSERT_TRUE(ca_list != nullptr);
  22036. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  22037. }
  22038. #endif
  22039. // ============================================================================
  22040. // MbedTLS-Specific Tests
  22041. // ============================================================================
  22042. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  22043. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  22044. using namespace httplib::tls;
  22045. // Track if callback was invoked
  22046. bool callback_invoked = false;
  22047. // The callback receives void* ctx which is actually MbedTlsContext*
  22048. // We can access the mbedtls_ssl_config via the context
  22049. auto setup_callback = [&callback_invoked](void *ctx) {
  22050. callback_invoked = true;
  22051. // Cast to MbedTlsContext* to access the ssl config
  22052. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  22053. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  22054. // Use static variables to hold certificate data (simplified for test)
  22055. static mbedtls_x509_crt own_cert;
  22056. static mbedtls_pk_context own_key;
  22057. static mbedtls_x509_crt ca_chain;
  22058. static bool initialized = false;
  22059. if (!initialized) {
  22060. mbedtls_x509_crt_init(&own_cert);
  22061. mbedtls_pk_init(&own_key);
  22062. mbedtls_x509_crt_init(&ca_chain);
  22063. // Load server certificate
  22064. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  22065. return false;
  22066. }
  22067. // Load server private key.
  22068. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  22069. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  22070. #if MBEDTLS_VERSION_MAJOR == 3
  22071. ,
  22072. mbedtls_ctr_drbg_random, nullptr
  22073. #endif
  22074. ) != 0) {
  22075. return false;
  22076. }
  22077. // Load CA chain for client verification
  22078. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  22079. return false;
  22080. }
  22081. initialized = true;
  22082. }
  22083. // Configure the SSL config
  22084. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  22085. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  22086. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  22087. // Set minimum TLS version using mbedTLS native API
  22088. #if MBEDTLS_VERSION_MAJOR >= 3
  22089. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  22090. #else
  22091. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  22092. MBEDTLS_SSL_MINOR_VERSION_3);
  22093. #endif
  22094. return true;
  22095. };
  22096. SSLServer svr(setup_callback);
  22097. ASSERT_TRUE(svr.is_valid());
  22098. ASSERT_TRUE(callback_invoked);
  22099. svr.Get("/test", [&](const Request &req, Response &res) {
  22100. res.set_content("test", "text/plain");
  22101. auto cert = req.peer_cert();
  22102. ASSERT_TRUE(static_cast<bool>(cert));
  22103. auto common_name = cert.subject_cn();
  22104. EXPECT_EQ("Common Name", common_name);
  22105. });
  22106. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22107. auto se = detail::scope_exit([&] {
  22108. svr.stop();
  22109. t.join();
  22110. ASSERT_FALSE(svr.is_running());
  22111. });
  22112. svr.wait_until_ready();
  22113. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  22114. cli.enable_server_certificate_verification(false);
  22115. cli.set_connection_timeout(30);
  22116. auto res = cli.Get("/test");
  22117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22118. ASSERT_EQ(StatusCode::OK_200, res->status);
  22119. }
  22120. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  22121. // context (owning mbedtls_ssl_config) before shutting down a still-open
  22122. // keep-alive SSL session, which reads through that config in
  22123. // mbedtls_ssl_close_notify.
  22124. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  22125. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22126. ASSERT_TRUE(svr.is_valid());
  22127. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  22128. res.set_content("test", "text/plain");
  22129. });
  22130. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22131. auto se = detail::scope_exit([&] {
  22132. svr.stop();
  22133. t.join();
  22134. ASSERT_FALSE(svr.is_running());
  22135. });
  22136. svr.wait_until_ready();
  22137. {
  22138. SSLClient cli(HOST, PORT);
  22139. cli.enable_server_certificate_verification(false);
  22140. cli.set_keep_alive(true);
  22141. auto res = cli.Get("/test");
  22142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22143. ASSERT_EQ(StatusCode::OK_200, res->status);
  22144. // cli is destructed here with the keep-alive SSL session still open.
  22145. }
  22146. }
  22147. #endif
  22148. // WebSocket Tests
  22149. TEST(WebSocketTest, RSVBitsMustBeZero) {
  22150. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  22151. // defining the meaning of these bits has been negotiated.
  22152. auto make_frame = [](uint8_t first_byte) {
  22153. std::string frame;
  22154. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  22155. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  22156. frame += "Hello";
  22157. return frame;
  22158. };
  22159. // RSV1 set (0x40)
  22160. {
  22161. detail::BufferStream strm;
  22162. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  22163. ws::Opcode opcode;
  22164. std::string payload;
  22165. bool fin;
  22166. EXPECT_EQ(
  22167. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22168. ws::impl::FrameRead::Fail);
  22169. }
  22170. // RSV2 set (0x20)
  22171. {
  22172. detail::BufferStream strm;
  22173. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  22174. ws::Opcode opcode;
  22175. std::string payload;
  22176. bool fin;
  22177. EXPECT_EQ(
  22178. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22179. ws::impl::FrameRead::Fail);
  22180. }
  22181. // RSV3 set (0x10)
  22182. {
  22183. detail::BufferStream strm;
  22184. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  22185. ws::Opcode opcode;
  22186. std::string payload;
  22187. bool fin;
  22188. EXPECT_EQ(
  22189. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22190. ws::impl::FrameRead::Fail);
  22191. }
  22192. // No RSV bits set - should succeed
  22193. {
  22194. detail::BufferStream strm;
  22195. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  22196. ws::Opcode opcode;
  22197. std::string payload;
  22198. bool fin;
  22199. EXPECT_EQ(
  22200. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22201. ws::impl::FrameRead::Ok);
  22202. EXPECT_EQ(ws::Opcode::Text, opcode);
  22203. EXPECT_EQ("Hello", payload);
  22204. EXPECT_TRUE(fin);
  22205. }
  22206. }
  22207. TEST(WebSocketTest, ControlFrameValidation) {
  22208. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  22209. // payload length <= 125.
  22210. // Ping with FIN=0 - must be rejected
  22211. {
  22212. detail::BufferStream strm;
  22213. std::string frame;
  22214. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  22215. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22216. strm.write(frame.data(), frame.size());
  22217. ws::Opcode opcode;
  22218. std::string payload;
  22219. bool fin;
  22220. EXPECT_EQ(
  22221. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22222. ws::impl::FrameRead::Fail);
  22223. }
  22224. // Close with FIN=0 - must be rejected
  22225. {
  22226. detail::BufferStream strm;
  22227. std::string frame;
  22228. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  22229. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22230. strm.write(frame.data(), frame.size());
  22231. ws::Opcode opcode;
  22232. std::string payload;
  22233. bool fin;
  22234. EXPECT_EQ(
  22235. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22236. ws::impl::FrameRead::Fail);
  22237. }
  22238. // Ping with payload_len=126 (extended length) - must be rejected
  22239. {
  22240. detail::BufferStream strm;
  22241. std::string frame;
  22242. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22243. frame += static_cast<char>(126); // payload_len=126 (>125)
  22244. frame += static_cast<char>(0x00); // extended length high byte
  22245. frame += static_cast<char>(126); // extended length low byte
  22246. frame += std::string(126, 'x');
  22247. strm.write(frame.data(), frame.size());
  22248. ws::Opcode opcode;
  22249. std::string payload;
  22250. bool fin;
  22251. EXPECT_EQ(
  22252. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22253. ws::impl::FrameRead::Fail);
  22254. }
  22255. // Ping with FIN=1 and payload_len=125 - should succeed
  22256. {
  22257. detail::BufferStream strm;
  22258. std::string frame;
  22259. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22260. frame += static_cast<char>(125); // payload_len=125
  22261. frame += std::string(125, 'x');
  22262. strm.write(frame.data(), frame.size());
  22263. ws::Opcode opcode;
  22264. std::string payload;
  22265. bool fin;
  22266. EXPECT_EQ(
  22267. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22268. ws::impl::FrameRead::Ok);
  22269. EXPECT_EQ(ws::Opcode::Ping, opcode);
  22270. EXPECT_EQ(125u, payload.size());
  22271. EXPECT_TRUE(fin);
  22272. }
  22273. }
  22274. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  22275. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  22276. // length MUST be 0.
  22277. // MSB set - must be rejected
  22278. {
  22279. detail::BufferStream strm;
  22280. std::string frame;
  22281. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22282. frame += static_cast<char>(127); // 64-bit extended length
  22283. frame += static_cast<char>(0x80); // MSB set (invalid)
  22284. frame += std::string(7, '\0'); // remaining 7 bytes of length
  22285. strm.write(frame.data(), frame.size());
  22286. ws::Opcode opcode;
  22287. std::string payload;
  22288. bool fin;
  22289. EXPECT_EQ(
  22290. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22291. ws::impl::FrameRead::Fail);
  22292. }
  22293. // MSB clear - should pass length parsing (will be rejected by max_len,
  22294. // but that's a different check; use a small length to verify)
  22295. {
  22296. detail::BufferStream strm;
  22297. std::string frame;
  22298. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22299. frame += static_cast<char>(127); // 64-bit extended length
  22300. frame += std::string(7, '\0'); // high bytes = 0
  22301. frame += static_cast<char>(0x03); // length = 3
  22302. frame += "abc";
  22303. strm.write(frame.data(), frame.size());
  22304. ws::Opcode opcode;
  22305. std::string payload;
  22306. bool fin;
  22307. EXPECT_EQ(
  22308. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22309. ws::impl::FrameRead::Ok);
  22310. EXPECT_EQ(ws::Opcode::Text, opcode);
  22311. EXPECT_EQ("abc", payload);
  22312. }
  22313. }
  22314. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  22315. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  22316. // Valid UTF-8
  22317. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  22318. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  22319. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  22320. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  22321. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  22322. // Invalid UTF-8
  22323. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  22324. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  22325. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  22326. EXPECT_FALSE(
  22327. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  22328. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  22329. }
  22330. TEST(WebSocketTest, ConnectAndDisconnect) {
  22331. Server svr;
  22332. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22333. std::string msg;
  22334. while (ws.read(msg)) {}
  22335. });
  22336. auto port = svr.bind_to_any_port(HOST);
  22337. std::thread t([&]() { svr.listen_after_bind(); });
  22338. svr.wait_until_ready();
  22339. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22340. auto res = client.connect();
  22341. ASSERT_TRUE(res);
  22342. EXPECT_EQ(Error::Success, res.error());
  22343. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  22344. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  22345. EXPECT_TRUE(client.is_open());
  22346. client.close();
  22347. EXPECT_FALSE(client.is_open());
  22348. svr.stop();
  22349. t.join();
  22350. }
  22351. TEST(WebSocketTest, ValidURL) {
  22352. ws::WebSocketClient ws1("ws://localhost:8080/path");
  22353. EXPECT_TRUE(ws1.is_valid());
  22354. ws::WebSocketClient ws2("ws://example.com/path");
  22355. EXPECT_TRUE(ws2.is_valid());
  22356. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  22357. EXPECT_TRUE(ws3.is_valid());
  22358. #ifdef CPPHTTPLIB_SSL_ENABLED
  22359. ws::WebSocketClient wss1("wss://example.com/path");
  22360. EXPECT_TRUE(wss1.is_valid());
  22361. ws::WebSocketClient wss2("wss://example.com:443/path");
  22362. EXPECT_TRUE(wss2.is_valid());
  22363. #endif
  22364. }
  22365. TEST(WebSocketTest, InvalidURL) {
  22366. // No scheme
  22367. ws::WebSocketClient ws1("localhost:8080/path");
  22368. EXPECT_FALSE(ws1.is_valid());
  22369. // No path
  22370. ws::WebSocketClient ws2("ws://localhost:8080");
  22371. EXPECT_FALSE(ws2.is_valid());
  22372. // Empty string
  22373. ws::WebSocketClient ws3("");
  22374. EXPECT_FALSE(ws3.is_valid());
  22375. // Missing host
  22376. ws::WebSocketClient ws4("ws://:8080/path");
  22377. EXPECT_FALSE(ws4.is_valid());
  22378. // Port number overflow — should not crash
  22379. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  22380. EXPECT_FALSE(ws5.is_valid());
  22381. // Port out of range
  22382. ws::WebSocketClient ws6("ws://localhost:99999/path");
  22383. EXPECT_FALSE(ws6.is_valid());
  22384. }
  22385. TEST(WebSocketTest, UnsupportedScheme) {
  22386. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  22387. ws::WebSocketClient ws1("http://localhost:8080/path");
  22388. EXPECT_FALSE(ws1.is_valid());
  22389. ws::WebSocketClient ws2("https://localhost:8080/path");
  22390. EXPECT_FALSE(ws2.is_valid());
  22391. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  22392. EXPECT_FALSE(ws3.is_valid());
  22393. #else
  22394. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  22395. std::invalid_argument);
  22396. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  22397. std::invalid_argument);
  22398. #endif
  22399. }
  22400. TEST(WebSocketTest, ConnectWhenInvalid) {
  22401. ws::WebSocketClient ws("not a valid url");
  22402. EXPECT_FALSE(ws.is_valid());
  22403. auto res = ws.connect();
  22404. EXPECT_FALSE(res);
  22405. EXPECT_EQ(Error::Connection, res.error());
  22406. EXPECT_EQ(-1, res.status());
  22407. }
  22408. TEST(WebSocketTest, ConnectRefusedReportsError) {
  22409. // Grab a port that is free, then close it again so nothing listens there
  22410. Server svr;
  22411. auto port = svr.bind_to_any_port(HOST);
  22412. svr.stop();
  22413. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22414. auto res = client.connect();
  22415. ASSERT_FALSE(res);
  22416. EXPECT_EQ(Error::Connection, res.error());
  22417. EXPECT_EQ(-1, res.status());
  22418. }
  22419. TEST(WebSocketTest, DefaultPort) {
  22420. ws::WebSocketClient ws1("ws://example.com/path");
  22421. EXPECT_TRUE(ws1.is_valid());
  22422. // ws:// defaults to port 80 (verified by successful parse)
  22423. #ifdef CPPHTTPLIB_SSL_ENABLED
  22424. ws::WebSocketClient ws2("wss://example.com/path");
  22425. EXPECT_TRUE(ws2.is_valid());
  22426. // wss:// defaults to port 443 (verified by successful parse)
  22427. #endif
  22428. }
  22429. TEST(WebSocketTest, IPv6LiteralAddress) {
  22430. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  22431. EXPECT_TRUE(ws1.is_valid());
  22432. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  22433. EXPECT_TRUE(ws2.is_valid());
  22434. }
  22435. TEST(WebSocketTest, ComplexPath) {
  22436. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  22437. EXPECT_TRUE(ws1.is_valid());
  22438. ws::WebSocketClient ws2("ws://localhost:8080/");
  22439. EXPECT_TRUE(ws2.is_valid());
  22440. }
  22441. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  22442. Server svr;
  22443. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22444. std::string msg;
  22445. while (ws.read(msg)) {}
  22446. });
  22447. auto port = svr.bind_to_any_port(HOST);
  22448. std::thread t([&]() { svr.listen_after_bind(); });
  22449. svr.wait_until_ready();
  22450. auto another_host = "example.com";
  22451. auto wrong_ip = "192.0.2.1";
  22452. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22453. client.set_hostname_addr_map({{another_host, wrong_ip}});
  22454. ASSERT_TRUE(client.connect());
  22455. EXPECT_TRUE(client.is_open());
  22456. client.close();
  22457. svr.stop();
  22458. t.join();
  22459. }
  22460. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  22461. Server svr;
  22462. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22463. std::string msg;
  22464. while (ws.read(msg)) {}
  22465. });
  22466. auto port = svr.bind_to_any_port(HOST);
  22467. std::thread t([&]() { svr.listen_after_bind(); });
  22468. svr.wait_until_ready();
  22469. auto wrong_ip = "192.0.2.1";
  22470. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22471. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  22472. client.set_connection_timeout(1);
  22473. client.set_read_timeout(1);
  22474. client.set_write_timeout(1);
  22475. EXPECT_FALSE(client.connect());
  22476. EXPECT_FALSE(client.is_open());
  22477. svr.stop();
  22478. t.join();
  22479. }
  22480. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  22481. // A mapped value that is not an IP literal must be resolved. HOST resolves
  22482. // from the hosts file, so this test needs no external DNS. "target.invalid"
  22483. // (RFC 6761) is only a map key and the Host header value.
  22484. auto host = "target.invalid";
  22485. Server svr;
  22486. std::string received_host;
  22487. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22488. received_host = req.get_header_value("Host");
  22489. std::string msg;
  22490. while (ws.read(msg)) {}
  22491. });
  22492. auto port = svr.bind_to_any_port(HOST);
  22493. std::thread t([&]() { svr.listen_after_bind(); });
  22494. // ASSERT_* below returns from the test body, which would leave t joinable
  22495. // and make ~thread call std::terminate.
  22496. auto se = detail::scope_exit([&] {
  22497. svr.stop();
  22498. if (t.joinable()) { t.join(); }
  22499. });
  22500. svr.wait_until_ready();
  22501. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  22502. std::to_string(port) + "/ws");
  22503. client.set_hostname_addr_map({{host, HOST}});
  22504. ASSERT_TRUE(client.connect());
  22505. EXPECT_TRUE(client.is_open());
  22506. client.close();
  22507. svr.stop();
  22508. t.join();
  22509. // The mapping only redirects the connection; the identity stays host_.
  22510. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  22511. }
  22512. class WebSocketIntegrationTest : public ::testing::Test {
  22513. protected:
  22514. void SetUp() override {
  22515. server_ = httplib::detail::make_unique<Server>();
  22516. setup_server();
  22517. start_server();
  22518. }
  22519. void TearDown() override {
  22520. server_->stop();
  22521. if (server_thread_.joinable()) { server_thread_.join(); }
  22522. }
  22523. void setup_server() {
  22524. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22525. std::string msg;
  22526. ws::ReadResult ret;
  22527. while ((ret = ws.read(msg))) {
  22528. if (ret == ws::Binary) {
  22529. ws.send(msg.data(), msg.size());
  22530. } else {
  22531. ws.send(msg);
  22532. }
  22533. }
  22534. });
  22535. server_->WebSocket("/ws-echo-string",
  22536. [](const Request &, ws::WebSocket &ws) {
  22537. std::string msg;
  22538. while (ws.read(msg)) {
  22539. ws.send("echo: " + msg);
  22540. }
  22541. });
  22542. server_->WebSocket(
  22543. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  22544. // Echo back request metadata
  22545. ws.send("path:" + req.path);
  22546. ws.send("header:" + req.get_header_value("X-Test-Header"));
  22547. std::string msg;
  22548. while (ws.read(msg)) {}
  22549. });
  22550. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  22551. std::string msg;
  22552. ws.read(msg); // wait for a message
  22553. ws.close();
  22554. });
  22555. server_->WebSocket("/ws-close-status",
  22556. [](const Request &, ws::WebSocket &ws) {
  22557. std::string msg;
  22558. ws.read(msg); // wait for a message
  22559. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  22560. });
  22561. server_->WebSocket(
  22562. "/ws-subprotocol",
  22563. [](const Request &, ws::WebSocket &ws) {
  22564. std::string msg;
  22565. while (ws.read(msg)) {
  22566. ws.send(msg);
  22567. }
  22568. },
  22569. [](const std::vector<std::string> &protocols) -> std::string {
  22570. for (const auto &p : protocols) {
  22571. if (p == "graphql-ws") { return p; }
  22572. }
  22573. return "";
  22574. });
  22575. server_->WebSocket(
  22576. "/ws-subprotocol-unoffered",
  22577. [](const Request &, ws::WebSocket &ws) {
  22578. std::string msg;
  22579. while (ws.read(msg)) {
  22580. ws.send(msg);
  22581. }
  22582. },
  22583. [](const std::vector<std::string> &) -> std::string {
  22584. return "admin";
  22585. });
  22586. }
  22587. void start_server() {
  22588. port_ = server_->bind_to_any_port(HOST);
  22589. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22590. server_->wait_until_ready();
  22591. }
  22592. std::unique_ptr<Server> server_;
  22593. std::thread server_thread_;
  22594. int port_ = 0;
  22595. };
  22596. TEST_F(WebSocketIntegrationTest, TextEcho) {
  22597. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22598. "/ws-echo");
  22599. ASSERT_TRUE(client.connect());
  22600. ASSERT_TRUE(client.is_open());
  22601. ASSERT_TRUE(client.send("Hello WebSocket"));
  22602. std::string msg;
  22603. EXPECT_EQ(ws::Text, client.read(msg));
  22604. EXPECT_EQ("Hello WebSocket", msg);
  22605. client.close();
  22606. }
  22607. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  22608. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22609. "/ws-echo");
  22610. ASSERT_TRUE(client.connect());
  22611. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  22612. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  22613. std::string msg;
  22614. EXPECT_EQ(ws::Binary, client.read(msg));
  22615. EXPECT_EQ(binary_data, msg);
  22616. client.close();
  22617. }
  22618. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  22619. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22620. "/ws-echo");
  22621. ASSERT_TRUE(client.connect());
  22622. for (int i = 0; i < 10; i++) {
  22623. auto text = "message " + std::to_string(i);
  22624. ASSERT_TRUE(client.send(text));
  22625. std::string msg;
  22626. ASSERT_TRUE(client.read(msg));
  22627. EXPECT_EQ(text, msg);
  22628. }
  22629. client.close();
  22630. }
  22631. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  22632. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22633. "/ws-close");
  22634. ASSERT_TRUE(client.connect());
  22635. // Send a message to trigger the server to close
  22636. ASSERT_TRUE(client.send("trigger close"));
  22637. // The server will close, so read should return false
  22638. std::string msg;
  22639. EXPECT_FALSE(client.read(msg));
  22640. EXPECT_FALSE(client.is_open());
  22641. }
  22642. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  22643. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22644. "/ws-echo");
  22645. ASSERT_TRUE(client.connect());
  22646. // 128KB message
  22647. std::string large_data(128 * 1024, 'X');
  22648. ASSERT_TRUE(client.send(large_data));
  22649. std::string msg;
  22650. ASSERT_TRUE(client.read(msg));
  22651. EXPECT_EQ(large_data, msg);
  22652. client.close();
  22653. }
  22654. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  22655. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22656. "/ws-echo");
  22657. ASSERT_TRUE(client.connect());
  22658. const int num_threads = 4;
  22659. std::vector<std::thread> threads;
  22660. std::atomic<int> send_count{0};
  22661. for (int t = 0; t < num_threads; t++) {
  22662. threads.emplace_back([&client, &send_count, t]() {
  22663. for (int i = 0; i < 5; i++) {
  22664. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  22665. if (client.send(text)) { send_count++; }
  22666. }
  22667. });
  22668. }
  22669. for (auto &th : threads) {
  22670. th.join();
  22671. }
  22672. int received = 0;
  22673. std::string msg;
  22674. while (received < send_count.load()) {
  22675. if (!client.read(msg)) { break; }
  22676. received++;
  22677. }
  22678. EXPECT_EQ(send_count.load(), received);
  22679. client.close();
  22680. }
  22681. TEST_F(WebSocketIntegrationTest, ReadString) {
  22682. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22683. "/ws-echo-string");
  22684. ASSERT_TRUE(client.connect());
  22685. ASSERT_TRUE(client.send("hello"));
  22686. std::string msg;
  22687. ASSERT_TRUE(client.read(msg));
  22688. EXPECT_EQ("echo: hello", msg);
  22689. ASSERT_TRUE(client.send("world"));
  22690. ASSERT_TRUE(client.read(msg));
  22691. EXPECT_EQ("echo: world", msg);
  22692. client.close();
  22693. }
  22694. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  22695. Headers headers = {{"X-Test-Header", "test-value"}};
  22696. ws::WebSocketClient client(
  22697. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  22698. ASSERT_TRUE(client.connect());
  22699. std::string msg;
  22700. ASSERT_TRUE(client.read(msg));
  22701. EXPECT_EQ("path:/ws-request-info", msg);
  22702. ASSERT_TRUE(client.read(msg));
  22703. EXPECT_EQ("header:test-value", msg);
  22704. client.close();
  22705. }
  22706. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  22707. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22708. "/ws-echo");
  22709. client.set_read_timeout(1, 0); // 1 second
  22710. ASSERT_TRUE(client.connect());
  22711. // Don't send anything — server echo handler waits for a message, so read()
  22712. // should time out. The connection survives it: nothing was consumed.
  22713. std::string msg;
  22714. EXPECT_EQ(client.read(msg), ws::Timeout);
  22715. EXPECT_TRUE(client.is_open());
  22716. // And it is still usable afterwards.
  22717. EXPECT_TRUE(client.send("after timeout"));
  22718. EXPECT_EQ(client.read(msg), ws::Text);
  22719. EXPECT_EQ(msg, "after timeout");
  22720. }
  22721. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  22722. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22723. "/ws-echo");
  22724. client.set_read_timeout(1, 0);
  22725. ASSERT_TRUE(client.connect());
  22726. ASSERT_TRUE(client.send("first"));
  22727. std::string msg;
  22728. ASSERT_EQ(client.read(msg), ws::Text);
  22729. ASSERT_EQ(msg, "first");
  22730. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  22731. // not be used with a read timeout: it would reprocess the previous message.
  22732. EXPECT_EQ(client.read(msg), ws::Timeout);
  22733. EXPECT_EQ(msg, "first");
  22734. }
  22735. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  22736. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22737. "/ws-echo");
  22738. ASSERT_TRUE(client.connect());
  22739. // Setting it once the connection is open reaches the live stream, not just
  22740. // the seed for the next connect().
  22741. client.set_read_timeout(1, 0);
  22742. std::string msg;
  22743. EXPECT_EQ(client.read(msg), ws::Timeout);
  22744. EXPECT_TRUE(client.is_open());
  22745. }
  22746. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  22747. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22748. "/ws-echo");
  22749. client.set_read_timeout(5, 0);
  22750. ASSERT_TRUE(client.connect());
  22751. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22752. // The server should reject it and close the connection.
  22753. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  22754. client.send(oversized);
  22755. // The server's read() should have failed due to payload limit,
  22756. // so our read() should return false (connection closed).
  22757. std::string msg;
  22758. EXPECT_FALSE(client.read(msg));
  22759. }
  22760. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  22761. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22762. "/ws-echo");
  22763. client.set_read_timeout(10, 0);
  22764. ASSERT_TRUE(client.connect());
  22765. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22766. // This should succeed.
  22767. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  22768. ASSERT_TRUE(client.send(at_limit));
  22769. std::string msg;
  22770. ASSERT_TRUE(client.read(msg));
  22771. EXPECT_EQ(at_limit.size(), msg.size());
  22772. client.close();
  22773. }
  22774. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  22775. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22776. "/nonexistent");
  22777. auto res = client.connect();
  22778. EXPECT_FALSE(res);
  22779. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22780. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  22781. EXPECT_FALSE(client.is_open());
  22782. }
  22783. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  22784. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22785. "/ws-echo");
  22786. ASSERT_TRUE(client.connect());
  22787. ASSERT_TRUE(client.send(""));
  22788. std::string msg;
  22789. EXPECT_EQ(ws::Text, client.read(msg));
  22790. EXPECT_EQ("", msg);
  22791. client.close();
  22792. }
  22793. TEST_F(WebSocketIntegrationTest, Reconnect) {
  22794. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22795. "/ws-echo");
  22796. // First connection
  22797. ASSERT_TRUE(client.connect());
  22798. ASSERT_TRUE(client.send("first"));
  22799. std::string msg;
  22800. ASSERT_TRUE(client.read(msg));
  22801. EXPECT_EQ("first", msg);
  22802. client.close();
  22803. EXPECT_FALSE(client.is_open());
  22804. // Reconnect using the same client object
  22805. ASSERT_TRUE(client.connect());
  22806. ASSERT_TRUE(client.is_open());
  22807. ASSERT_TRUE(client.send("second"));
  22808. ASSERT_TRUE(client.read(msg));
  22809. EXPECT_EQ("second", msg);
  22810. client.close();
  22811. }
  22812. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  22813. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22814. "/ws-close-status");
  22815. ASSERT_TRUE(client.connect());
  22816. // Trigger the server to close with GoingAway status
  22817. ASSERT_TRUE(client.send("trigger"));
  22818. // read() should return false after receiving the close frame
  22819. std::string msg;
  22820. EXPECT_FALSE(client.read(msg));
  22821. EXPECT_FALSE(client.is_open());
  22822. }
  22823. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  22824. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22825. "/ws-echo");
  22826. ASSERT_TRUE(client.connect());
  22827. client.close(ws::CloseStatus::GoingAway, "client leaving");
  22828. EXPECT_FALSE(client.is_open());
  22829. }
  22830. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  22831. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  22832. ws::WebSocketClient client(
  22833. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22834. ASSERT_TRUE(client.connect());
  22835. // Server should have selected graphql-ws
  22836. EXPECT_EQ("graphql-ws", client.subprotocol());
  22837. client.close();
  22838. }
  22839. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  22840. Headers headers;
  22841. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  22842. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  22843. ws::WebSocketClient client(
  22844. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22845. ASSERT_TRUE(client.connect());
  22846. // The offer on the second field line counts too, so graphql-ws is selected
  22847. EXPECT_EQ("graphql-ws", client.subprotocol());
  22848. client.close();
  22849. }
  22850. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  22851. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  22852. ws::WebSocketClient client(
  22853. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22854. ASSERT_TRUE(client.connect());
  22855. // Server should not have selected any subprotocol
  22856. EXPECT_TRUE(client.subprotocol().empty());
  22857. client.close();
  22858. }
  22859. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  22860. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22861. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22862. "/ws-subprotocol-unoffered",
  22863. headers);
  22864. ASSERT_TRUE(client.connect());
  22865. EXPECT_TRUE(client.subprotocol().empty());
  22866. client.close();
  22867. }
  22868. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  22869. // Connect without requesting any subprotocol
  22870. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22871. "/ws-subprotocol");
  22872. ASSERT_TRUE(client.connect());
  22873. EXPECT_TRUE(client.subprotocol().empty());
  22874. client.close();
  22875. }
  22876. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  22877. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22878. "/ws-echo");
  22879. client.set_tcp_nodelay(true);
  22880. client.set_connection_timeout(3, 0);
  22881. bool socket_options_called = false;
  22882. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  22883. ASSERT_TRUE(client.connect());
  22884. ASSERT_TRUE(client.is_open());
  22885. EXPECT_TRUE(socket_options_called);
  22886. ASSERT_TRUE(client.send("hello"));
  22887. std::string msg;
  22888. auto result = client.read(msg);
  22889. EXPECT_EQ(result, ws::ReadResult::Text);
  22890. EXPECT_EQ(msg, "hello");
  22891. client.close();
  22892. }
  22893. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  22894. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22895. "/ws-echo");
  22896. client.set_connection_timeout(std::chrono::seconds(3));
  22897. client.set_write_timeout(std::chrono::seconds(3));
  22898. // A sub-second remainder exercises the seconds/microseconds split.
  22899. client.set_read_timeout(std::chrono::milliseconds(1500));
  22900. ASSERT_TRUE(client.connect());
  22901. auto start = std::chrono::steady_clock::now();
  22902. std::string msg;
  22903. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  22904. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  22905. std::chrono::steady_clock::now() - start)
  22906. .count();
  22907. // Above 1s so that dropping the microseconds half of the split fails here.
  22908. // Ignoring the setter altogether would not reach this line at all: a client
  22909. // waits forever by default.
  22910. EXPECT_GE(elapsed, 1400);
  22911. EXPECT_LT(elapsed, 30000);
  22912. }
  22913. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  22914. Server svr;
  22915. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  22916. if (!req.has_header("Authorization")) {
  22917. res.status = StatusCode::Unauthorized_401;
  22918. res.set_content("Unauthorized", "text/plain");
  22919. return Server::HandlerResponse::Handled;
  22920. }
  22921. return Server::HandlerResponse::Unhandled;
  22922. });
  22923. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22924. std::string msg;
  22925. while (ws.read(msg)) {
  22926. ws.send(msg);
  22927. }
  22928. });
  22929. auto port = svr.bind_to_any_port("localhost");
  22930. std::thread t([&]() { svr.listen_after_bind(); });
  22931. svr.wait_until_ready();
  22932. // Without Authorization header - should be rejected before upgrade
  22933. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  22934. EXPECT_FALSE(client1.connect());
  22935. // The rejection is framed like any other HTTP response
  22936. {
  22937. Client cli("localhost", port);
  22938. Headers headers = {{"Upgrade", "websocket"},
  22939. {"Connection", "Upgrade"},
  22940. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22941. {"Sec-WebSocket-Version", "13"}};
  22942. auto res = cli.Get("/ws", headers);
  22943. ASSERT_TRUE(res);
  22944. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22945. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22946. EXPECT_EQ("Unauthorized", res->body);
  22947. }
  22948. // With Authorization header - should succeed
  22949. Headers headers = {{"Authorization", "Bearer token123"}};
  22950. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  22951. headers);
  22952. ASSERT_TRUE(client2.connect());
  22953. ASSERT_TRUE(client2.send("hello"));
  22954. std::string msg;
  22955. ASSERT_TRUE(client2.read(msg));
  22956. EXPECT_EQ("hello", msg);
  22957. client2.close();
  22958. svr.stop();
  22959. t.join();
  22960. }
  22961. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  22962. Server svr;
  22963. std::atomic<int> pre_request_calls{0};
  22964. std::atomic<bool> route_matched{false};
  22965. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  22966. pre_request_calls++;
  22967. if (req.matched_route == "/ws/:id") { route_matched = true; }
  22968. if (req.get_header_value("Authorization") != "Bearer token123") {
  22969. res.status = StatusCode::Unauthorized_401;
  22970. res.set_content("Unauthorized", "text/plain");
  22971. return Server::HandlerResponse::Handled;
  22972. }
  22973. return Server::HandlerResponse::Unhandled;
  22974. });
  22975. std::atomic<bool> handler_called{false};
  22976. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  22977. handler_called = true;
  22978. ws.send(req.matched_route + " " + req.path_params.at("id"));
  22979. });
  22980. auto port = svr.bind_to_any_port("localhost");
  22981. std::thread t([&]() { svr.listen_after_bind(); });
  22982. svr.wait_until_ready();
  22983. // Without Authorization header - should be rejected before upgrade
  22984. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  22985. "/ws/1");
  22986. EXPECT_FALSE(client1.connect());
  22987. EXPECT_FALSE(handler_called);
  22988. EXPECT_EQ(1, pre_request_calls);
  22989. EXPECT_TRUE(route_matched);
  22990. // The rejection is an ordinary HTTP response, not a protocol switch
  22991. {
  22992. Client cli("localhost", port);
  22993. Headers headers = {{"Upgrade", "websocket"},
  22994. {"Connection", "Upgrade"},
  22995. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22996. {"Sec-WebSocket-Version", "13"}};
  22997. auto res = cli.Get("/ws/1", headers);
  22998. ASSERT_TRUE(res);
  22999. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23000. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23001. EXPECT_EQ("Unauthorized", res->body);
  23002. }
  23003. EXPECT_FALSE(handler_called);
  23004. // With Authorization header - should succeed
  23005. Headers headers = {{"Authorization", "Bearer token123"}};
  23006. ws::WebSocketClient client2(
  23007. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  23008. ASSERT_TRUE(client2.connect());
  23009. std::string msg;
  23010. ASSERT_TRUE(client2.read(msg));
  23011. EXPECT_EQ("/ws/:id 2", msg);
  23012. EXPECT_TRUE(handler_called);
  23013. client2.close();
  23014. svr.stop();
  23015. t.join();
  23016. }
  23017. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  23018. Server svr;
  23019. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23020. // A read timeout is how a handler gets control back. Without it, a handler
  23021. // parked in read() can never write on the connection it is reading.
  23022. ws.set_read_timeout(std::chrono::milliseconds(100));
  23023. std::string msg;
  23024. while (ws.is_open()) {
  23025. auto r = ws.read(msg);
  23026. if (r == httplib::ws::Timeout) {
  23027. ws.send("tick");
  23028. continue;
  23029. }
  23030. if (r == httplib::ws::Fail) { break; }
  23031. ws.send(msg);
  23032. }
  23033. });
  23034. auto port = svr.bind_to_any_port("localhost");
  23035. std::thread t([&]() { svr.listen_after_bind(); });
  23036. svr.wait_until_ready();
  23037. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23038. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  23039. ASSERT_TRUE(client.connect());
  23040. // The client sends nothing, so anything it receives came out of the
  23041. // handler's timeout path.
  23042. std::string msg;
  23043. ASSERT_EQ(client.read(msg), ws::Text);
  23044. EXPECT_EQ("tick", msg);
  23045. client.close();
  23046. svr.stop();
  23047. t.join();
  23048. }
  23049. // Stream::read may return fewer bytes than asked for. This is that contract at
  23050. // its worst -- one byte per call -- which is what a frame header straddling a
  23051. // read buffer's boundary looks like to the frame parser.
  23052. class WsByteAtATimeStream : public Stream {
  23053. public:
  23054. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  23055. bool is_readable() const override { return true; }
  23056. bool wait_readable() const override { return true; }
  23057. bool wait_writable() const override { return true; }
  23058. ssize_t read(char *ptr, size_t size) override {
  23059. if (size == 0 || pos_ >= data_.size()) { return 0; }
  23060. *ptr = data_[pos_++];
  23061. return 1;
  23062. }
  23063. ssize_t write(const char *, size_t size) override {
  23064. return static_cast<ssize_t>(size);
  23065. }
  23066. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  23067. ip = "127.0.0.1";
  23068. port = 0;
  23069. }
  23070. void get_local_ip_and_port(std::string &ip, int &port) const override {
  23071. ip = "127.0.0.1";
  23072. port = 0;
  23073. }
  23074. socket_t socket() const override { return INVALID_SOCKET; }
  23075. time_t duration() const override { return 0; }
  23076. private:
  23077. std::string data_;
  23078. size_t pos_ = 0;
  23079. };
  23080. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  23081. // The payload uses the 16-bit extended length, so the header, the length
  23082. // and the mask key are all multi-byte fields here. Each used to be read
  23083. // with a single read() call, which fails as soon as one is split. The
  23084. // payload is also a little over one read chunk, so it is read in two.
  23085. std::string body;
  23086. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  23087. body += static_cast<char>(i % 251);
  23088. }
  23089. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  23090. std::string frame;
  23091. frame += static_cast<char>(0x81); // FIN + Text
  23092. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  23093. frame += static_cast<char>(body.size() >> 8);
  23094. frame += static_cast<char>(body.size() & 0xff);
  23095. for (size_t i = 0; i < 4; i++) {
  23096. frame += static_cast<char>(mask[i]);
  23097. }
  23098. for (size_t i = 0; i < body.size(); i++) {
  23099. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  23100. }
  23101. WsByteAtATimeStream strm(frame);
  23102. ws::Opcode opcode;
  23103. std::string payload;
  23104. bool fin = false;
  23105. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  23106. /*expect_masked=*/true, body.size()),
  23107. ws::impl::FrameRead::Ok);
  23108. EXPECT_TRUE(fin);
  23109. EXPECT_EQ(opcode, ws::Opcode::Text);
  23110. EXPECT_EQ(payload, body);
  23111. }
  23112. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  23113. std::string body(2000, 'x');
  23114. std::string frame;
  23115. frame += static_cast<char>(0x82); // FIN + Binary
  23116. frame += static_cast<char>(126); // 16-bit length follows
  23117. frame += static_cast<char>(body.size() >> 8);
  23118. frame += static_cast<char>(body.size() & 0xff);
  23119. frame += body;
  23120. detail::BufferStream strm;
  23121. strm.write(frame.data(), frame.size());
  23122. ws::Opcode opcode;
  23123. std::string payload;
  23124. bool fin;
  23125. EXPECT_EQ(
  23126. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  23127. ws::impl::FrameRead::Ok);
  23128. EXPECT_EQ(body, payload);
  23129. }
  23130. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  23131. // The header announces the largest payload allowed, and only 3 bytes of it
  23132. // ever arrive.
  23133. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  23134. std::string frame;
  23135. frame += static_cast<char>(0x82); // FIN + Binary
  23136. frame += static_cast<char>(127); // 64-bit length follows
  23137. for (int shift = 56; shift >= 0; shift -= 8) {
  23138. frame += static_cast<char>((len >> shift) & 0xff);
  23139. }
  23140. frame += "abc";
  23141. detail::BufferStream strm;
  23142. strm.write(frame.data(), frame.size());
  23143. ws::Opcode opcode;
  23144. std::string payload;
  23145. bool fin;
  23146. EXPECT_EQ(
  23147. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  23148. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  23149. ws::impl::FrameRead::Fail);
  23150. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  23151. }
  23152. TEST(WebSocketTest, QueryStringInHandshake) {
  23153. Server svr;
  23154. std::mutex mtx;
  23155. std::string received_target;
  23156. std::string received_token;
  23157. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23158. {
  23159. std::lock_guard<std::mutex> lock(mtx);
  23160. received_target = req.target;
  23161. if (req.has_param("token")) {
  23162. received_token = req.get_param_value("token");
  23163. }
  23164. }
  23165. std::string msg;
  23166. while (ws.read(msg)) {
  23167. ws.send(msg);
  23168. }
  23169. });
  23170. auto port = svr.bind_to_any_port("localhost");
  23171. std::thread t([&]() { svr.listen_after_bind(); });
  23172. svr.wait_until_ready();
  23173. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23174. "/ws?token=ABC&session=123");
  23175. ASSERT_TRUE(client.connect());
  23176. // Round-trip ensures the handler has run and captured the request.
  23177. ASSERT_TRUE(client.send("hello"));
  23178. std::string msg;
  23179. ASSERT_TRUE(client.read(msg));
  23180. EXPECT_EQ("hello", msg);
  23181. client.close();
  23182. {
  23183. std::lock_guard<std::mutex> lock(mtx);
  23184. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  23185. EXPECT_EQ("ABC", received_token);
  23186. }
  23187. svr.stop();
  23188. t.join();
  23189. }
  23190. // Run a handshake against a throwaway server and hand the request the server
  23191. // received back to the caller, so tests can assert on the headers the client
  23192. // actually put on the wire.
  23193. static void capture_websocket_handshake_request(
  23194. const Headers &client_headers,
  23195. std::function<void(const Request &, int port)> verify) {
  23196. Server svr;
  23197. std::mutex mtx;
  23198. Request received;
  23199. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23200. {
  23201. std::lock_guard<std::mutex> lock(mtx);
  23202. received = req;
  23203. }
  23204. std::string msg;
  23205. while (ws.read(msg)) {
  23206. ws.send(msg);
  23207. }
  23208. });
  23209. auto port = svr.bind_to_any_port("localhost");
  23210. std::thread t([&]() { svr.listen_after_bind(); });
  23211. auto se = detail::scope_exit([&] {
  23212. svr.stop();
  23213. t.join();
  23214. });
  23215. svr.wait_until_ready();
  23216. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  23217. client_headers);
  23218. ASSERT_TRUE(client.connect());
  23219. ASSERT_TRUE(client.send("hello"));
  23220. std::string msg;
  23221. ASSERT_TRUE(client.read(msg));
  23222. client.close();
  23223. {
  23224. std::lock_guard<std::mutex> lock(mtx);
  23225. verify(received, port);
  23226. }
  23227. }
  23228. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  23229. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  23230. // Non-default port must be present in the Host header. Default ports
  23231. // (80/443) are omitted; that logic is covered by
  23232. // MakeHostAndPortStringTest.
  23233. EXPECT_EQ("localhost:" + std::to_string(port),
  23234. req.get_header_value("Host"));
  23235. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  23236. req.get_header_value("User-Agent"));
  23237. EXPECT_FALSE(req.has_header("Accept"));
  23238. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  23239. EXPECT_FALSE(req.has_header("Content-Length"));
  23240. });
  23241. }
  23242. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  23243. capture_websocket_handshake_request(
  23244. {{"Host", "example.com"},
  23245. {"User-Agent", "custom-agent"},
  23246. {"X-Custom", "value"}},
  23247. [](const Request &req, int) {
  23248. EXPECT_EQ("example.com", req.get_header_value("Host"));
  23249. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  23250. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  23251. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  23252. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  23253. });
  23254. }
  23255. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  23256. capture_websocket_handshake_request(
  23257. {{"Upgrade", "bogus"},
  23258. {"Connection", "close"},
  23259. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  23260. {"Sec-WebSocket-Version", "8"}},
  23261. [](const Request &req, int) {
  23262. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  23263. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  23264. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  23265. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  23266. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  23267. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  23268. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  23269. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  23270. req.get_header_value("Sec-WebSocket-Key"));
  23271. });
  23272. }
  23273. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  23274. // A header the client refuses to send must abort the handshake before any
  23275. // part of it reaches the wire; a lone request line would otherwise sit in
  23276. // the peer's buffer as a truncated request.
  23277. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  23278. ASSERT_NE(INVALID_SOCKET, srv);
  23279. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  23280. sockaddr_in addr{};
  23281. addr.sin_family = AF_INET;
  23282. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  23283. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23284. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  23285. ASSERT_EQ(0, ::listen(srv, 1));
  23286. sockaddr_in bound{};
  23287. socklen_t bound_len = sizeof(bound);
  23288. ASSERT_EQ(
  23289. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  23290. auto port = ntohs(bound.sin_port);
  23291. ssize_t received = -1;
  23292. std::thread t([&] {
  23293. // Bound every blocking call so a regression fails the test with a bad
  23294. // value instead of hanging the suite.
  23295. fd_set rfds;
  23296. FD_ZERO(&rfds);
  23297. FD_SET(srv, &rfds);
  23298. timeval tv{5, 0};
  23299. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  23300. 0) {
  23301. return;
  23302. }
  23303. sockaddr_in cli_addr{};
  23304. socklen_t cli_len = sizeof(cli_addr);
  23305. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  23306. if (cli == INVALID_SOCKET) { return; }
  23307. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  23308. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23309. char buf[4096];
  23310. received = ::recv(cli, buf, sizeof(buf), 0);
  23311. });
  23312. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  23313. // connect() has already shut the socket down by the time it returns false,
  23314. // so the peer sees EOF without waiting for the client to be destroyed.
  23315. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  23316. {{"X-Bad", "a\r\nInjected: 1"}});
  23317. EXPECT_FALSE(client.connect());
  23318. t.join();
  23319. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  23320. EXPECT_EQ(0, received);
  23321. }
  23322. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  23323. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  23324. // contains "upgrade" as a substring is a different token and must not
  23325. // start a WebSocket handshake.
  23326. auto make_request = [](const std::vector<std::string> &connection_values) {
  23327. Request req;
  23328. req.method = "GET";
  23329. req.headers.emplace("Upgrade", "websocket");
  23330. for (const auto &value : connection_values) {
  23331. req.headers.emplace("Connection", value);
  23332. }
  23333. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23334. req.headers.emplace("Sec-WebSocket-Version", "13");
  23335. return req;
  23336. };
  23337. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  23338. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  23339. EXPECT_TRUE(
  23340. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  23341. EXPECT_TRUE(
  23342. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  23343. EXPECT_TRUE(
  23344. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  23345. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  23346. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  23347. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  23348. EXPECT_FALSE(
  23349. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  23350. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  23351. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23352. }
  23353. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  23354. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  23355. // asks recipients to match each protocol-name case-insensitively, and RFC
  23356. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  23357. // client naming websocket alongside another protocol, or on a second field
  23358. // line, is offering websocket; a value that merely contains "websocket" as a
  23359. // substring is a different protocol name and is not.
  23360. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  23361. Request req;
  23362. req.method = "GET";
  23363. for (const auto &value : upgrade_values) {
  23364. req.headers.emplace("Upgrade", value);
  23365. }
  23366. req.headers.emplace("Connection", "Upgrade");
  23367. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23368. req.headers.emplace("Sec-WebSocket-Version", "13");
  23369. return req;
  23370. };
  23371. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  23372. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  23373. EXPECT_TRUE(
  23374. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  23375. EXPECT_TRUE(
  23376. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  23377. EXPECT_TRUE(
  23378. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  23379. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  23380. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  23381. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  23382. EXPECT_FALSE(
  23383. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  23384. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  23385. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23386. }
  23387. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  23388. Server svr;
  23389. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  23390. auto port = svr.bind_to_any_port("localhost");
  23391. std::thread t([&]() { svr.listen_after_bind(); });
  23392. auto se = detail::scope_exit([&] {
  23393. svr.stop();
  23394. t.join();
  23395. });
  23396. svr.wait_until_ready();
  23397. Headers headers = {{"Upgrade", "websocket"},
  23398. {"Connection", "notupgrade"},
  23399. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23400. {"Sec-WebSocket-Version", "13"}};
  23401. Client cli("localhost", port);
  23402. auto res = cli.Get("/ws", headers);
  23403. // The route exists only as a WebSocket route, so a request that fails the
  23404. // handshake check falls through to ordinary routing.
  23405. ASSERT_TRUE(res);
  23406. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23407. }
  23408. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  23409. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  23410. // Connection value is the only thing left for the client to reject.
  23411. Server svr;
  23412. svr.Get("/ws", [](const Request &req, Response &res) {
  23413. res.status = StatusCode::SwitchingProtocol_101;
  23414. res.set_header("Upgrade", "websocket");
  23415. res.set_header("Connection", "notupgrade");
  23416. res.set_header("Sec-WebSocket-Accept",
  23417. detail::websocket_accept_key(
  23418. req.get_header_value("Sec-WebSocket-Key")));
  23419. });
  23420. auto port = svr.bind_to_any_port("localhost");
  23421. std::thread t([&]() { svr.listen_after_bind(); });
  23422. auto se = detail::scope_exit([&] {
  23423. svr.stop();
  23424. t.join();
  23425. });
  23426. svr.wait_until_ready();
  23427. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23428. auto res = client.connect();
  23429. EXPECT_FALSE(res);
  23430. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23431. EXPECT_FALSE(client.is_open());
  23432. }
  23433. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  23434. Server svr;
  23435. svr.Get("/ws", [](const Request &req, Response &res) {
  23436. res.status = StatusCode::SwitchingProtocol_101;
  23437. res.set_header("Upgrade", "websocket");
  23438. res.set_header("Connection", "Upgrade");
  23439. res.set_header("Sec-WebSocket-Accept",
  23440. detail::websocket_accept_key(
  23441. req.get_header_value("Sec-WebSocket-Key")));
  23442. res.set_header("Sec-WebSocket-Protocol", "admin");
  23443. });
  23444. auto port = svr.bind_to_any_port("localhost");
  23445. std::thread t([&]() { svr.listen_after_bind(); });
  23446. auto se = detail::scope_exit([&] {
  23447. svr.stop();
  23448. t.join();
  23449. });
  23450. svr.wait_until_ready();
  23451. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  23452. // Server selects a subprotocol the client never offered
  23453. {
  23454. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23455. ws::WebSocketClient client(url, headers);
  23456. auto res = client.connect();
  23457. EXPECT_FALSE(res);
  23458. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23459. EXPECT_FALSE(client.is_open());
  23460. EXPECT_TRUE(client.subprotocol().empty());
  23461. }
  23462. // Client offered none but the server named one anyway
  23463. {
  23464. ws::WebSocketClient client(url);
  23465. auto res = client.connect();
  23466. EXPECT_FALSE(res);
  23467. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23468. EXPECT_FALSE(client.is_open());
  23469. EXPECT_TRUE(client.subprotocol().empty());
  23470. }
  23471. }
  23472. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  23473. // The socket path doubles as the URL host, so it must not contain '/'.
  23474. const char *shard = getenv("GTEST_SHARD_INDEX");
  23475. const std::string sock_path =
  23476. shard ? std::string("httplib-ws-") + shard + ".sock"
  23477. : std::string("httplib-ws.sock");
  23478. std::remove(sock_path.c_str());
  23479. Server svr;
  23480. std::mutex mtx;
  23481. std::string received_host;
  23482. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23483. {
  23484. std::lock_guard<std::mutex> lock(mtx);
  23485. received_host = req.get_header_value("Host");
  23486. }
  23487. std::string msg;
  23488. while (ws.read(msg)) {
  23489. ws.send(msg);
  23490. }
  23491. });
  23492. svr.set_address_family(AF_UNIX);
  23493. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  23494. auto se = detail::scope_exit([&] {
  23495. svr.stop();
  23496. t.join();
  23497. std::remove(sock_path.c_str());
  23498. });
  23499. svr.wait_until_ready();
  23500. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  23501. client.set_address_family(AF_UNIX);
  23502. ASSERT_TRUE(client.connect());
  23503. ASSERT_TRUE(client.send("hello"));
  23504. std::string msg;
  23505. ASSERT_TRUE(client.read(msg));
  23506. client.close();
  23507. {
  23508. std::lock_guard<std::mutex> lock(mtx);
  23509. // There is no host:port for a Unix socket, so the same "localhost"
  23510. // placeholder the HTTP client uses is expected.
  23511. EXPECT_EQ("localhost", received_host);
  23512. }
  23513. }
  23514. // Two threads must never parse WebSocket frames from the same stream.
  23515. // close() used to read the peer's Close reply with its own frame read, so it
  23516. // raced a reader thread that was in the middle of a payload: the payload loop
  23517. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  23518. // so bytes taken by close() were replaced with bytes from further along the
  23519. // stream. The message kept its length and silently changed content.
  23520. //
  23521. // The raw peer below sends a frame header plus part of the payload, waits for
  23522. // the handler to call close(), and only then sends the rest. Whichever thread
  23523. // would win the race for those bytes, the message must arrive intact, because
  23524. // close() must not touch the stream while read() owns it.
  23525. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  23526. #ifndef _WIN32
  23527. signal(SIGPIPE, SIG_IGN);
  23528. #endif
  23529. const size_t payload_len = 120; // fits the 7-bit length field
  23530. const size_t prefix_len = 8;
  23531. const int attempts = 8;
  23532. std::string expected(payload_len, '\0');
  23533. for (size_t i = 0; i < payload_len; i++) {
  23534. expected[i] = static_cast<char>('a' + i % 26);
  23535. }
  23536. std::atomic<bool> peer_stalled{false};
  23537. std::atomic<bool> handler_done{false};
  23538. std::mutex received_mutex;
  23539. std::vector<std::string> received;
  23540. // Bound every wait, so a regression fails the test instead of hanging the
  23541. // suite.
  23542. auto wait_for = [](const std::atomic<bool> &flag) {
  23543. for (int i = 0; i < 500 && !flag; i++) {
  23544. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23545. }
  23546. };
  23547. Server svr;
  23548. svr.set_websocket_ping_interval(0);
  23549. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23550. std::thread reader([&]() {
  23551. std::string msg;
  23552. while (ws.read(msg)) {
  23553. std::lock_guard<std::mutex> guard(received_mutex);
  23554. received.push_back(msg);
  23555. }
  23556. });
  23557. // Wait until the peer stalls mid-payload, so the reader thread is parked
  23558. // inside read_websocket_frame() when close() runs.
  23559. wait_for(peer_stalled);
  23560. ws.close();
  23561. reader.join();
  23562. handler_done = true;
  23563. });
  23564. auto port = svr.bind_to_any_port("127.0.0.1");
  23565. std::thread t([&]() { svr.listen_after_bind(); });
  23566. auto se = detail::scope_exit([&] {
  23567. svr.stop();
  23568. t.join();
  23569. });
  23570. svr.wait_until_ready();
  23571. auto send_bytes = [](socket_t s, const std::string &data) {
  23572. #ifdef _WIN32
  23573. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  23574. #else
  23575. auto n = ::send(s, data.data(), data.size(), 0);
  23576. #endif
  23577. return n == static_cast<decltype(n)>(data.size());
  23578. };
  23579. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  23580. // Every length used here fits the 7-bit length field.
  23581. auto masked_header = [](uint8_t first_byte, size_t len) {
  23582. std::string h;
  23583. h += static_cast<char>(first_byte);
  23584. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  23585. h.append(4, '\0'); // mask key
  23586. return h;
  23587. };
  23588. for (int attempt = 0; attempt < attempts; attempt++) {
  23589. peer_stalled = false;
  23590. handler_done = false;
  23591. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23592. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  23593. auto se_sock = detail::scope_exit([&] {
  23594. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  23595. });
  23596. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23597. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  23598. sockaddr_in addr{};
  23599. addr.sin_family = AF_INET;
  23600. addr.sin_port = htons(static_cast<uint16_t>(port));
  23601. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23602. ASSERT_EQ(
  23603. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  23604. << "attempt " << attempt;
  23605. ASSERT_TRUE(send_bytes(sock,
  23606. "GET /ws HTTP/1.1\r\n"
  23607. "Host: 127.0.0.1\r\n"
  23608. "Upgrade: websocket\r\n"
  23609. "Connection: Upgrade\r\n"
  23610. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23611. "Sec-WebSocket-Version: 13\r\n"
  23612. "\r\n"))
  23613. << "attempt " << attempt;
  23614. std::string response;
  23615. while (response.find("\r\n\r\n") == std::string::npos) {
  23616. char buf[512];
  23617. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  23618. if (n <= 0) { break; }
  23619. response.append(buf, static_cast<size_t>(n));
  23620. }
  23621. ASSERT_NE(std::string::npos, response.find(" 101 "))
  23622. << "attempt " << attempt;
  23623. // Send the header of a Binary message but only the first prefix_len bytes
  23624. // of its payload, leaving the reader thread stalled inside the payload.
  23625. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  23626. expected.substr(0, prefix_len)))
  23627. << "attempt " << attempt;
  23628. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23629. peer_stalled = true;
  23630. // Let close() send its Close frame and park in its own read before the
  23631. // rest of the payload arrives, so both threads are waiting for it.
  23632. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23633. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  23634. close_frame += static_cast<char>(0x03); // status 1000
  23635. close_frame += static_cast<char>(0xE8);
  23636. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  23637. << "attempt " << attempt;
  23638. // Closing the peer releases the reader thread even on the buggy path,
  23639. // where it waits for bytes another thread already consumed.
  23640. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23641. detail::close_socket(sock);
  23642. sock = INVALID_SOCKET;
  23643. wait_for(handler_done);
  23644. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  23645. }
  23646. std::lock_guard<std::mutex> guard(received_mutex);
  23647. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  23648. << "a message in flight when close() ran was dropped";
  23649. for (size_t i = 0; i < received.size(); i++) {
  23650. EXPECT_EQ(expected, received[i]) << "message " << i;
  23651. }
  23652. }
  23653. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  23654. // returning the socket, or INVALID_SOCKET.
  23655. static socket_t connect_raw_websocket(int port, const std::string &path) {
  23656. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23657. if (sock == INVALID_SOCKET) { return sock; }
  23658. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23659. sockaddr_in addr{};
  23660. addr.sin_family = AF_INET;
  23661. addr.sin_port = htons(static_cast<uint16_t>(port));
  23662. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23663. std::string req = "GET " + path +
  23664. " HTTP/1.1\r\n"
  23665. "Host: 127.0.0.1\r\n"
  23666. "Upgrade: websocket\r\n"
  23667. "Connection: Upgrade\r\n"
  23668. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23669. "Sec-WebSocket-Version: 13\r\n"
  23670. "\r\n";
  23671. std::string res;
  23672. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  23673. ::send(sock, req.data(), static_cast<int>(req.size()), 0) ==
  23674. static_cast<int>(req.size())) {
  23675. char c;
  23676. while (res.find("\r\n\r\n") == std::string::npos &&
  23677. ::recv(sock, &c, 1, 0) == 1) {
  23678. res += c;
  23679. }
  23680. }
  23681. if (res.find(" 101 ") == std::string::npos) {
  23682. detail::close_socket(sock);
  23683. return INVALID_SOCKET;
  23684. }
  23685. return sock;
  23686. }
  23687. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  23688. // The payload must fit the 7-bit length field.
  23689. static std::string masked_frame(uint8_t first_byte,
  23690. const std::string &payload) {
  23691. std::string f;
  23692. f += static_cast<char>(first_byte);
  23693. f += static_cast<char>(0x80 | payload.size());
  23694. f.append(4, '\0');
  23695. return f + payload;
  23696. }
  23697. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  23698. std::atomic<bool> done{false};
  23699. std::string received;
  23700. Server svr;
  23701. svr.set_websocket_ping_interval(0);
  23702. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23703. std::string msg;
  23704. if (ws.read(msg) == ws::Binary) { received = msg; }
  23705. done = true;
  23706. });
  23707. auto port = svr.bind_to_any_port("127.0.0.1");
  23708. std::thread t([&]() { svr.listen_after_bind(); });
  23709. auto se = detail::scope_exit([&] {
  23710. svr.stop();
  23711. t.join();
  23712. });
  23713. svr.wait_until_ready();
  23714. auto sock = connect_raw_websocket(port, "/ws");
  23715. ASSERT_NE(INVALID_SOCKET, sock);
  23716. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23717. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  23718. masked_frame(0x89, "p") + // FIN + Ping
  23719. masked_frame(0x80, "lo"); // FIN + Continuation
  23720. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23721. for (int i = 0; i < 500 && !done; i++) {
  23722. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23723. }
  23724. ASSERT_TRUE(done);
  23725. EXPECT_EQ("Hello", received);
  23726. // The Ping between the fragments is answered with a Pong.
  23727. char pong[3];
  23728. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  23729. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  23730. }
  23731. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  23732. Server svr;
  23733. svr.set_websocket_ping_interval(-1);
  23734. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23735. std::string msg;
  23736. while (ws.read(msg)) {}
  23737. });
  23738. auto port = svr.bind_to_any_port("127.0.0.1");
  23739. std::thread t([&]() { svr.listen_after_bind(); });
  23740. auto se = detail::scope_exit([&] {
  23741. svr.stop();
  23742. t.join();
  23743. });
  23744. svr.wait_until_ready();
  23745. auto sock = connect_raw_websocket(port, "/ws");
  23746. ASSERT_NE(INVALID_SOCKET, sock);
  23747. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23748. // Nothing comes while the client stays quiet.
  23749. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  23750. char c;
  23751. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  23752. }
  23753. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  23754. Server svr;
  23755. svr.set_websocket_ping_interval(0);
  23756. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23757. std::string msg;
  23758. while (ws.read(msg)) {}
  23759. });
  23760. auto port = svr.bind_to_any_port("127.0.0.1");
  23761. std::thread t([&]() { svr.listen_after_bind(); });
  23762. auto se = detail::scope_exit([&] {
  23763. svr.stop();
  23764. t.join();
  23765. });
  23766. svr.wait_until_ready();
  23767. // Each Close payload and the reply it should get: an echo when valid, 1002
  23768. // otherwise.
  23769. std::vector<std::pair<std::string, std::string>> cases = {
  23770. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  23771. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  23772. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  23773. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  23774. };
  23775. // Also between the fragments of a message.
  23776. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  23777. for (const auto &c : cases) {
  23778. auto sock = connect_raw_websocket(port, "/ws");
  23779. ASSERT_NE(INVALID_SOCKET, sock);
  23780. auto frames = prefix + masked_frame(0x88, c.first);
  23781. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23782. std::string reply;
  23783. char buf[256];
  23784. while (reply.size() < 2 + c.second.size()) {
  23785. auto n = ::recv(sock, buf, sizeof(buf), 0);
  23786. if (n <= 0) { break; }
  23787. reply.append(buf, static_cast<size_t>(n));
  23788. }
  23789. detail::close_socket(sock);
  23790. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  23791. c.second,
  23792. reply);
  23793. }
  23794. }
  23795. }
  23796. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23797. class WebSocketSSLIntegrationTest : public ::testing::Test {
  23798. protected:
  23799. void SetUp() override {
  23800. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  23801. SERVER_PRIVATE_KEY_FILE);
  23802. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23803. std::string msg;
  23804. ws::ReadResult ret;
  23805. while ((ret = ws.read(msg))) {
  23806. if (ret == ws::Binary) {
  23807. ws.send(msg.data(), msg.size());
  23808. } else {
  23809. ws.send(msg);
  23810. }
  23811. }
  23812. });
  23813. port_ = server_->bind_to_any_port(HOST);
  23814. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23815. server_->wait_until_ready();
  23816. }
  23817. void TearDown() override {
  23818. server_->stop();
  23819. if (server_thread_.joinable()) { server_thread_.join(); }
  23820. }
  23821. std::unique_ptr<SSLServer> server_;
  23822. std::thread server_thread_;
  23823. int port_ = 0;
  23824. };
  23825. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  23826. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23827. {
  23828. ws::WebSocketClient client(url);
  23829. client.enable_server_certificate_verification(false);
  23830. auto calls = 0;
  23831. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  23832. calls++;
  23833. return false;
  23834. });
  23835. EXPECT_FALSE(client.connect());
  23836. EXPECT_GT(calls, 0);
  23837. }
  23838. {
  23839. ws::WebSocketClient client(url);
  23840. client.enable_server_certificate_verification(false);
  23841. client.set_session_verifier([](tls::session_t) {
  23842. return SSLVerifierResponse::CertificateRejected;
  23843. });
  23844. EXPECT_FALSE(client.connect());
  23845. }
  23846. {
  23847. ws::WebSocketClient client(url);
  23848. client.enable_server_certificate_verification(false);
  23849. client.set_session_verifier([](tls::session_t) {
  23850. return SSLVerifierResponse::CertificateAccepted;
  23851. });
  23852. EXPECT_TRUE(client.connect());
  23853. }
  23854. }
  23855. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  23856. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23857. "/ws-echo");
  23858. client.enable_server_certificate_verification(false);
  23859. ASSERT_TRUE(client.connect());
  23860. ASSERT_TRUE(client.is_open());
  23861. ASSERT_TRUE(client.send("Hello WSS"));
  23862. std::string msg;
  23863. EXPECT_EQ(ws::Text, client.read(msg));
  23864. EXPECT_EQ("Hello WSS", msg);
  23865. client.close();
  23866. }
  23867. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  23868. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  23869. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  23870. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  23871. // client (without calling close() first) is the only path that runs
  23872. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  23873. // bug exactly.
  23874. //
  23875. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  23876. // when linked against an instrumented libssl; run under Valgrind to catch it
  23877. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  23878. // suite (the freed session otherwise stalls on the close handshake) — this test
  23879. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  23880. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  23881. {
  23882. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23883. "/ws-echo");
  23884. client.enable_server_certificate_verification(false);
  23885. client.set_read_timeout(2, 0);
  23886. client.set_write_timeout(2, 0);
  23887. ASSERT_TRUE(client.connect());
  23888. ASSERT_TRUE(client.is_open());
  23889. ASSERT_TRUE(client.send("still open"));
  23890. // Intentionally do NOT call client.close(): leaving scope runs
  23891. // shutdown_and_close() with the WebSocket still open, which must send the
  23892. // close frame while the TLS session is still alive.
  23893. }
  23894. }
  23895. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  23896. // shutdown_and_close() at the start of connect(), reproducing the same
  23897. // use-after-free within the test body rather than at scope exit. The second
  23898. // connect must succeed and echo, proving the close handshake ran over a live
  23899. // session. See the note above about memory-tool requirements.
  23900. TEST_F(WebSocketSSLIntegrationTest,
  23901. ReconnectWhileOpenSendsCloseOverLiveSession) {
  23902. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23903. "/ws-echo");
  23904. client.enable_server_certificate_verification(false);
  23905. client.set_read_timeout(2, 0);
  23906. client.set_write_timeout(2, 0);
  23907. ASSERT_TRUE(client.connect());
  23908. ASSERT_TRUE(client.is_open());
  23909. ASSERT_TRUE(client.send("still open"));
  23910. // Reconnect without closing first: connect() calls shutdown_and_close() on
  23911. // the still-open connection, which must not touch a freed TLS session.
  23912. ASSERT_TRUE(client.connect());
  23913. ASSERT_TRUE(client.is_open());
  23914. ASSERT_TRUE(client.send("after reconnect"));
  23915. std::string msg;
  23916. EXPECT_EQ(ws::Text, client.read(msg));
  23917. EXPECT_EQ("after reconnect", msg);
  23918. client.close();
  23919. }
  23920. #endif
  23921. #ifdef CPPHTTPLIB_SSL_ENABLED
  23922. class WebSocketSSLCATest : public ::testing::Test {
  23923. protected:
  23924. void SetUp() override {
  23925. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  23926. SERVER_PRIVATE_KEY_FILE);
  23927. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23928. std::string msg;
  23929. while (ws.read(msg)) {
  23930. ws.send(msg);
  23931. }
  23932. });
  23933. port_ = server_->bind_to_any_port("127.0.0.1");
  23934. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23935. server_->wait_until_ready();
  23936. }
  23937. void TearDown() override {
  23938. server_->stop();
  23939. if (server_thread_.joinable()) { server_thread_.join(); }
  23940. }
  23941. std::string url() const {
  23942. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  23943. }
  23944. std::unique_ptr<SSLServer> server_;
  23945. std::thread server_thread_;
  23946. int port_ = 0;
  23947. };
  23948. // A custom CA loaded as PEM verifies the server with full certificate
  23949. // verification enabled
  23950. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  23951. ws::WebSocketClient client(url());
  23952. std::string cert;
  23953. read_file(SERVER_CERT2_FILE, cert);
  23954. client.load_ca_cert_store(cert.c_str(), cert.size());
  23955. ASSERT_TRUE(client.connect());
  23956. ASSERT_TRUE(client.send("hello"));
  23957. std::string msg;
  23958. EXPECT_EQ(ws::Text, client.read(msg));
  23959. EXPECT_EQ("hello", msg);
  23960. client.close();
  23961. }
  23962. // A custom CA that does not cover the server must fail verification (the
  23963. // custom CA is exclusive; system certs are not loaded alongside it)
  23964. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  23965. ws::WebSocketClient client(url());
  23966. std::string cert;
  23967. read_file(CLIENT_CA_CERT_FILE, cert);
  23968. client.load_ca_cert_store(cert.c_str(), cert.size());
  23969. auto res = client.connect();
  23970. ASSERT_FALSE(res);
  23971. EXPECT_EQ(Error::SSLServerVerification, res.error());
  23972. EXPECT_EQ(-1, res.status());
  23973. EXPECT_NE(0u, res.ssl_backend_error());
  23974. }
  23975. // The same CA as a file path rather than PEM in memory
  23976. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  23977. ws::WebSocketClient client(url());
  23978. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23979. ASSERT_TRUE(client.connect());
  23980. ASSERT_TRUE(client.send("hello"));
  23981. std::string msg;
  23982. EXPECT_EQ(ws::Text, client.read(msg));
  23983. EXPECT_EQ("hello", msg);
  23984. client.close();
  23985. }
  23986. // ...and a CA file that does not cover the server still fails, so it is the
  23987. // path above that decides the outcome
  23988. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  23989. ws::WebSocketClient client(url());
  23990. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23991. ASSERT_FALSE(client.connect());
  23992. }
  23993. // Regression test: reconnecting with a native custom CA store used to reuse
  23994. // a store handle the previous TLS context had already freed (use-after-free
  23995. // under the OpenSSL backend). The context now lives as long as the client.
  23996. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  23997. ws::WebSocketClient client(url());
  23998. std::string cert;
  23999. read_file(SERVER_CERT2_FILE, cert);
  24000. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  24001. ASSERT_TRUE(client.connect());
  24002. client.close();
  24003. ASSERT_TRUE(client.connect());
  24004. ASSERT_TRUE(client.send("again"));
  24005. std::string msg;
  24006. EXPECT_EQ(ws::Text, client.read(msg));
  24007. EXPECT_EQ("again", msg);
  24008. client.close();
  24009. }
  24010. // Regression test: a certificate with a trusted chain but no identity match
  24011. // for the server IP must be rejected. The Mbed TLS backend used to skip
  24012. // verification entirely for IP hosts, so this connection succeeded there.
  24013. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  24014. // chain verification while the identity check must still fail.
  24015. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  24016. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24017. ASSERT_TRUE(svr.is_valid());
  24018. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24019. std::string msg;
  24020. while (ws.read(msg)) {
  24021. ws.send(msg);
  24022. }
  24023. });
  24024. auto port = svr.bind_to_any_port("127.0.0.1");
  24025. auto t = std::thread([&]() { svr.listen_after_bind(); });
  24026. auto se = detail::scope_exit([&] {
  24027. svr.stop();
  24028. t.join();
  24029. });
  24030. svr.wait_until_ready();
  24031. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  24032. "/echo");
  24033. std::string cert;
  24034. read_file(SERVER_CERT_FILE, cert);
  24035. client.load_ca_cert_store(cert.c_str(), cert.size());
  24036. ASSERT_FALSE(client.connect());
  24037. }
  24038. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  24039. // SNI, so nothing binds the host name to the TLS session. These bind the
  24040. // server to "localhost" instead, the only shape that exercises the SNI and
  24041. // hostname-verification path with certificate verification left enabled.
  24042. class WebSocketSSLDnsHostTest : public ::testing::Test {
  24043. protected:
  24044. void Start(const char *cert_file) {
  24045. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  24046. SERVER_PRIVATE_KEY_FILE);
  24047. ASSERT_TRUE(server_->is_valid());
  24048. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24049. std::string msg;
  24050. while (ws.read(msg)) {
  24051. ws.send(msg);
  24052. }
  24053. });
  24054. port_ = server_->bind_to_any_port("localhost");
  24055. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24056. server_->wait_until_ready();
  24057. }
  24058. void TearDown() override {
  24059. if (server_) { server_->stop(); }
  24060. if (server_thread_.joinable()) { server_thread_.join(); }
  24061. }
  24062. std::string url() const {
  24063. return "wss://localhost:" + std::to_string(port_) + "/echo";
  24064. }
  24065. std::unique_ptr<SSLServer> server_;
  24066. std::thread server_thread_;
  24067. int port_ = 0;
  24068. };
  24069. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  24070. // out and the connection is usable
  24071. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  24072. Start(SERVER_CERT2_FILE);
  24073. ws::WebSocketClient client(url());
  24074. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24075. ASSERT_TRUE(client.connect());
  24076. ASSERT_TRUE(client.send("hello"));
  24077. std::string msg;
  24078. EXPECT_EQ(ws::Text, client.read(msg));
  24079. EXPECT_EQ("hello", msg);
  24080. client.close();
  24081. }
  24082. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  24083. // while the identity check must still reject "localhost"
  24084. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  24085. Start(SERVER_CERT_FILE);
  24086. ws::WebSocketClient client(url());
  24087. client.set_ca_cert_path(SERVER_CERT_FILE);
  24088. auto res = client.connect();
  24089. ASSERT_FALSE(res);
  24090. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  24091. EXPECT_EQ(-1, res.status());
  24092. }
  24093. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  24094. // disabled: the chain is still checked, only the identity check is skipped
  24095. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  24096. Start(SERVER_CERT_FILE);
  24097. ws::WebSocketClient client(url());
  24098. client.set_ca_cert_path(SERVER_CERT_FILE);
  24099. client.enable_server_hostname_verification(false);
  24100. ASSERT_TRUE(client.connect());
  24101. ASSERT_TRUE(client.send("hello"));
  24102. std::string msg;
  24103. EXPECT_EQ(ws::Text, client.read(msg));
  24104. EXPECT_EQ("hello", msg);
  24105. client.close();
  24106. }
  24107. // A CA that did not sign the server certificate fails the chain, even though
  24108. // the name would match
  24109. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  24110. Start(SERVER_CERT2_FILE);
  24111. ws::WebSocketClient client(url());
  24112. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24113. ASSERT_FALSE(client.connect());
  24114. }
  24115. // With verification disabled, neither the chain nor the name is checked
  24116. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  24117. Start(SERVER_CERT_FILE);
  24118. ws::WebSocketClient client(url());
  24119. client.enable_server_certificate_verification(false);
  24120. ASSERT_TRUE(client.connect());
  24121. ASSERT_TRUE(client.send("hello"));
  24122. std::string msg;
  24123. EXPECT_EQ(ws::Text, client.read(msg));
  24124. EXPECT_EQ("hello", msg);
  24125. client.close();
  24126. }
  24127. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  24128. protected:
  24129. void SetUp() override {
  24130. server_ = httplib::detail::make_unique<SSLServer>(
  24131. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24132. ASSERT_TRUE(server_->is_valid());
  24133. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24134. std::string msg;
  24135. while (ws.read(msg)) {
  24136. ws.send(msg);
  24137. }
  24138. });
  24139. port_ = server_->bind_to_any_port("localhost");
  24140. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24141. server_->wait_until_ready();
  24142. }
  24143. void TearDown() override {
  24144. server_->stop();
  24145. if (server_thread_.joinable()) { server_thread_.join(); }
  24146. }
  24147. std::string url() const {
  24148. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24149. }
  24150. void ConnectWithClientCert(const std::string &client_cert_file,
  24151. const std::string &client_private_key_file,
  24152. const char *private_key_password) {
  24153. std::string cert_pem, key_pem;
  24154. read_file(client_cert_file, cert_pem);
  24155. read_file(client_private_key_file, key_pem);
  24156. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  24157. key_pem.c_str(), key_pem.size(),
  24158. private_key_password};
  24159. ws::WebSocketClient client(url(), pem);
  24160. ASSERT_TRUE(client.is_valid());
  24161. client.enable_server_certificate_verification(false);
  24162. ASSERT_TRUE(client.connect());
  24163. ASSERT_TRUE(client.send("hello"));
  24164. std::string msg;
  24165. EXPECT_EQ(ws::Text, client.read(msg));
  24166. EXPECT_EQ("hello", msg);
  24167. client.close();
  24168. }
  24169. std::unique_ptr<SSLServer> server_;
  24170. std::thread server_thread_;
  24171. int port_ = 0;
  24172. };
  24173. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  24174. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  24175. }
  24176. // Control for the tests above: the fixture's server really does require a
  24177. // client certificate, so it is the PEM the constructor installed that decides
  24178. // the outcome.
  24179. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  24180. ws::WebSocketClient client(url());
  24181. ASSERT_TRUE(client.is_valid());
  24182. client.enable_server_certificate_verification(false);
  24183. EXPECT_FALSE(client.connect());
  24184. }
  24185. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  24186. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  24187. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  24188. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  24189. }
  24190. #endif
  24191. #if !defined(_WIN32)
  24192. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  24193. auto secret_dir = std::string("./symlink_test_secret");
  24194. auto served_dir = std::string("./symlink_test_served");
  24195. auto secret_file = secret_dir + "/secret.txt";
  24196. auto symlink_path = served_dir + "/escape";
  24197. // Setup: create directories and files
  24198. mkdir(secret_dir.c_str(), 0755);
  24199. mkdir(served_dir.c_str(), 0755);
  24200. {
  24201. std::ofstream ofs(secret_file);
  24202. ofs << "SECRET_DATA";
  24203. }
  24204. // Create symlink using absolute path so it resolves correctly
  24205. #ifdef PATH_MAX
  24206. char abs_secret[PATH_MAX];
  24207. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  24208. #else
  24209. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  24210. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  24211. ASSERT_NE(nullptr, abs_secret);
  24212. #endif
  24213. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  24214. auto se = detail::scope_exit([&] {
  24215. unlink(symlink_path.c_str());
  24216. unlink(secret_file.c_str());
  24217. rmdir(served_dir.c_str());
  24218. rmdir(secret_dir.c_str());
  24219. });
  24220. Server svr;
  24221. svr.set_mount_point("/", served_dir);
  24222. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  24223. auto se2 = detail::scope_exit([&] {
  24224. svr.stop();
  24225. listen_thread.join();
  24226. });
  24227. svr.wait_until_ready();
  24228. Client cli("localhost", PORT);
  24229. // Symlink pointing outside base dir should be blocked
  24230. auto res = cli.Get("/escape/secret.txt");
  24231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24232. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  24233. }
  24234. #endif
  24235. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  24236. // "GET /smuggled" request), reads the first response, and only then sends the
  24237. // embedded request as the body. Returns how many times /smuggled ran.
  24238. //
  24239. // The body is sent AFTER receiving the first response (as in the original
  24240. // PoC) so that the stream_line_reader cannot buffer it together with the
  24241. // headers of the first request.
  24242. static int count_smuggled_requests(const std::string &outer_head,
  24243. std::string &first_response) {
  24244. Server svr;
  24245. svr.set_mount_point("/", "./www");
  24246. std::atomic<int> smuggled_count(0);
  24247. svr.Get("/smuggled", [&](const Request &, Response &res) {
  24248. smuggled_count++;
  24249. res.set_content("oops", "text/plain");
  24250. });
  24251. svr.Post("/post", [&](const Request &req, Response &res) {
  24252. res.set_content(req.body, "text/plain");
  24253. });
  24254. auto port = svr.bind_to_any_port("localhost");
  24255. thread t = thread([&] { svr.listen_after_bind(); });
  24256. auto se = detail::scope_exit([&] {
  24257. svr.stop();
  24258. t.join();
  24259. });
  24260. svr.wait_until_ready();
  24261. auto error = Error::Success;
  24262. auto sock = detail::create_client_socket(
  24263. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  24264. /*connection_timeout_sec=*/2, 0,
  24265. /*read_timeout_sec=*/2, 0,
  24266. /*write_timeout_sec=*/2, 0, std::string(), error);
  24267. EXPECT_NE(INVALID_SOCKET, sock);
  24268. if (sock == INVALID_SOCKET) { return -1; }
  24269. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24270. // The "smuggled" request will be sent as the body of the outer request
  24271. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  24272. "Host: localhost\r\n"
  24273. "Connection: close\r\n"
  24274. "\r\n";
  24275. auto head = outer_head;
  24276. auto len = std::to_string(smuggled.size());
  24277. for (auto pos = head.find("{len}"); pos != std::string::npos;
  24278. pos = head.find("{len}", pos + len.size())) {
  24279. head.replace(pos, 5, len);
  24280. }
  24281. // Step 1: Send only the outer request headers (no body yet)
  24282. auto sent = send(sock, head.data(), head.size(), 0);
  24283. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  24284. // Step 2: Read the first response
  24285. char buf[4096];
  24286. for (;;) {
  24287. auto n = recv(sock, buf, sizeof(buf), 0);
  24288. if (n <= 0) break;
  24289. first_response.append(buf, static_cast<size_t>(n));
  24290. // Stop once we have a complete response (headers + body)
  24291. auto hdr_end = first_response.find("\r\n\r\n");
  24292. if (hdr_end != std::string::npos) {
  24293. // Check for Content-Length to know when the body is complete
  24294. auto cl_pos = first_response.find("Content-Length:");
  24295. if (cl_pos != std::string::npos) {
  24296. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  24297. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  24298. auto cl = std::stoul(
  24299. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  24300. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  24301. } else {
  24302. break; // No Content-Length, assume headers-only response
  24303. }
  24304. }
  24305. }
  24306. // Step 3: Now send the body, which looks like a new HTTP request. On a
  24307. // vulnerable server the keep-alive loop reads this as a second request. The
  24308. // server may already have closed the connection, so the result is ignored.
  24309. send(sock, smuggled.data(), smuggled.size(), 0);
  24310. // Half-close so that a server which drained the body sees EOF and closes,
  24311. // instead of the read below waiting for the read timeout.
  24312. #ifdef _WIN32
  24313. ::shutdown(sock, SD_SEND);
  24314. #else
  24315. ::shutdown(sock, SHUT_WR);
  24316. #endif
  24317. // Step 4: Read until the server closes the connection
  24318. for (;;) {
  24319. auto n = recv(sock, buf, sizeof(buf), 0);
  24320. if (n <= 0) break;
  24321. }
  24322. return smuggled_count.load();
  24323. }
  24324. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  24325. // A GET request with Content-Length to a static file handler must have its
  24326. // body drained before the keep-alive connection is reused. Otherwise the
  24327. // unread body bytes are interpreted as the next HTTP request.
  24328. std::string first_response;
  24329. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  24330. "Host: localhost\r\n"
  24331. "Content-Length: {len}\r\n"
  24332. "\r\n",
  24333. first_response));
  24334. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  24335. }
  24336. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  24337. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  24338. // be answered with 400 and the connection closed. Treating it as "no body"
  24339. // leaves the body to be parsed as the next request.
  24340. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  24341. const char *targets[] = {
  24342. "GET /file", // handler that never reads the body
  24343. "GET /not-found", // no handler matches (404)
  24344. "POST /post", // handler that reads the body
  24345. };
  24346. for (auto target : targets) {
  24347. for (auto value : values) {
  24348. std::string first_response;
  24349. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  24350. " HTTP/1.1\r\n"
  24351. "Host: localhost\r\n"
  24352. "Content-Length: " +
  24353. value + "\r\n\r\n",
  24354. first_response))
  24355. << target << " with Content-Length: " << value;
  24356. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  24357. << target << " with Content-Length: " << value;
  24358. }
  24359. }
  24360. }
  24361. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  24362. // A 400 for an unparseable request line leaves the rest of the message
  24363. // unread, so the connection must be closed rather than reused.
  24364. std::string first_response;
  24365. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  24366. "Host: localhost\r\n"
  24367. "Content-Length: {len}\r\n"
  24368. "\r\n",
  24369. first_response));
  24370. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  24371. }
  24372. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  24373. // Same as above for a header block that fails to parse.
  24374. std::string first_response;
  24375. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  24376. "Host: localhost\r\n"
  24377. "Bad Header\r\n"
  24378. "Content-Length: {len}\r\n"
  24379. "\r\n",
  24380. first_response));
  24381. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  24382. }
  24383. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  24384. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  24385. // server must not read another request on that connection, even when the
  24386. // request had no body to drain.
  24387. std::string first_response;
  24388. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  24389. "Host: localhost\r\n"
  24390. "\r\n",
  24391. first_response));
  24392. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  24393. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  24394. }
  24395. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  24396. // A content reader that stops early leaves the stream inside the body.
  24397. // Draining the whole Content-Length from there, or reading the body again,
  24398. // reads into the next request, and whatever follows is parsed as a request
  24399. // of its own.
  24400. Server svr;
  24401. std::atomic<int> smuggled_count(0);
  24402. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  24403. svr.Post("/upload", [](const Request &req, Response &res,
  24404. const ContentReader &content_reader) {
  24405. // Stop at the last chunk, so the whole body has been read however it
  24406. // arrives.
  24407. auto length = req.get_header_value_u64("Content-Length");
  24408. size_t total = 0;
  24409. auto consumed = content_reader([&](const char *, size_t n) {
  24410. total += n;
  24411. return total < length;
  24412. });
  24413. EXPECT_FALSE(consumed);
  24414. if (req.has_param("retry")) {
  24415. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  24416. }
  24417. // Replace the 400 the aborted read set, which would close the connection.
  24418. res.set_redirect("/done");
  24419. });
  24420. auto port = svr.bind_to_any_port(HOST);
  24421. thread t = thread([&] { svr.listen_after_bind(); });
  24422. auto se = detail::scope_exit([&] {
  24423. svr.stop();
  24424. t.join();
  24425. });
  24426. svr.wait_until_ready();
  24427. // A front end sees the second request as a POST whose body is the GET. The
  24428. // first body is as long as the POST's headers, so draining it again reads
  24429. // exactly those and leaves the GET to be parsed next.
  24430. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  24431. "Host: localhost\r\n"
  24432. "\r\n";
  24433. std::string second_head = "POST /post HTTP/1.1\r\n"
  24434. "Host: localhost\r\n"
  24435. "Content-Length: " +
  24436. std::to_string(inner.size()) +
  24437. "\r\n"
  24438. "\r\n";
  24439. for (auto target : {"/upload", "/upload?retry"}) {
  24440. smuggled_count = 0;
  24441. std::string request = "POST " + std::string(target) +
  24442. " HTTP/1.1\r\n"
  24443. "Host: localhost\r\n"
  24444. "Content-Length: " +
  24445. std::to_string(second_head.size()) +
  24446. "\r\n"
  24447. "\r\n" +
  24448. std::string(second_head.size(), 'A') + second_head +
  24449. inner;
  24450. std::string response;
  24451. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  24452. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  24453. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  24454. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  24455. EXPECT_EQ(0, smuggled_count.load()) << target;
  24456. }
  24457. }
  24458. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  24459. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  24460. // must be rejected with 400 Bad Request.
  24461. Server svr;
  24462. svr.Post("/test", [&](const Request &, Response &res) {
  24463. res.set_content("ok", "text/plain");
  24464. });
  24465. thread t = thread([&] { svr.listen(HOST, PORT); });
  24466. auto se = detail::scope_exit([&] {
  24467. svr.stop();
  24468. t.join();
  24469. ASSERT_FALSE(svr.is_running());
  24470. });
  24471. svr.wait_until_ready();
  24472. // Exact "chunked"
  24473. {
  24474. auto req = "POST /test HTTP/1.1\r\n"
  24475. "Host: localhost\r\n"
  24476. "Content-Length: 5\r\n"
  24477. "Transfer-Encoding: chunked\r\n"
  24478. "Connection: close\r\n"
  24479. "\r\n"
  24480. "hello";
  24481. std::string response;
  24482. ASSERT_TRUE(send_request(1, req, &response));
  24483. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24484. response.substr(0, response.find("\r\n")));
  24485. }
  24486. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  24487. {
  24488. auto req = "POST /test HTTP/1.1\r\n"
  24489. "Host: localhost\r\n"
  24490. "Content-Length: 5\r\n"
  24491. "Transfer-Encoding: gzip, chunked\r\n"
  24492. "Connection: close\r\n"
  24493. "\r\n"
  24494. "hello";
  24495. std::string response;
  24496. ASSERT_TRUE(send_request(1, req, &response));
  24497. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24498. response.substr(0, response.find("\r\n")));
  24499. }
  24500. }
  24501. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  24502. Server svr;
  24503. svr.Post("/test", [&](const Request &, Response &res) {
  24504. res.set_content("ok", "text/plain");
  24505. });
  24506. thread t = thread([&] { svr.listen(HOST, PORT); });
  24507. auto se = detail::scope_exit([&] {
  24508. svr.stop();
  24509. t.join();
  24510. ASSERT_FALSE(svr.is_running());
  24511. });
  24512. svr.wait_until_ready();
  24513. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  24514. // length cannot be determined, so the server must answer 400 and close
  24515. // rather than treat the request as bodyless and leave the body in the
  24516. // socket for the next request to pick up.
  24517. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  24518. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  24519. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  24520. std::string response;
  24521. ASSERT_TRUE(send_request(1, req, &response));
  24522. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24523. response.substr(0, response.find("\r\n")))
  24524. << transfer_encoding;
  24525. }
  24526. // RFC 9110 5.3: the codings may also be split across several
  24527. // Transfer-Encoding lines, which combine in the order they were received.
  24528. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  24529. // just like the single-line "chunked, gzip" above.
  24530. {
  24531. auto req = "POST /test HTTP/1.1\r\n"
  24532. "Host: localhost\r\n"
  24533. "Transfer-Encoding: chunked\r\n"
  24534. "Transfer-Encoding: gzip\r\n"
  24535. "\r\n"
  24536. "0\r\n\r\n";
  24537. std::string response;
  24538. ASSERT_TRUE(send_request(1, req, &response));
  24539. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24540. response.substr(0, response.find("\r\n")));
  24541. }
  24542. // A sequence ending in chunked stays valid.
  24543. auto req = "POST /test HTTP/1.1\r\n"
  24544. "Host: localhost\r\n"
  24545. "Transfer-Encoding: gzip, chunked\r\n"
  24546. "Connection: close\r\n"
  24547. "\r\n"
  24548. "0\r\n\r\n";
  24549. std::string response;
  24550. ASSERT_TRUE(send_request(1, req, &response));
  24551. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  24552. // ...including when it is spread over several lines.
  24553. auto split_req = "POST /test HTTP/1.1\r\n"
  24554. "Host: localhost\r\n"
  24555. "Transfer-Encoding: gzip\r\n"
  24556. "Transfer-Encoding: chunked\r\n"
  24557. "Connection: close\r\n"
  24558. "\r\n"
  24559. "0\r\n\r\n";
  24560. std::string split_response;
  24561. ASSERT_TRUE(send_request(1, split_req, &split_response));
  24562. EXPECT_EQ("HTTP/1.1 200 OK",
  24563. split_response.substr(0, split_response.find("\r\n")));
  24564. }
  24565. // Regression for issue #2450: a DELETE without Content-Length on a
  24566. // keep-alive connection must not let the post-response drain consume the
  24567. // next request's bytes.
  24568. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  24569. Server svr;
  24570. std::atomic<int> delete_count(0);
  24571. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  24572. delete_count++;
  24573. res.status = StatusCode::NoContent_204;
  24574. });
  24575. auto port = svr.bind_to_any_port(HOST);
  24576. thread t = thread([&] { svr.listen_after_bind(); });
  24577. auto se = detail::scope_exit([&] {
  24578. svr.stop();
  24579. t.join();
  24580. });
  24581. svr.wait_until_ready();
  24582. auto error = Error::Success;
  24583. auto sock = detail::create_client_socket(
  24584. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24585. /*connection_timeout_sec=*/2, 0,
  24586. /*read_timeout_sec=*/2, 0,
  24587. /*write_timeout_sec=*/2, 0, std::string(), error);
  24588. ASSERT_NE(INVALID_SOCKET, sock);
  24589. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24590. auto send_request_and_read_response = [&](const std::string &req,
  24591. std::string &out) -> bool {
  24592. auto sent = send(sock, req.data(), req.size(), 0);
  24593. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  24594. char buf[4096];
  24595. for (;;) {
  24596. auto n = recv(sock, buf, sizeof(buf), 0);
  24597. if (n <= 0) { return !out.empty(); }
  24598. out.append(buf, static_cast<size_t>(n));
  24599. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  24600. }
  24601. };
  24602. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  24603. "Host: localhost\r\n"
  24604. "\r\n";
  24605. std::string resp1;
  24606. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  24607. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  24608. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  24609. "Host: localhost\r\n"
  24610. "Connection: close\r\n"
  24611. "\r\n";
  24612. std::string resp2;
  24613. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  24614. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  24615. EXPECT_EQ(2, delete_count.load());
  24616. }
  24617. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  24618. Server svr;
  24619. svr.Post("/ingest", [&](const Request &, Response &res,
  24620. const ContentReader &content_reader) {
  24621. auto consumed = content_reader([](const char *, size_t) { return false; });
  24622. EXPECT_FALSE(consumed);
  24623. res.status = StatusCode::Conflict_409;
  24624. res.set_header("Connection", "close");
  24625. });
  24626. auto port = svr.bind_to_any_port(HOST);
  24627. thread t = thread([&] { svr.listen_after_bind(); });
  24628. auto se = detail::scope_exit([&] {
  24629. svr.stop();
  24630. t.join();
  24631. });
  24632. svr.wait_until_ready();
  24633. auto error = Error::Success;
  24634. auto sock = detail::create_client_socket(
  24635. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24636. /*connection_timeout_sec=*/2, 0,
  24637. /*read_timeout_sec=*/1, 0,
  24638. /*write_timeout_sec=*/2, 0, std::string(), error);
  24639. ASSERT_NE(INVALID_SOCKET, sock);
  24640. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24641. std::string request = "POST /ingest HTTP/1.1\r\n"
  24642. "Host: localhost\r\n"
  24643. "Transfer-Encoding: chunked\r\n"
  24644. "\r\n"
  24645. "4\r\n"
  24646. "data\r\n";
  24647. auto sent = send(sock, request.data(), request.size(), 0);
  24648. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  24649. std::string response;
  24650. ssize_t received = 0;
  24651. do {
  24652. char buf[4096];
  24653. received = recv(sock, buf, sizeof(buf), 0);
  24654. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  24655. } while (received > 0);
  24656. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  24657. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  24658. EXPECT_EQ(0, received);
  24659. }
  24660. namespace no_proxy_test {
  24661. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  24662. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  24663. // calling listen().
  24664. class ScopedServer {
  24665. public:
  24666. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  24667. ~ScopedServer() {
  24668. svr_.stop();
  24669. if (th_.joinable()) { th_.join(); }
  24670. }
  24671. Server &svr() { return svr_; }
  24672. int port() const { return port_; }
  24673. void listen() {
  24674. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24675. svr_.wait_until_ready();
  24676. }
  24677. private:
  24678. Server svr_;
  24679. std::thread th_;
  24680. int port_ = 0;
  24681. };
  24682. class ProxyAndTargetServers {
  24683. public:
  24684. ProxyAndTargetServers() {
  24685. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  24686. proxy_hits_++;
  24687. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24688. res.set_content("via-proxy", "text/plain");
  24689. });
  24690. target_.Get(".*", [this](const Request &req, Response &res) {
  24691. target_hits_++;
  24692. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24693. res.set_content("direct", "text/plain");
  24694. });
  24695. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  24696. target_port_ = target_.bind_to_any_port("127.0.0.1");
  24697. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  24698. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  24699. proxy_mock_.wait_until_ready();
  24700. target_.wait_until_ready();
  24701. }
  24702. ~ProxyAndTargetServers() {
  24703. proxy_mock_.stop();
  24704. target_.stop();
  24705. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  24706. if (target_thread_.joinable()) { target_thread_.join(); }
  24707. }
  24708. Server &proxy_mock() { return proxy_mock_; }
  24709. Server &target() { return target_; }
  24710. int proxy_port() const { return proxy_port_; }
  24711. int target_port() const { return target_port_; }
  24712. int proxy_hits() const { return proxy_hits_.load(); }
  24713. int target_hits() const { return target_hits_.load(); }
  24714. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  24715. void reset_counters() {
  24716. proxy_hits_ = 0;
  24717. target_hits_ = 0;
  24718. last_had_proxy_authz_ = false;
  24719. }
  24720. private:
  24721. Server proxy_mock_;
  24722. Server target_;
  24723. std::thread proxy_thread_;
  24724. std::thread target_thread_;
  24725. int proxy_port_ = 0;
  24726. int target_port_ = 0;
  24727. std::atomic<int> proxy_hits_{0};
  24728. std::atomic<int> target_hits_{0};
  24729. std::atomic<bool> last_had_proxy_authz_{false};
  24730. };
  24731. inline std::unique_ptr<Client> make_client(const std::string &host,
  24732. ProxyAndTargetServers &s) {
  24733. auto cli = detail::make_unique<Client>(host, s.target_port());
  24734. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  24735. cli->set_proxy("127.0.0.1", s.proxy_port());
  24736. return cli;
  24737. }
  24738. } // namespace no_proxy_test
  24739. using no_proxy_test::make_client;
  24740. using no_proxy_test::ProxyAndTargetServers;
  24741. TEST(NoProxyTest, ExactHostnameBypasses) {
  24742. ProxyAndTargetServers s;
  24743. auto cli = make_client("example.com", s);
  24744. cli->set_no_proxy({"example.com"});
  24745. auto res = cli->Get("/");
  24746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24747. EXPECT_EQ(0, s.proxy_hits());
  24748. EXPECT_EQ(1, s.target_hits());
  24749. }
  24750. TEST(NoProxyTest, SubdomainBypasses) {
  24751. ProxyAndTargetServers s;
  24752. auto cli = make_client("foo.example.com", s);
  24753. cli->set_no_proxy({"example.com"});
  24754. auto res = cli->Get("/");
  24755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24756. EXPECT_EQ(0, s.proxy_hits());
  24757. EXPECT_EQ(1, s.target_hits());
  24758. }
  24759. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  24760. // Regression guard: "evilexample.com" must not be considered a subdomain
  24761. // of "example.com". Without the dot-boundary rule, a naive endsWith
  24762. // check would let traffic bypass the proxy and leak credentials direct
  24763. // to the attacker host.
  24764. ProxyAndTargetServers s;
  24765. auto cli = make_client("evilexample.com", s);
  24766. cli->set_no_proxy({"example.com"});
  24767. auto res = cli->Get("/");
  24768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24769. EXPECT_GE(s.proxy_hits(), 1);
  24770. EXPECT_EQ(0, s.target_hits());
  24771. }
  24772. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  24773. ProxyAndTargetServers s;
  24774. auto cli = make_client("example.com.evil.com", s);
  24775. cli->set_no_proxy({"example.com"});
  24776. auto res = cli->Get("/");
  24777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24778. EXPECT_GE(s.proxy_hits(), 1);
  24779. EXPECT_EQ(0, s.target_hits());
  24780. }
  24781. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  24782. ProxyAndTargetServers s;
  24783. auto cli = make_client("example.com", s);
  24784. cli->set_no_proxy({".example.com"});
  24785. auto res = cli->Get("/");
  24786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24787. EXPECT_EQ(0, s.proxy_hits());
  24788. EXPECT_EQ(1, s.target_hits());
  24789. }
  24790. TEST(NoProxyTest, CaseInsensitiveHostname) {
  24791. ProxyAndTargetServers s;
  24792. auto cli = make_client("Example.COM", s);
  24793. cli->set_no_proxy({"EXAMPLE.com"});
  24794. auto res = cli->Get("/");
  24795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24796. EXPECT_EQ(0, s.proxy_hits());
  24797. EXPECT_EQ(1, s.target_hits());
  24798. }
  24799. TEST(NoProxyTest, TrailingDotIsNormalized) {
  24800. ProxyAndTargetServers s;
  24801. auto cli = make_client("example.com.", s);
  24802. cli->set_no_proxy({"example.com"});
  24803. auto res = cli->Get("/");
  24804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24805. EXPECT_EQ(0, s.proxy_hits());
  24806. EXPECT_EQ(1, s.target_hits());
  24807. }
  24808. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  24809. // Trailing dots must be normalized on BOTH sides — host and entry.
  24810. // An implementation that only strips the host-side trailing dot would
  24811. // fail to match host "example.com" against entry "example.com." because
  24812. // a literal substring search would compare 11 chars against 12.
  24813. ProxyAndTargetServers s;
  24814. auto cli = make_client("example.com", s);
  24815. cli->set_no_proxy({"example.com."});
  24816. auto res = cli->Get("/");
  24817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24818. EXPECT_EQ(0, s.proxy_hits());
  24819. EXPECT_EQ(1, s.target_hits());
  24820. }
  24821. TEST(NoProxyTest, WildcardBypassesEverything) {
  24822. ProxyAndTargetServers s;
  24823. auto cli = make_client("anything.invalid.test", s);
  24824. cli->set_no_proxy({"*"});
  24825. auto res = cli->Get("/");
  24826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24827. EXPECT_EQ(0, s.proxy_hits());
  24828. EXPECT_EQ(1, s.target_hits());
  24829. }
  24830. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  24831. ProxyAndTargetServers s;
  24832. Client cli("127.0.0.1", s.target_port());
  24833. cli.set_proxy("127.0.0.1", s.proxy_port());
  24834. cli.set_no_proxy({"127.0.0.1"});
  24835. auto res = cli.Get("/");
  24836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24837. EXPECT_EQ(0, s.proxy_hits());
  24838. EXPECT_EQ(1, s.target_hits());
  24839. }
  24840. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  24841. ProxyAndTargetServers s;
  24842. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  24843. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  24844. cli.set_proxy("127.0.0.1", s.proxy_port());
  24845. cli.set_no_proxy({"::1"});
  24846. auto res = cli.Get("/");
  24847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24848. EXPECT_EQ(0, s.proxy_hits());
  24849. EXPECT_EQ(1, s.target_hits());
  24850. }
  24851. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  24852. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  24853. // must still be recognized as IPv6 for CIDR matching. Implementations
  24854. // that detect IPv6 only when the host begins with '[' would parse the
  24855. // host as a hostname and miss the match.
  24856. ProxyAndTargetServers s;
  24857. Client cli("fe80::1", s.target_port());
  24858. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24859. cli.set_proxy("127.0.0.1", s.proxy_port());
  24860. cli.set_no_proxy({"fe80::/10"});
  24861. auto res = cli.Get("/");
  24862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24863. EXPECT_EQ(0, s.proxy_hits());
  24864. EXPECT_EQ(1, s.target_hits());
  24865. }
  24866. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  24867. ProxyAndTargetServers s;
  24868. Client cli("::1", s.target_port());
  24869. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  24870. cli.set_proxy("127.0.0.1", s.proxy_port());
  24871. cli.set_no_proxy({"[::1]"});
  24872. auto res = cli.Get("/");
  24873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24874. EXPECT_EQ(0, s.proxy_hits());
  24875. EXPECT_EQ(1, s.target_hits());
  24876. }
  24877. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  24878. ProxyAndTargetServers s;
  24879. Client cli("fe80::1", s.target_port());
  24880. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24881. cli.set_proxy("127.0.0.1", s.proxy_port());
  24882. cli.set_no_proxy({"[fe80::]/10"});
  24883. auto res = cli.Get("/");
  24884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24885. EXPECT_EQ(0, s.proxy_hits());
  24886. EXPECT_EQ(1, s.target_hits());
  24887. }
  24888. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  24889. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  24890. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  24891. // tricks via address-family conversion.
  24892. ProxyAndTargetServers s;
  24893. Client cli("::ffff:127.0.0.1", s.target_port());
  24894. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  24895. cli.set_proxy("127.0.0.1", s.proxy_port());
  24896. cli.set_no_proxy({"127.0.0.1"});
  24897. auto res = cli.Get("/");
  24898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24899. EXPECT_GE(s.proxy_hits(), 1);
  24900. EXPECT_EQ(0, s.target_hits());
  24901. }
  24902. TEST(NoProxyTest, IPv4CidrMatch) {
  24903. ProxyAndTargetServers s;
  24904. Client cli("127.0.0.1", s.target_port());
  24905. cli.set_proxy("127.0.0.1", s.proxy_port());
  24906. cli.set_no_proxy({"127.0.0.0/8"});
  24907. auto res = cli.Get("/");
  24908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24909. EXPECT_EQ(0, s.proxy_hits());
  24910. EXPECT_EQ(1, s.target_hits());
  24911. }
  24912. TEST(NoProxyTest, IPv4CidrNonMatch) {
  24913. ProxyAndTargetServers s;
  24914. Client cli("127.0.0.1", s.target_port());
  24915. cli.set_proxy("127.0.0.1", s.proxy_port());
  24916. cli.set_no_proxy({"10.0.0.0/8"});
  24917. auto res = cli.Get("/");
  24918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24919. EXPECT_GE(s.proxy_hits(), 1);
  24920. EXPECT_EQ(0, s.target_hits());
  24921. }
  24922. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  24923. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  24924. // IPv4 target matches.
  24925. ProxyAndTargetServers s;
  24926. Client cli("127.0.0.1", s.target_port());
  24927. cli.set_proxy("127.0.0.1", s.proxy_port());
  24928. cli.set_no_proxy({"0.0.0.0/0"});
  24929. auto res = cli.Get("/");
  24930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24931. EXPECT_EQ(0, s.proxy_hits());
  24932. EXPECT_EQ(1, s.target_hits());
  24933. }
  24934. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  24935. ProxyAndTargetServers s;
  24936. Client cli("127.0.0.1", s.target_port());
  24937. cli.set_proxy("127.0.0.1", s.proxy_port());
  24938. cli.set_no_proxy({"127.0.0.1"});
  24939. auto res = cli.Get("/");
  24940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24941. EXPECT_EQ(0, s.proxy_hits());
  24942. EXPECT_EQ(1, s.target_hits());
  24943. }
  24944. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  24945. ProxyAndTargetServers s;
  24946. Client cli("127.0.0.1", s.target_port());
  24947. cli.set_proxy("127.0.0.1", s.proxy_port());
  24948. cli.set_no_proxy({"127.0.0.0/33"});
  24949. auto res = cli.Get("/");
  24950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24951. EXPECT_GE(s.proxy_hits(), 1);
  24952. EXPECT_EQ(0, s.target_hits());
  24953. }
  24954. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  24955. // Empty prefix after the slash must be rejected, not silently treated as /32.
  24956. ProxyAndTargetServers s;
  24957. Client cli("127.0.0.1", s.target_port());
  24958. cli.set_proxy("127.0.0.1", s.proxy_port());
  24959. cli.set_no_proxy({"127.0.0.1/"});
  24960. auto res = cli.Get("/");
  24961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24962. EXPECT_GE(s.proxy_hits(), 1);
  24963. EXPECT_EQ(0, s.target_hits());
  24964. }
  24965. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  24966. ProxyAndTargetServers s;
  24967. auto cli = make_client("internal.corp", s);
  24968. cli->set_proxy_basic_auth("u", "p");
  24969. cli->set_no_proxy({"internal.corp"});
  24970. auto res = cli->Get("/");
  24971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24972. EXPECT_EQ(1, s.target_hits());
  24973. EXPECT_EQ(0, s.proxy_hits());
  24974. EXPECT_FALSE(s.last_had_proxy_authz())
  24975. << "Proxy-Authorization must not be sent direct to the target";
  24976. }
  24977. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  24978. ProxyAndTargetServers s;
  24979. auto cli = make_client("public.example", s);
  24980. cli->set_proxy_basic_auth("u", "p");
  24981. cli->set_no_proxy({"internal.corp"}); // does not match
  24982. auto res = cli->Get("/");
  24983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24984. EXPECT_GE(s.proxy_hits(), 1);
  24985. EXPECT_TRUE(s.last_had_proxy_authz());
  24986. }
  24987. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  24988. std::atomic<int> hits{0};
  24989. std::atomic<int> hits_with_authz{0};
  24990. no_proxy_test::ScopedServer proxy_mock;
  24991. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24992. hits++;
  24993. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  24994. if (req.target.find("/redir") != std::string::npos) {
  24995. res.set_redirect("http://other.example/landed");
  24996. } else {
  24997. res.set_content("via-proxy", "text/plain");
  24998. }
  24999. });
  25000. proxy_mock.listen();
  25001. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  25002. hits = 0;
  25003. hits_with_authz = 0;
  25004. Client cli("public.example", 80);
  25005. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25006. cli.set_proxy_basic_auth(c.first, c.second);
  25007. cli.set_follow_location(true);
  25008. // The redirect to another host goes through the proxy as well
  25009. auto res = cli.Get("/redir");
  25010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25011. EXPECT_EQ(2, hits.load());
  25012. EXPECT_EQ(2, hits_with_authz.load());
  25013. }
  25014. }
  25015. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  25016. ProxyAndTargetServers s;
  25017. auto cli = make_client("anything.test", s);
  25018. auto res = cli->Get("/");
  25019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25020. EXPECT_GE(s.proxy_hits(), 1);
  25021. EXPECT_EQ(0, s.target_hits());
  25022. }
  25023. TEST(NoProxyTest, PortSpecificEntryRejected) {
  25024. ProxyAndTargetServers s;
  25025. auto cli = make_client("example.com", s);
  25026. cli->set_no_proxy({"example.com:8080"});
  25027. auto res = cli->Get("/");
  25028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25029. EXPECT_GE(s.proxy_hits(), 1);
  25030. EXPECT_EQ(0, s.target_hits());
  25031. }
  25032. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  25033. ProxyAndTargetServers s;
  25034. auto cli = make_client("anything.test", s);
  25035. cli->set_no_proxy({"", " ", "\t"});
  25036. auto res = cli->Get("/");
  25037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25038. EXPECT_GE(s.proxy_hits(), 1);
  25039. EXPECT_EQ(0, s.target_hits());
  25040. }
  25041. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  25042. // An entry with leading/trailing whitespace must still match — env-style
  25043. // values are commonly pasted with stray spaces and an implementation
  25044. // that feeds the raw token directly to inet_pton would fail to match
  25045. // valid CIDRs because of the spaces.
  25046. ProxyAndTargetServers s;
  25047. Client cli("127.0.0.1", s.target_port());
  25048. cli.set_proxy("127.0.0.1", s.proxy_port());
  25049. cli.set_no_proxy({" 127.0.0.0/8 "});
  25050. auto res = cli.Get("/");
  25051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25052. EXPECT_EQ(0, s.proxy_hits());
  25053. EXPECT_EQ(1, s.target_hits());
  25054. }
  25055. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  25056. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  25057. // go direct and must NOT carry Proxy-Authorization.
  25058. std::atomic<int> proxy_hits{0};
  25059. std::atomic<int> target_hits{0};
  25060. std::atomic<bool> target_saw_authz{false};
  25061. no_proxy_test::ScopedServer proxy_mock, target;
  25062. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25063. proxy_hits++;
  25064. res.status = 302;
  25065. res.set_header("Location", "http://127.0.0.1:" +
  25066. std::to_string(target.port()) + "/landed");
  25067. });
  25068. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25069. target_hits++;
  25070. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  25071. res.set_content("direct", "text/plain");
  25072. });
  25073. proxy_mock.listen();
  25074. target.listen();
  25075. Client cli("public.example", target.port());
  25076. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25077. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25078. cli.set_proxy_basic_auth("u", "p");
  25079. cli.set_no_proxy({"127.0.0.1"});
  25080. cli.set_follow_location(true);
  25081. auto res = cli.Get("/redir");
  25082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25083. EXPECT_GE(proxy_hits.load(), 1);
  25084. EXPECT_GE(target_hits.load(), 1);
  25085. EXPECT_FALSE(target_saw_authz.load());
  25086. }
  25087. #ifdef CPPHTTPLIB_SSL_ENABLED
  25088. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  25089. // Direct origin replying 407 must not trigger the digest retry; otherwise
  25090. // proxy creds would be sent to the (possibly hostile) origin.
  25091. std::atomic<int> target_hits{0};
  25092. std::atomic<bool> target_saw_proxy_authz{false};
  25093. no_proxy_test::ScopedServer target;
  25094. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25095. target_hits++;
  25096. if (req.has_header("Proxy-Authorization")) {
  25097. target_saw_proxy_authz = true;
  25098. }
  25099. res.status = StatusCode::ProxyAuthenticationRequired_407;
  25100. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  25101. "nonce=\"abc\", algorithm=MD5");
  25102. });
  25103. target.listen();
  25104. // The proxy address is set to the target's port: the bypass MUST kick in;
  25105. // if it doesn't, the test still routes "via proxy" to the same server and
  25106. // the Proxy-Authorization assertion below catches the leak.
  25107. Client cli("evil.example", target.port());
  25108. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  25109. cli.set_proxy("127.0.0.1", target.port());
  25110. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25111. cli.set_no_proxy({"evil.example"});
  25112. auto res = cli.Get("/x");
  25113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25114. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  25115. EXPECT_EQ(1, target_hits.load());
  25116. EXPECT_FALSE(target_saw_proxy_authz.load());
  25117. }
  25118. #endif
  25119. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  25120. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  25121. std::atomic<int> proxy_hits{0};
  25122. std::atomic<int> bypass_hits{0};
  25123. std::atomic<bool> proxy_saw_c_url{false};
  25124. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  25125. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25126. proxy_hits++;
  25127. if (req.path.find("/start") != std::string::npos) {
  25128. res.status = 302;
  25129. res.set_header("Location", "http://127.0.0.1:" +
  25130. std::to_string(bypass_server.port()) +
  25131. "/middle");
  25132. return;
  25133. }
  25134. if (req.path.find("/end") != std::string::npos) {
  25135. proxy_saw_c_url = true;
  25136. res.set_content("c-via-proxy", "text/plain");
  25137. return;
  25138. }
  25139. res.set_content("unexpected", "text/plain");
  25140. });
  25141. // public.example's "advertised" port is arbitrary (the request never lands
  25142. // there — it goes through the proxy), but use a dynamic value to stay
  25143. // friendly with sharded parallel runs.
  25144. int public_port = bypass_server.port();
  25145. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  25146. bypass_hits++;
  25147. res.status = 302;
  25148. res.set_header("Location", "http://public.example:" +
  25149. std::to_string(public_port) + "/end");
  25150. });
  25151. proxy_mock.listen();
  25152. bypass_server.listen();
  25153. Client cli("public.example", public_port);
  25154. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25155. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25156. cli.set_no_proxy({"127.0.0.1"});
  25157. cli.set_follow_location(true);
  25158. auto res = cli.Get("/start");
  25159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25160. EXPECT_EQ(StatusCode::OK_200, res->status);
  25161. EXPECT_EQ("c-via-proxy", res->body);
  25162. EXPECT_GE(proxy_hits.load(), 2);
  25163. EXPECT_GE(bypass_hits.load(), 1);
  25164. EXPECT_TRUE(proxy_saw_c_url.load());
  25165. }
  25166. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  25167. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  25168. // request reconnects to the correct endpoint.
  25169. std::atomic<int> proxy_hits{0};
  25170. std::atomic<int> target_hits{0};
  25171. no_proxy_test::ScopedServer proxy_mock, target;
  25172. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25173. proxy_hits++;
  25174. res.set_content("via-proxy", "text/plain");
  25175. });
  25176. target.svr().Get(".*", [&](const Request &, Response &res) {
  25177. target_hits++;
  25178. res.set_content("direct", "text/plain");
  25179. });
  25180. proxy_mock.listen();
  25181. target.listen();
  25182. Client cli("public.example", target.port());
  25183. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25184. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25185. cli.set_keep_alive(true);
  25186. auto res1 = cli.Get("/a");
  25187. ASSERT_TRUE(res1);
  25188. EXPECT_EQ("via-proxy", res1->body);
  25189. EXPECT_EQ(1, proxy_hits.load());
  25190. EXPECT_EQ(0, target_hits.load());
  25191. cli.set_no_proxy({"public.example"});
  25192. auto res2 = cli.Get("/b");
  25193. ASSERT_TRUE(res2);
  25194. EXPECT_EQ("direct", res2->body);
  25195. EXPECT_EQ(1, proxy_hits.load());
  25196. EXPECT_EQ(1, target_hits.load());
  25197. }
  25198. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  25199. namespace proxy_tunnel_test {
  25200. // SSLServer counterpart to no_proxy_test::ScopedServer.
  25201. class ScopedSSLServer {
  25202. public:
  25203. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  25204. port_ = svr_.bind_to_any_port("127.0.0.1");
  25205. }
  25206. ~ScopedSSLServer() {
  25207. svr_.stop();
  25208. if (th_.joinable()) { th_.join(); }
  25209. }
  25210. SSLServer &svr() { return svr_; }
  25211. int port() const { return port_; }
  25212. void listen() {
  25213. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25214. svr_.wait_until_ready();
  25215. }
  25216. private:
  25217. SSLServer svr_;
  25218. std::thread th_;
  25219. int port_ = 0;
  25220. };
  25221. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  25222. class ScopedConnectProxy {
  25223. public:
  25224. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  25225. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  25226. if (listen_fd_ < 0) { return; }
  25227. int yes = 1;
  25228. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  25229. sockaddr_in a{};
  25230. a.sin_family = AF_INET;
  25231. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  25232. a.sin_port = 0;
  25233. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  25234. return;
  25235. }
  25236. socklen_t alen = sizeof(a);
  25237. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  25238. 0) {
  25239. return;
  25240. }
  25241. port_ = ntohs(a.sin_port);
  25242. if (::listen(listen_fd_, 1) != 0) { return; }
  25243. th_ = std::thread([this] { run(); });
  25244. }
  25245. ~ScopedConnectProxy() {
  25246. stop_ = true;
  25247. if (listen_fd_ >= 0) {
  25248. ::shutdown(listen_fd_, SHUT_RDWR);
  25249. ::close(listen_fd_);
  25250. }
  25251. if (th_.joinable()) { th_.join(); }
  25252. }
  25253. int port() const { return port_; }
  25254. int connect_hits() const { return connect_hits_.load(); }
  25255. // Head of the last CONNECT request, as the proxy saw it on the wire.
  25256. std::string connect_request() const {
  25257. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  25258. return connect_request_;
  25259. }
  25260. private:
  25261. void run() {
  25262. while (!stop_.load()) {
  25263. fd_set rfds;
  25264. FD_ZERO(&rfds);
  25265. FD_SET(listen_fd_, &rfds);
  25266. timeval tv{0, 100 * 1000};
  25267. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  25268. if (sel <= 0) { continue; }
  25269. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  25270. if (client_fd < 0) { continue; }
  25271. std::string req;
  25272. char buf[2048];
  25273. while (req.find("\r\n\r\n") == std::string::npos) {
  25274. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  25275. if (n <= 0) { break; }
  25276. req.append(buf, static_cast<size_t>(n));
  25277. }
  25278. if (req.compare(0, 7, "CONNECT") != 0) {
  25279. ::close(client_fd);
  25280. continue;
  25281. }
  25282. connect_hits_++;
  25283. {
  25284. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  25285. connect_request_ = req;
  25286. }
  25287. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  25288. ::send(client_fd, ok, std::strlen(ok), 0);
  25289. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  25290. sockaddr_in o{};
  25291. o.sin_family = AF_INET;
  25292. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  25293. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  25294. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  25295. 0) {
  25296. ::close(client_fd);
  25297. ::close(origin_fd);
  25298. continue;
  25299. }
  25300. auto forward = [](int from, int to) {
  25301. char b[8192];
  25302. for (;;) {
  25303. ssize_t n = ::recv(from, b, sizeof(b), 0);
  25304. if (n <= 0) { break; }
  25305. ssize_t off = 0;
  25306. while (off < n) {
  25307. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  25308. if (s <= 0) {
  25309. off = n;
  25310. break;
  25311. }
  25312. off += s;
  25313. }
  25314. }
  25315. ::shutdown(to, SHUT_WR);
  25316. };
  25317. std::thread t1([&] { forward(client_fd, origin_fd); });
  25318. std::thread t2([&] { forward(origin_fd, client_fd); });
  25319. t1.join();
  25320. t2.join();
  25321. ::close(client_fd);
  25322. ::close(origin_fd);
  25323. }
  25324. }
  25325. int forward_port_ = -1;
  25326. int listen_fd_ = -1;
  25327. int port_ = 0;
  25328. std::thread th_;
  25329. std::atomic<bool> stop_{false};
  25330. std::atomic<int> connect_hits_{0};
  25331. mutable std::mutex connect_request_mutex_;
  25332. std::string connect_request_;
  25333. };
  25334. // Sends one request through the CONNECT proxy to the TLS origin with a
  25335. // credential configured for each hop, and checks that each credential reaches
  25336. // only the hop it was configured for: the proxy's on the CONNECT request, the
  25337. // origin's (every header in origin_headers) on the tunnelled request.
  25338. void CredentialsStayWithTheirHop(
  25339. const std::function<void(SSLClient &)> &set_credentials,
  25340. const std::string &scheme,
  25341. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  25342. std::atomic<int> origin_hits{0};
  25343. std::atomic<bool> origin_saw_proxy_authz{false};
  25344. std::atomic<bool> origin_saw_headers{false};
  25345. ScopedSSLServer origin;
  25346. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  25347. origin_hits++;
  25348. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  25349. origin_saw_headers =
  25350. std::all_of(origin_headers.begin(), origin_headers.end(),
  25351. [&](const std::string &h) { return req.has_header(h); });
  25352. res.set_content("ok", "text/plain");
  25353. });
  25354. origin.listen();
  25355. ScopedConnectProxy proxy(origin.port());
  25356. ASSERT_NE(0, proxy.port());
  25357. // Pinned to 127.0.0.1 for the same reason as the test below.
  25358. SSLClient cli("127.0.0.1", origin.port());
  25359. cli.enable_server_certificate_verification(false);
  25360. cli.set_proxy("127.0.0.1", proxy.port());
  25361. set_credentials(cli);
  25362. auto res = cli.Get("/x");
  25363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25364. EXPECT_EQ(StatusCode::OK_200, res->status);
  25365. EXPECT_EQ(1, origin_hits.load());
  25366. EXPECT_EQ(1, proxy.connect_hits());
  25367. EXPECT_TRUE(origin_saw_headers.load());
  25368. EXPECT_FALSE(origin_saw_proxy_authz.load())
  25369. << "Proxy-Authorization must not be sent inside the tunnel";
  25370. auto connect_req = proxy.connect_request();
  25371. EXPECT_NE(std::string::npos,
  25372. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  25373. for (const auto &h : origin_headers) {
  25374. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  25375. << h << " must not be sent to the proxy on CONNECT";
  25376. }
  25377. }
  25378. } // namespace proxy_tunnel_test
  25379. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  25380. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25381. [](SSLClient &cli) {
  25382. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25383. cli.set_basic_auth("origin-user", "origin-pass");
  25384. },
  25385. "Basic");
  25386. }
  25387. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  25388. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25389. [](SSLClient &cli) {
  25390. cli.set_proxy_bearer_token_auth("proxy-token");
  25391. cli.set_bearer_token_auth("origin-token");
  25392. },
  25393. "Bearer");
  25394. }
  25395. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  25396. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25397. [](SSLClient &cli) {
  25398. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25399. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  25400. {"Cookie", "sid=origin-session"},
  25401. {"X-Api-Key", "origin-key"}});
  25402. },
  25403. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  25404. }
  25405. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  25406. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  25407. // retry; otherwise proxy creds would be sent to the origin.
  25408. std::atomic<int> origin_hits{0};
  25409. std::atomic<bool> origin_saw_proxy_authz{false};
  25410. proxy_tunnel_test::ScopedSSLServer origin;
  25411. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  25412. origin_hits++;
  25413. if (req.has_header("Proxy-Authorization")) {
  25414. origin_saw_proxy_authz = true;
  25415. }
  25416. res.status = StatusCode::ProxyAuthenticationRequired_407;
  25417. res.set_header("Proxy-Authenticate",
  25418. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  25419. "algorithm=MD5");
  25420. });
  25421. origin.listen();
  25422. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  25423. ASSERT_NE(0, proxy.port());
  25424. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  25425. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  25426. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  25427. // and answer with its own status, making this test flaky.
  25428. SSLClient cli("127.0.0.1", origin.port());
  25429. cli.enable_server_certificate_verification(false);
  25430. cli.set_proxy("127.0.0.1", proxy.port());
  25431. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25432. auto res = cli.Get("/x");
  25433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25434. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  25435. EXPECT_EQ(1, origin_hits.load());
  25436. EXPECT_FALSE(origin_saw_proxy_authz.load());
  25437. EXPECT_EQ(1, proxy.connect_hits());
  25438. }
  25439. #endif