test.cc 963 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definition is linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. } // namespace tls
  68. } // namespace httplib
  69. #endif
  70. using namespace std;
  71. using namespace httplib;
  72. const char *HOST = "localhost";
  73. static int get_base_port() {
  74. const char *shard = getenv("GTEST_SHARD_INDEX");
  75. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  76. }
  77. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  78. // New standalone tests MUST use svr.bind_to_any_port() instead.
  79. const int PORT = get_base_port();
  80. const string LONG_QUERY_VALUE = string(25000, '@');
  81. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  82. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  83. const string TOO_LONG_QUERY_URL =
  84. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  85. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  86. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  87. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  88. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  89. return file.name == key;
  90. });
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return *it;
  93. #else
  94. if (it != items.end()) { return *it; }
  95. throw std::runtime_error("invalid multipart form data name error");
  96. #endif
  97. }
  98. static void read_file(const std::string &path, std::string &out) {
  99. std::ifstream fs(path, std::ios_base::binary);
  100. if (!fs) {
  101. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  102. return;
  103. #else
  104. throw std::runtime_error("File not found: " + path);
  105. #endif
  106. }
  107. fs.seekg(0, std::ios_base::end);
  108. auto size = fs.tellg();
  109. fs.seekg(0);
  110. out.resize(static_cast<size_t>(size));
  111. fs.read(&out[0], static_cast<std::streamsize>(size));
  112. }
  113. class UnixSocketTest : public ::testing::Test {
  114. protected:
  115. void TearDown() override { std::remove(pathname_.c_str()); }
  116. void client_GET(const std::string &addr) {
  117. httplib::Client cli{addr};
  118. cli.set_address_family(AF_UNIX);
  119. ASSERT_TRUE(cli.is_valid());
  120. const auto &result = cli.Get(pattern_);
  121. ASSERT_TRUE(result) << "error: " << result.error();
  122. const auto &resp = result.value();
  123. EXPECT_EQ(resp.status, StatusCode::OK_200);
  124. EXPECT_EQ(resp.body, content_);
  125. }
  126. static std::string make_sock_path() {
  127. const char *shard = getenv("GTEST_SHARD_INDEX");
  128. return shard ? std::string("./httplib-server-") + shard + ".sock"
  129. : "./httplib-server.sock";
  130. }
  131. const std::string pathname_{make_sock_path()};
  132. const std::string pattern_{"/hi"};
  133. const std::string content_{"Hello World!"};
  134. };
  135. TEST_F(UnixSocketTest, pathname) {
  136. httplib::Server svr;
  137. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  138. res.set_content(content_, "text/plain");
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. }
  152. #if defined(__linux__) || \
  153. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  154. TEST_F(UnixSocketTest, PeerPid) {
  155. httplib::Server svr;
  156. std::string remote_port_val;
  157. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. remote_port_val = std::to_string(req.remote_port);
  160. });
  161. std::thread t{[&] {
  162. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  163. }};
  164. auto se = detail::scope_exit([&] {
  165. svr.stop();
  166. t.join();
  167. ASSERT_FALSE(svr.is_running());
  168. });
  169. svr.wait_until_ready();
  170. ASSERT_TRUE(svr.is_running());
  171. client_GET(pathname_);
  172. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  173. }
  174. #endif
  175. #ifdef __linux__
  176. TEST_F(UnixSocketTest, abstract) {
  177. constexpr char svr_path[]{"\x00httplib-server.sock"};
  178. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  179. httplib::Server svr;
  180. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  181. res.set_content(content_, "text/plain");
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(abstract_addr);
  194. }
  195. #endif
  196. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  197. httplib::Server svr;
  198. std::string received_host_header;
  199. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  200. // Capture the Host header sent by the client
  201. auto host_iter = req.headers.find("Host");
  202. if (host_iter != req.headers.end()) {
  203. received_host_header = host_iter->second;
  204. }
  205. res.set_content(content_, "text/plain");
  206. });
  207. std::thread t{[&] {
  208. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  209. }};
  210. auto se = detail::scope_exit([&] {
  211. svr.stop();
  212. t.join();
  213. ASSERT_FALSE(svr.is_running());
  214. });
  215. svr.wait_until_ready();
  216. ASSERT_TRUE(svr.is_running());
  217. // Test that Host header is automatically set to "localhost" for Unix socket
  218. // connections
  219. httplib::Client cli{pathname_};
  220. cli.set_address_family(AF_UNIX);
  221. ASSERT_TRUE(cli.is_valid());
  222. const auto &result = cli.Get(pattern_);
  223. ASSERT_TRUE(result) << "error: " << result.error();
  224. const auto &resp = result.value();
  225. EXPECT_EQ(resp.status, StatusCode::OK_200);
  226. EXPECT_EQ(resp.body, content_);
  227. // Verify that Host header was automatically set to "localhost"
  228. EXPECT_EQ(received_host_header, "localhost");
  229. }
  230. #ifndef _WIN32
  231. TEST(SocketStream, wait_writable_UNIX) {
  232. int fds[2];
  233. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  234. const auto asSocketStream = [&](socket_t fd,
  235. std::function<bool(Stream &)> func) {
  236. return detail::process_client_socket(
  237. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  238. };
  239. asSocketStream(fds[0], [&](Stream &s0) {
  240. EXPECT_EQ(s0.socket(), fds[0]);
  241. EXPECT_TRUE(s0.wait_writable());
  242. EXPECT_TRUE(s0.is_peer_alive());
  243. EXPECT_EQ(0, close(fds[1]));
  244. EXPECT_FALSE(s0.is_peer_alive());
  245. return true;
  246. });
  247. EXPECT_EQ(0, close(fds[0]));
  248. }
  249. TEST(SocketStream, wait_writable_INET) {
  250. sockaddr_in addr;
  251. memset(&addr, 0, sizeof(addr));
  252. addr.sin_family = AF_INET;
  253. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  254. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  255. int disconnected_svr_sock = -1;
  256. std::thread svr{[&] {
  257. const int s = socket(AF_INET, SOCK_STREAM, 0);
  258. ASSERT_LE(0, s);
  259. // PORT + 1 is shared with the SSL redirect tests and with
  260. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  261. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  262. // because that happens on a worker thread the ASSERT does not stop the
  263. // test: it runs on and fails at the disconnected_svr_sock check instead.
  264. default_socket_options(s);
  265. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  266. ASSERT_EQ(0, listen(s, 1));
  267. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  268. ASSERT_EQ(0, close(s));
  269. }};
  270. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  271. std::thread cli{[&] {
  272. const int s = socket(AF_INET, SOCK_STREAM, 0);
  273. ASSERT_LE(0, s);
  274. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  275. ASSERT_EQ(0, close(s));
  276. }};
  277. cli.join();
  278. svr.join();
  279. ASSERT_NE(disconnected_svr_sock, -1);
  280. const auto asSocketStream = [&](socket_t fd,
  281. std::function<bool(Stream &)> func) {
  282. return detail::process_client_socket(
  283. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  284. };
  285. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  286. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  287. // wait_writable() returns true because select_write() only checks if the
  288. // send buffer has space. Peer disconnection is detected later by send().
  289. EXPECT_TRUE(ss.wait_writable());
  290. return true;
  291. });
  292. ASSERT_EQ(0, close(disconnected_svr_sock));
  293. }
  294. #endif // #ifndef _WIN32
  295. TEST(SetSocketOptTest, TcpNoDelay) {
  296. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  297. ASSERT_NE(sock, INVALID_SOCKET);
  298. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  299. int val = 0;
  300. socklen_t len = sizeof(val);
  301. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  302. reinterpret_cast<char *>(&val), &len));
  303. EXPECT_NE(val, 0);
  304. detail::close_socket(sock);
  305. }
  306. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  307. // accept() reports failures through WSAGetLastError() on Windows and through
  308. // errno everywhere else. Asking the wrong one is what made the accept loop
  309. // treat every recoverable failure as fatal on Windows.
  310. struct Classification {
  311. bool resource;
  312. bool transient;
  313. };
  314. auto classify = [](int err) {
  315. #ifdef _WIN32
  316. WSASetLastError(err);
  317. #else
  318. errno = err;
  319. #endif
  320. // Read both before asserting: an assertion may clobber the error slot.
  321. Classification c;
  322. c.resource = detail::is_accept_resource_error();
  323. c.transient = detail::is_accept_transient_error();
  324. return c;
  325. };
  326. #ifdef _WIN32
  327. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  328. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  329. WSAECONNRESET, WSAECONNABORTED};
  330. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  331. #else
  332. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  333. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  334. ECONNABORTED};
  335. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  336. #endif
  337. for (auto err : resource_errors) {
  338. const auto c = classify(err);
  339. EXPECT_TRUE(c.resource) << "error " << err;
  340. EXPECT_FALSE(c.transient) << "error " << err;
  341. }
  342. for (auto err : transient_errors) {
  343. const auto c = classify(err);
  344. EXPECT_TRUE(c.transient) << "error " << err;
  345. EXPECT_FALSE(c.resource) << "error " << err;
  346. }
  347. for (auto err : fatal_errors) {
  348. const auto c = classify(err);
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. EXPECT_FALSE(c.transient) << "error " << err;
  351. }
  352. #ifdef _WIN32
  353. WSASetLastError(0);
  354. #else
  355. errno = 0;
  356. #endif
  357. }
  358. TEST(ClientTest, MoveConstructible) {
  359. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  360. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  361. }
  362. TEST(ClientTest, MoveAssignable) {
  363. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  365. }
  366. #ifdef _WIN32
  367. TEST(StartupTest, WSAStartup) {
  368. WSADATA wsaData;
  369. int ret = WSAStartup(0x0002, &wsaData);
  370. ASSERT_EQ(0, ret);
  371. }
  372. #endif
  373. TEST(DecodePathTest, PercentCharacter) {
  374. EXPECT_EQ(
  375. decode_path_component(
  376. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  377. U8("descrip=Gastos áéíóúñÑ 6"));
  378. }
  379. TEST(DecodePathTest, PercentCharacterNUL) {
  380. string expected;
  381. expected.push_back('x');
  382. expected.push_back('\0');
  383. expected.push_back('x');
  384. EXPECT_EQ(decode_path_component("x%00x"), expected);
  385. }
  386. TEST(DecodePathTest, UnicodeEncoding) {
  387. // %u0041 = 'A' (1-byte UTF-8)
  388. EXPECT_EQ("A", decode_path_component("%u0041"));
  389. // %u00E9 = 'é' (2-byte UTF-8)
  390. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  391. // %u3042 = 'あ' (3-byte UTF-8)
  392. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  393. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  394. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  395. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  396. // neighbours)
  397. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  398. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  399. }
  400. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  401. // A sign or whitespace inside the two-character escape window must not be
  402. // accepted as a valid percent-encoding; the sequence is passed through
  403. // literally, matching decode_uri_component / decode_path_component.
  404. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  405. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  406. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  407. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  408. // Well-formed escapes still decode.
  409. EXPECT_EQ("-", decode_query_component("%2D", false));
  410. EXPECT_EQ("A", decode_query_component("%41", false));
  411. }
  412. TEST(SanitizeFilenameTest, VariousPatterns) {
  413. // Path traversal
  414. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  415. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  416. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  417. // Normal and edge cases
  418. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  419. EXPECT_EQ("filename.txt",
  420. httplib::sanitize_filename("/path/to/filename.txt"));
  421. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  422. EXPECT_EQ("", httplib::sanitize_filename(".."));
  423. EXPECT_EQ("", httplib::sanitize_filename(""));
  424. // Null bytes stripped
  425. EXPECT_EQ("safe.txt",
  426. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  427. // Whitespace-only rejected
  428. EXPECT_EQ("", httplib::sanitize_filename(" "));
  429. }
  430. // Forward declaration (see the base64_encode note below): split builds move the
  431. // definition into httplib.cc, so re-declaring it here lets the test link.
  432. namespace httplib {
  433. namespace detail {
  434. bool is_chunked_transfer_encoding(const Headers &headers);
  435. } // namespace detail
  436. } // namespace httplib
  437. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  438. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  439. auto make = [](std::initializer_list<const char *> lines) {
  440. Headers h;
  441. for (auto te : lines) {
  442. if (te) { h.emplace("Transfer-Encoding", te); }
  443. }
  444. return h;
  445. };
  446. // Sole coding, matched case-insensitively.
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  450. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  454. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  457. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  458. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  459. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  460. // were received, into one list. Headers preserves that order, so the answer
  461. // is decided by the last coding of the last line and the order the lines
  462. // arrived in is significant.
  463. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  464. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  465. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  466. // The split can fall anywhere in the list.
  467. EXPECT_TRUE(
  468. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  469. EXPECT_FALSE(
  470. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  471. // A trailing line naming no coding leaves the list ending in nothing, so it
  472. // must not inherit the chunked from the line before it.
  473. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  474. }
  475. // Forward declarations (see the base64_encode note below).
  476. namespace httplib {
  477. namespace detail {
  478. bool parse_status_line(const char *line, std::string &version, int &status,
  479. std::string &reason);
  480. std::string file_extension(const std::string &path);
  481. std::string
  482. find_content_type(const std::string &path,
  483. const std::map<std::string, std::string> &user_data,
  484. const std::string &default_content_type);
  485. bool can_compress_content_type(const std::string &content_type);
  486. bool is_prohibited_header_name(const std::string &name);
  487. #ifdef CPPHTTPLIB_SSL_ENABLED
  488. bool match_hostname(const std::string &pattern, const std::string &hostname);
  489. #endif
  490. } // namespace detail
  491. } // namespace httplib
  492. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  493. struct {
  494. const char *line;
  495. const char *version;
  496. int status;
  497. const char *reason;
  498. } cases[] = {
  499. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  500. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  501. // The reason phrase may be empty, or left out along with its space.
  502. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  503. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  504. };
  505. for (const auto &c : cases) {
  506. std::string version;
  507. int status = 0;
  508. std::string reason = "unset";
  509. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  510. << c.line;
  511. EXPECT_EQ(c.version, version);
  512. EXPECT_EQ(c.status, status);
  513. EXPECT_EQ(c.reason, reason);
  514. }
  515. }
  516. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  517. const char *lines[] = {
  518. "HTTP/2 200 OK\r\n",
  519. "HTTP/1.2 200 OK\r\n",
  520. "HTTP/1.1 20 OK\r\n",
  521. "HTTP/1.1 2000 OK\r\n",
  522. "HTTP/1.1 2x0 OK\r\n",
  523. "HTTP/1.1 200 OK\r\n",
  524. "HTTP/1.1 200OK\r\n",
  525. "HTTP/1.1 200 O\rK\r\n",
  526. "HTTP/1.1 200 OK",
  527. "HTTP/1.1 200 OK\r\nX",
  528. "",
  529. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  530. "HTTP/1.1 200 OK\n",
  531. #endif
  532. };
  533. for (auto line : lines) {
  534. std::string version;
  535. int status = 0;
  536. std::string reason;
  537. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  538. << line;
  539. }
  540. }
  541. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  542. // Long enough to overflow the stack when matched with std::regex.
  543. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  544. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  545. std::string version;
  546. int status = 0;
  547. std::string reason;
  548. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  549. EXPECT_EQ(200, status);
  550. EXPECT_EQ(long_reason, reason);
  551. }
  552. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  553. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  554. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  555. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  556. EXPECT_EQ("", detail::file_extension("noext"));
  557. EXPECT_EQ("", detail::file_extension("a."));
  558. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  559. EXPECT_EQ("", detail::file_extension("a.b-c"));
  560. // Long enough to overflow the stack when matched with std::regex.
  561. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  562. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  563. }
  564. #ifdef CPPHTTPLIB_SSL_ENABLED
  565. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  566. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  567. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  568. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  569. // A wildcard needs two labels after it, in the leftmost label only
  570. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  571. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  572. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  573. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  574. EXPECT_FALSE(
  575. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  576. // No name may have an empty label
  577. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  578. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  579. }
  580. #endif
  581. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  582. detail::case_ignore::hash hash;
  583. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  584. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  585. // Long enough to overflow the stack if hashed one call per character.
  586. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  587. }
  588. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  589. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  590. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  591. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  592. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  593. // Same 26-bit hash as html, svg and js.
  594. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  595. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  596. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  597. }
  598. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  599. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  600. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  601. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  602. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  603. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  604. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  605. // Same 26-bit hash as application/json.
  606. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  607. }
  608. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  609. Request req;
  610. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  611. EXPECT_TRUE(req.is_multipart_form_data());
  612. std::string boundary;
  613. EXPECT_TRUE(detail::parse_multipart_boundary(
  614. req.get_header_value("Content-Type"), boundary));
  615. EXPECT_EQ("x", boundary);
  616. }
  617. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  618. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  619. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  620. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  621. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  622. // Same 26-bit hash as REMOTE_ADDR.
  623. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  624. }
  625. // Forward declaration: in split builds split.py strips `inline` and moves the
  626. // definition into httplib.cc, so detail::base64_encode is not visible from the
  627. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  628. // in both header-only and split builds.
  629. namespace httplib {
  630. namespace detail {
  631. std::string base64_encode(const std::string &in);
  632. } // namespace detail
  633. } // namespace httplib
  634. TEST(Base64EncodeTest, KnownAnswers) {
  635. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  636. // where the accumulator's top bit is already set before the next shift.
  637. EXPECT_EQ("", detail::base64_encode(""));
  638. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  639. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  640. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  641. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  642. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  643. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  644. // High bytes keep the top bit set across several rounds.
  645. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  646. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  647. }
  648. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  649. string unescapedCharacters = "-_.!~*'()";
  650. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  651. }
  652. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  653. string reservedCharacters = ";,/?:@&=+$";
  654. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  655. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  656. }
  657. TEST(ClientQueryOrder, PreserveOrder) {
  658. // This test reproduces Issue #2259: client may reorder query parameters
  659. // when sending a GET request. The expected behavior is that the client
  660. // preserves the original query string order when the caller supplied it
  661. // as part of the path.
  662. Server svr;
  663. svr.Get("/", [&](const Request &req, Response &res) {
  664. // Echo back the raw target so the test can assert ordering
  665. res.set_content(req.target, "text/plain");
  666. });
  667. std::thread t{[&] { svr.listen(HOST, PORT); }};
  668. auto se = detail::scope_exit([&] {
  669. svr.stop();
  670. t.join();
  671. ASSERT_FALSE(svr.is_running());
  672. });
  673. svr.wait_until_ready();
  674. Client cli(HOST, PORT);
  675. ASSERT_TRUE(cli.is_valid());
  676. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  677. auto res = cli.Get(original);
  678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  679. // Expect the echoed target to exactly match the original path (order
  680. // preserved)
  681. EXPECT_EQ(res->body, original);
  682. }
  683. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  684. string chineseCharacters = U8("中国語");
  685. string russianCharacters = U8("дом");
  686. string brazilianCharacters = U8("óculos");
  687. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  688. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  689. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  690. "%D0%B4%D0%BE%D0%BC");
  691. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  692. }
  693. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  694. string unescapedCharacters = "-_.!~*'()";
  695. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  696. }
  697. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  698. string reservedCharacters = ";,/?:@&=+$";
  699. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  700. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  701. }
  702. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  703. string chineseCharacters = U8("中国語");
  704. string russianCharacters = U8("дом");
  705. string brazilianCharacters = U8("óculos");
  706. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  707. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  708. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  709. "%D0%B4%D0%BE%D0%BC");
  710. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  711. }
  712. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  713. // Issue #2082 use case: encoding path component with ampersand
  714. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  715. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  716. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  717. }
  718. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  719. string unescapedCharacters = "-_.!~*'()";
  720. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  721. }
  722. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  723. string reservedCharacters = ";,/?:@&=+$#";
  724. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  725. }
  726. TEST(EncodeUriTest, TestUTF8Characters) {
  727. string chineseCharacters = U8("中国語");
  728. string russianCharacters = U8("дом");
  729. string brazilianCharacters = U8("óculos");
  730. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  731. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  732. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  733. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  734. }
  735. TEST(EncodeUriTest, TestCompleteUri) {
  736. string uri =
  737. "https://example.com/path/to/resource?query=value&param=test#fragment";
  738. EXPECT_EQ(
  739. httplib::encode_uri(uri),
  740. "https://example.com/path/to/resource?query=value&param=test#fragment");
  741. }
  742. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  743. string uri =
  744. "https://example.com/path with spaces/file name.html?q=hello world";
  745. EXPECT_EQ(httplib::encode_uri(uri),
  746. "https://example.com/path%20with%20spaces/"
  747. "file%20name.html?q=hello%20world");
  748. }
  749. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  750. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  751. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  752. }
  753. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  754. string unescapedCharacters = "-_.!~*'()";
  755. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  756. }
  757. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  758. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  759. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  760. string encodedBrazilian = "%C3%B3culos";
  761. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  762. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  763. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  764. }
  765. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  766. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  767. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  768. "Piri Tommy Villiers - on & on");
  769. }
  770. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  771. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  772. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  773. }
  774. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  775. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  776. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  777. }
  778. TEST(DecodeUriTest, TestUTF8Characters) {
  779. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  780. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  781. string encodedBrazilian = "%C3%B3culos";
  782. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  783. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  784. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  785. }
  786. TEST(DecodeUriTest, TestCompleteUri) {
  787. string encodedUri = "https://example.com/path%20with%20spaces/"
  788. "file%20name.html?q=hello%20world";
  789. EXPECT_EQ(
  790. httplib::decode_uri(encodedUri),
  791. "https://example.com/path with spaces/file name.html?q=hello world");
  792. }
  793. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  794. string original =
  795. "https://example.com/path with spaces/file name.html?q=hello world";
  796. string encoded = httplib::encode_uri(original);
  797. string decoded = httplib::decode_uri(encoded);
  798. EXPECT_EQ(decoded, original);
  799. }
  800. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  801. // decode_uri is the inverse of encode_uri: an escaped reserved character
  802. // stays encoded so it is not promoted into a real delimiter, while
  803. // non-reserved escapes still decode (like JS decodeURI).
  804. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  805. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  806. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  807. "%3F%3A%40%26%3D%2B%24%2C%3B");
  808. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  809. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  810. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  811. "http://example.com/a%2Fb");
  812. // decode_uri_component still decodes the reserved character.
  813. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  814. }
  815. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  816. string original = "Piri Tommy Villiers - on & on";
  817. string encoded = httplib::encode_uri_component(original);
  818. string decoded = httplib::decode_uri_component(encoded);
  819. EXPECT_EQ(decoded, original);
  820. }
  821. TEST(TrimTests, TrimStringTests) {
  822. EXPECT_EQ("abc", detail::trim_copy("abc"));
  823. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  824. EXPECT_TRUE(detail::trim_copy("").empty());
  825. }
  826. TEST(AsciiTest, LocaleIndependentClassification) {
  827. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  828. // which consult the global C locale: std::isalnum(0xC5) can return true
  829. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  830. // helpers must classify every byte by the ASCII grammar alone.
  831. for (int i = 0; i < 256; i++) {
  832. auto c = static_cast<char>(i);
  833. auto is_digit = i >= '0' && i <= '9';
  834. auto is_upper = i >= 'A' && i <= 'Z';
  835. auto is_lower = i >= 'a' && i <= 'z';
  836. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  837. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  838. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  839. << "byte " << i;
  840. }
  841. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  842. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  843. // Non-ASCII bytes must be percent-encoded, never passed through as
  844. // alphanumeric.
  845. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  846. }
  847. TEST(FromCharsTest, Double) {
  848. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  849. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  850. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  851. auto parse = [](const std::string &s, double &v) {
  852. return detail::from_chars(s.data(), s.data() + s.size(), v);
  853. };
  854. double v = -1.0;
  855. // Representative quality values.
  856. EXPECT_EQ(parse("0", v).ec, std::errc{});
  857. EXPECT_DOUBLE_EQ(v, 0.0);
  858. EXPECT_EQ(parse("1", v).ec, std::errc{});
  859. EXPECT_DOUBLE_EQ(v, 1.0);
  860. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  861. EXPECT_DOUBLE_EQ(v, 0.8);
  862. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  863. EXPECT_DOUBLE_EQ(v, 0.001);
  864. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  865. EXPECT_DOUBLE_EQ(v, 1.0);
  866. // A missing integer or fractional part is tolerated.
  867. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  868. EXPECT_DOUBLE_EQ(v, 0.5);
  869. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  870. EXPECT_DOUBLE_EQ(v, 5.0);
  871. // Values outside [0, 1] still parse; the caller range-checks them.
  872. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  873. EXPECT_DOUBLE_EQ(v, 123.456);
  874. // Stops at the first byte that is not part of the number and reports where.
  875. std::string trailing = "0.9, text/html";
  876. auto r = parse(trailing, v);
  877. EXPECT_EQ(r.ec, std::errc{});
  878. EXPECT_DOUBLE_EQ(v, 0.9);
  879. EXPECT_EQ(*r.ptr, ',');
  880. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  881. // outright, and an 'e'/'E' simply ends the number.
  882. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  883. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  884. std::string exp_input = "1.5e3";
  885. r = parse(exp_input, v);
  886. EXPECT_EQ(r.ec, std::errc{});
  887. EXPECT_DOUBLE_EQ(v, 1.5);
  888. EXPECT_EQ(*r.ptr, 'e');
  889. // Invalid inputs.
  890. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  891. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  892. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  893. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  894. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  895. // Pathological but well-formed inputs must stay bounded (no overflow, no
  896. // out-of-bounds table access) and stay within [0, 1] for the caller.
  897. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  898. std::errc{});
  899. EXPECT_DOUBLE_EQ(v, 0.0);
  900. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  901. std::errc{});
  902. EXPECT_GE(v, 0.0);
  903. EXPECT_LE(v, 1.0);
  904. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  905. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  906. }
  907. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  908. // Simple case without quality values
  909. std::vector<std::string> result1;
  910. EXPECT_TRUE(detail::parse_accept_header(
  911. "text/html,application/json,text/plain", result1));
  912. EXPECT_EQ(result1.size(), 3U);
  913. EXPECT_EQ(result1[0], "text/html");
  914. EXPECT_EQ(result1[1], "application/json");
  915. EXPECT_EQ(result1[2], "text/plain");
  916. // With quality values
  917. std::vector<std::string> result2;
  918. EXPECT_TRUE(detail::parse_accept_header(
  919. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  920. EXPECT_EQ(result2.size(), 3U);
  921. EXPECT_EQ(result2[0], "application/json"); // highest q value
  922. EXPECT_EQ(result2[1], "text/html");
  923. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  924. }
  925. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  926. // Mixed with and without quality values
  927. std::vector<std::string> result;
  928. EXPECT_TRUE(detail::parse_accept_header(
  929. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  930. EXPECT_EQ(result.size(), 3U);
  931. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  932. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  933. EXPECT_EQ(result[2], "application/json"); // q=0.5
  934. }
  935. TEST(ParseAcceptHeaderTest, EdgeCases) {
  936. // Empty header
  937. std::vector<std::string> empty_result;
  938. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  939. EXPECT_TRUE(empty_result.empty());
  940. // Single type
  941. std::vector<std::string> single_result;
  942. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  943. EXPECT_EQ(single_result.size(), 1U);
  944. EXPECT_EQ(single_result[0], "application/json");
  945. // Wildcard types
  946. std::vector<std::string> wildcard_result;
  947. EXPECT_TRUE(detail::parse_accept_header(
  948. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  949. EXPECT_EQ(wildcard_result.size(), 3U);
  950. EXPECT_EQ(wildcard_result[0], "application/json");
  951. EXPECT_EQ(wildcard_result[1], "text/*");
  952. EXPECT_EQ(wildcard_result[2], "*/*");
  953. }
  954. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  955. // Common browser Accept header
  956. std::vector<std::string> browser_result;
  957. EXPECT_TRUE(
  958. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  959. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  960. browser_result));
  961. EXPECT_EQ(browser_result.size(), 6U);
  962. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  963. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  964. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  965. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  966. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  967. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  968. // API client header
  969. std::vector<std::string> api_result;
  970. EXPECT_TRUE(detail::parse_accept_header(
  971. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  972. api_result));
  973. EXPECT_EQ(api_result.size(), 3U);
  974. EXPECT_EQ(api_result[0], "application/json");
  975. EXPECT_EQ(api_result[1], "application/xml");
  976. EXPECT_EQ(api_result[2], "text/plain");
  977. }
  978. TEST(ParseAcceptHeaderTest, SpecialCases) {
  979. // Quality value with 3 decimal places
  980. std::vector<std::string> decimal_result;
  981. EXPECT_TRUE(detail::parse_accept_header(
  982. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  983. EXPECT_EQ(decimal_result.size(), 2U);
  984. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  985. EXPECT_EQ(decimal_result[1], "text/html");
  986. // Zero quality (should still be included but with lowest priority)
  987. std::vector<std::string> zero_q_result;
  988. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  989. zero_q_result));
  990. EXPECT_EQ(zero_q_result.size(), 2U);
  991. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  992. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  993. // No spaces around commas
  994. std::vector<std::string> no_space_result;
  995. EXPECT_TRUE(detail::parse_accept_header(
  996. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  997. no_space_result));
  998. EXPECT_EQ(no_space_result.size(), 3U);
  999. EXPECT_EQ(no_space_result[0], "text/html");
  1000. EXPECT_EQ(no_space_result[1], "application/json");
  1001. EXPECT_EQ(no_space_result[2], "text/plain");
  1002. }
  1003. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1004. // Quality values always use '.' as the decimal separator, so parsing must
  1005. // not depend on the process locale. An embedding application may have
  1006. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1007. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1008. std::string saved = cur ? cur : "C";
  1009. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1010. "fr_FR.UTF-8"};
  1011. bool switched = false;
  1012. for (const auto loc : comma_locales) {
  1013. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1014. std::localeconv()->decimal_point[0] == ',') {
  1015. switched = true;
  1016. break;
  1017. }
  1018. }
  1019. if (!switched) {
  1020. std::setlocale(LC_NUMERIC, saved.c_str());
  1021. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1022. }
  1023. // The higher-weighted type appears later in the list, so a correct parse
  1024. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1025. // sensitive parse reads both weights as 0 and leaves the original order.
  1026. std::vector<std::string> result;
  1027. EXPECT_TRUE(detail::parse_accept_header(
  1028. "application/json;q=0.1,text/html;q=0.9", result));
  1029. ASSERT_EQ(result.size(), 2U);
  1030. EXPECT_EQ(result[0], "text/html");
  1031. EXPECT_EQ(result[1], "application/json");
  1032. std::setlocale(LC_NUMERIC, saved.c_str());
  1033. }
  1034. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1035. std::vector<std::string> result;
  1036. // Invalid quality value (> 1.0)
  1037. EXPECT_FALSE(
  1038. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1039. // Invalid quality value (< 0.0)
  1040. EXPECT_FALSE(
  1041. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1042. // Invalid quality value (not a number)
  1043. EXPECT_FALSE(detail::parse_accept_header(
  1044. "text/html;q=invalid,application/json", result));
  1045. // A valid numeric prefix does not make the entire quality value valid.
  1046. EXPECT_FALSE(detail::parse_accept_header(
  1047. "text/html;q=0.5junk,application/json", result));
  1048. // Empty quality value
  1049. EXPECT_FALSE(
  1050. detail::parse_accept_header("text/html;q=,application/json", result));
  1051. // Invalid media type format (no slash and not wildcard)
  1052. EXPECT_FALSE(
  1053. detail::parse_accept_header("invalidtype,application/json", result));
  1054. // Valid cases should still work
  1055. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1056. EXPECT_EQ(result.size(), 1U);
  1057. EXPECT_EQ(result[0], "*/*");
  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("text/*", result));
  1062. EXPECT_EQ(result.size(), 1U);
  1063. EXPECT_EQ(result[0], "text/*");
  1064. }
  1065. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1066. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1067. // and must not be answered with 400 Bad Request.
  1068. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1069. struct {
  1070. const char *value;
  1071. std::vector<std::string> expected;
  1072. } cases[] = {
  1073. {",application/json", {"application/json"}},
  1074. {"text/html,", {"text/html"}},
  1075. {"text/html,,*/*", {"text/html", "*/*"}},
  1076. // An empty element may be spelled with whitespace in it
  1077. {"text/html, , application/json", {"text/html", "application/json"}},
  1078. // Nothing but empty elements is an empty list, which means the same
  1079. // thing as no Accept header at all
  1080. {",,,", {}},
  1081. // Quality values still apply across ignored empty elements
  1082. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1083. };
  1084. for (const auto &c : cases) {
  1085. std::vector<std::string> result;
  1086. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1087. << "value: " << c.value;
  1088. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1089. }
  1090. // An invalid entry is still rejected when empty elements surround it
  1091. std::vector<std::string> result;
  1092. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1093. }
  1094. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1095. // or ';' inside one does not end the list element or the parameter. Section
  1096. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1097. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1098. struct {
  1099. const char *value;
  1100. std::vector<std::string> expected;
  1101. } cases[] = {
  1102. {"text/html;profile=\"a,b\",application/json",
  1103. {"text/html", "application/json"}},
  1104. // A "q=" inside a quoted value is not the weight
  1105. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1106. {"text/html", "application/json"}},
  1107. // The weight after a quoted value still applies
  1108. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1109. {"application/json", "text/html"}},
  1110. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1111. {"application/json", "text/html"}},
  1112. {"text/html;profile=\"a\\\"b\",application/json",
  1113. {"text/html", "application/json"}},
  1114. // An escaped backslash does not escape the '"' after it
  1115. {"text/html;profile=\"a\\\\\",application/json",
  1116. {"text/html", "application/json"}},
  1117. };
  1118. for (const auto &c : cases) {
  1119. std::vector<std::string> result;
  1120. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1121. << "value: " << c.value;
  1122. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1123. }
  1124. }
  1125. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1126. Server svr;
  1127. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1128. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1129. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1130. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1131. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1132. res.set_content("ok", "text/plain");
  1133. });
  1134. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1135. EXPECT_TRUE(false);
  1136. res.set_content("bad request", "text/plain");
  1137. });
  1138. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1139. auto se = detail::scope_exit([&] {
  1140. svr.stop();
  1141. listen_thread.join();
  1142. ASSERT_FALSE(svr.is_running());
  1143. });
  1144. svr.wait_until_ready();
  1145. Client cli("localhost", PORT);
  1146. {
  1147. auto res = cli.Get(
  1148. "/accept_ok",
  1149. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1151. EXPECT_EQ(StatusCode::OK_200, res->status);
  1152. }
  1153. {
  1154. auto res = cli.Get("/accept_bad_request",
  1155. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1157. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1158. }
  1159. }
  1160. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1161. Server svr;
  1162. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1163. res.set_content("ok", "text/plain");
  1164. });
  1165. std::atomic<int> start_count{0};
  1166. std::atomic<bool> running_when_called{false};
  1167. svr.set_start_handler([&]() {
  1168. running_when_called = svr.is_running();
  1169. start_count++;
  1170. });
  1171. auto port = svr.bind_to_any_port(HOST);
  1172. std::thread t([&]() { svr.listen_after_bind(); });
  1173. auto se = detail::scope_exit([&] {
  1174. svr.stop();
  1175. t.join();
  1176. ASSERT_FALSE(svr.is_running());
  1177. });
  1178. svr.wait_until_ready();
  1179. // A successful request proves the accept loop is running, which the start
  1180. // handler precedes; so by now the handler must have run exactly once.
  1181. Client cli(HOST, port);
  1182. cli.set_connection_timeout(std::chrono::seconds(5));
  1183. auto res = cli.Get("/");
  1184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1185. EXPECT_EQ(StatusCode::OK_200, res->status);
  1186. EXPECT_EQ(1, start_count.load());
  1187. EXPECT_TRUE(running_when_called.load());
  1188. }
  1189. TEST(DivideTest, DivideStringTests) {
  1190. auto divide = [](const std::string &str, char d) {
  1191. std::string lhs;
  1192. std::string rhs;
  1193. detail::divide(str, d,
  1194. [&](const char *lhs_data, std::size_t lhs_size,
  1195. const char *rhs_data, std::size_t rhs_size) {
  1196. lhs.assign(lhs_data, lhs_size);
  1197. rhs.assign(rhs_data, rhs_size);
  1198. });
  1199. return std::make_pair(std::move(lhs), std::move(rhs));
  1200. };
  1201. {
  1202. const auto res = divide("", '=');
  1203. EXPECT_EQ(res.first, "");
  1204. EXPECT_EQ(res.second, "");
  1205. }
  1206. {
  1207. const auto res = divide("=", '=');
  1208. EXPECT_EQ(res.first, "");
  1209. EXPECT_EQ(res.second, "");
  1210. }
  1211. {
  1212. const auto res = divide(" ", '=');
  1213. EXPECT_EQ(res.first, " ");
  1214. EXPECT_EQ(res.second, "");
  1215. }
  1216. {
  1217. const auto res = divide("a", '=');
  1218. EXPECT_EQ(res.first, "a");
  1219. EXPECT_EQ(res.second, "");
  1220. }
  1221. {
  1222. const auto res = divide("a=", '=');
  1223. EXPECT_EQ(res.first, "a");
  1224. EXPECT_EQ(res.second, "");
  1225. }
  1226. {
  1227. const auto res = divide("=b", '=');
  1228. EXPECT_EQ(res.first, "");
  1229. EXPECT_EQ(res.second, "b");
  1230. }
  1231. {
  1232. const auto res = divide("a=b", '=');
  1233. EXPECT_EQ(res.first, "a");
  1234. EXPECT_EQ(res.second, "b");
  1235. }
  1236. {
  1237. const auto res = divide("a=b=", '=');
  1238. EXPECT_EQ(res.first, "a");
  1239. EXPECT_EQ(res.second, "b=");
  1240. }
  1241. {
  1242. const auto res = divide("a=b=c", '=');
  1243. EXPECT_EQ(res.first, "a");
  1244. EXPECT_EQ(res.second, "b=c");
  1245. }
  1246. }
  1247. TEST(SplitTest, ParseQueryString) {
  1248. string s = "key1=val1&key2=val2&key3=val3";
  1249. Params dic;
  1250. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1251. [&](const char *b, const char *e) {
  1252. string key, val;
  1253. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1254. if (key.empty()) {
  1255. key.assign(b2, e2);
  1256. } else {
  1257. val.assign(b2, e2);
  1258. }
  1259. });
  1260. dic.emplace(key, val);
  1261. });
  1262. EXPECT_EQ("val1", dic.find("key1")->second);
  1263. EXPECT_EQ("val2", dic.find("key2")->second);
  1264. EXPECT_EQ("val3", dic.find("key3")->second);
  1265. }
  1266. TEST(SplitTest, ParseInvalidQueryTests) {
  1267. {
  1268. string s = " ";
  1269. Params dict;
  1270. detail::parse_query_text(s, dict);
  1271. EXPECT_TRUE(dict.empty());
  1272. }
  1273. {
  1274. string s = " = =";
  1275. Params dict;
  1276. detail::parse_query_text(s, dict);
  1277. EXPECT_TRUE(dict.empty());
  1278. }
  1279. }
  1280. TEST(ParseQueryTest, ParseQueryString) {
  1281. {
  1282. std::string s = "key1=val1&key2=val2&key3=val3";
  1283. Params dic;
  1284. detail::parse_query_text(s, dic);
  1285. EXPECT_EQ("val1", dic.find("key1")->second);
  1286. EXPECT_EQ("val2", dic.find("key2")->second);
  1287. EXPECT_EQ("val3", dic.find("key3")->second);
  1288. }
  1289. {
  1290. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1291. Params dic;
  1292. detail::parse_query_text(s, dic);
  1293. EXPECT_EQ("", dic.find("key1")->second);
  1294. EXPECT_EQ("val1", dic.find("key2")->second);
  1295. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1296. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1297. }
  1298. }
  1299. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1300. Params dic;
  1301. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1302. dic.emplace("key1", "val1");
  1303. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1304. dic.emplace("key2", "val2");
  1305. dic.emplace("key3", "val3");
  1306. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1307. }
  1308. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1309. Params params;
  1310. params.emplace("a", "1");
  1311. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1312. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1313. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1314. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1315. // Long enough to overflow the stack when matched with std::regex.
  1316. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1317. EXPECT_EQ("/p?" + long_query + "&a=1",
  1318. append_query_params("/p?" + long_query, params));
  1319. }
  1320. // Joins every entry of a Headers or Params into "key=value " so a whole
  1321. // traversal can be compared in one assertion. Both are instantiations of the
  1322. // same insertion-ordered container, so one helper serves both.
  1323. template <typename Map> static std::string entries_to_string(const Map &m) {
  1324. std::string s;
  1325. for (const auto &entry : m) {
  1326. s += entry.first + "=" + entry.second + " ";
  1327. }
  1328. return s;
  1329. }
  1330. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1331. // Params used to be a std::multimap, which sorted by name and handed the
  1332. // caller's query back alphabetised. A client signing its query string could
  1333. // not reproduce the order it asked for.
  1334. Params dic;
  1335. dic.emplace("zulu", "1");
  1336. dic.emplace("alpha", "2");
  1337. dic.emplace("mike", "3");
  1338. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1339. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1340. }
  1341. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1342. Params dic;
  1343. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1344. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1345. }
  1346. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1347. Request req;
  1348. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1349. req.params);
  1350. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1351. EXPECT_EQ("first", req.get_param_value("tag"));
  1352. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1353. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1354. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1355. EXPECT_EQ("", req.get_param_value("tag", 3));
  1356. }
  1357. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1358. // Params shares its container with Headers, which matches field names
  1359. // case-insensitively. Parameter names must not pick that up.
  1360. Params dic;
  1361. dic.emplace("Key", "upper");
  1362. dic.emplace("key", "lower");
  1363. EXPECT_EQ(2U, dic.size());
  1364. EXPECT_EQ(1U, dic.count("Key"));
  1365. EXPECT_EQ(1U, dic.count("key"));
  1366. EXPECT_EQ("upper", dic.find("Key")->second);
  1367. EXPECT_EQ("lower", dic.find("key")->second);
  1368. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1369. }
  1370. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1371. Server svr;
  1372. std::string order;
  1373. svr.Get("/order", [&](const Request &req, Response &res) {
  1374. order = entries_to_string(req.params);
  1375. res.set_content("ok", "text/plain");
  1376. });
  1377. auto port = svr.bind_to_any_port(HOST);
  1378. thread t = thread([&] { svr.listen_after_bind(); });
  1379. auto se = detail::scope_exit([&] {
  1380. svr.stop();
  1381. t.join();
  1382. ASSERT_FALSE(svr.is_running());
  1383. });
  1384. svr.wait_until_ready();
  1385. Client cli(HOST, port);
  1386. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1387. ASSERT_TRUE(res);
  1388. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1389. }
  1390. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1391. Server svr;
  1392. std::string field_order, file_order;
  1393. svr.Post("/order", [&](const Request &req, Response &res) {
  1394. for (const auto &field : req.form.fields) {
  1395. field_order += field.first + "=" + field.second.content + " ";
  1396. }
  1397. for (const auto &file : req.form.files) {
  1398. file_order += file.first + "=" + file.second.filename + " ";
  1399. }
  1400. res.set_content("ok", "text/plain");
  1401. });
  1402. auto port = svr.bind_to_any_port(HOST);
  1403. thread t = thread([&] { svr.listen_after_bind(); });
  1404. auto se = detail::scope_exit([&] {
  1405. svr.stop();
  1406. t.join();
  1407. ASSERT_FALSE(svr.is_running());
  1408. });
  1409. svr.wait_until_ready();
  1410. UploadFormDataItems items = {
  1411. {"zulu", "1", "", ""},
  1412. {"alpha", "2", "", ""},
  1413. {"mike", "3", "", ""},
  1414. {"zebra", "z", "z.txt", "text/plain"},
  1415. {"apple", "a", "a.txt", "text/plain"},
  1416. };
  1417. Client cli(HOST, port);
  1418. auto res = cli.Post("/order", items);
  1419. ASSERT_TRUE(res);
  1420. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1421. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1422. }
  1423. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1424. Server svr;
  1425. std::vector<std::string> values;
  1426. std::string first, second, out_of_range, order;
  1427. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1428. values = req.form.get_fields("tag");
  1429. first = req.form.get_field("tag", 0);
  1430. second = req.form.get_field("tag", 1);
  1431. out_of_range = req.form.get_field("tag", 2);
  1432. for (const auto &field : req.form.fields) {
  1433. order += field.first + "=" + field.second.content + " ";
  1434. }
  1435. res.set_content("ok", "text/plain");
  1436. });
  1437. auto port = svr.bind_to_any_port(HOST);
  1438. thread t = thread([&] { svr.listen_after_bind(); });
  1439. auto se = detail::scope_exit([&] {
  1440. svr.stop();
  1441. t.join();
  1442. ASSERT_FALSE(svr.is_running());
  1443. });
  1444. svr.wait_until_ready();
  1445. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1446. // not adjacent in the container.
  1447. UploadFormDataItems items = {
  1448. {"tag", "first", "", ""},
  1449. {"other", "x", "", ""},
  1450. {"tag", "second", "", ""},
  1451. };
  1452. Client cli(HOST, port);
  1453. auto res = cli.Post("/repeated", items);
  1454. ASSERT_TRUE(res);
  1455. ASSERT_EQ(2U, values.size());
  1456. EXPECT_EQ("first", values[0]);
  1457. EXPECT_EQ("second", values[1]);
  1458. EXPECT_EQ("first", first);
  1459. EXPECT_EQ("second", second);
  1460. // std::multimap already kept entries sharing a name in insertion order, so
  1461. // everything above passes without this change too. The whole traversal is
  1462. // what tells the two apart: sorting by name would hoist "other" to the front
  1463. // and the two "tag" parts would end up adjacent.
  1464. EXPECT_EQ("tag=first other=x tag=second ", order);
  1465. // Advancing past the last entry of a name used to run off the container;
  1466. // the container's saturating increment makes it return the default instead.
  1467. EXPECT_EQ("", out_of_range);
  1468. }
  1469. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1470. Server svr;
  1471. std::string file_names;
  1472. svr.Post("/upload", [&](const Request &req, Response &res) {
  1473. for (const auto &file : req.form.files) {
  1474. file_names += file.first + "|" + file.second.filename + " ";
  1475. }
  1476. res.set_content("ok", "text/plain");
  1477. });
  1478. auto port = svr.bind_to_any_port(HOST);
  1479. thread t = thread([&] { svr.listen_after_bind(); });
  1480. auto se = detail::scope_exit([&] {
  1481. svr.stop();
  1482. t.join();
  1483. ASSERT_FALSE(svr.is_running());
  1484. });
  1485. svr.wait_until_ready();
  1486. // A trailing backslash would otherwise escape the closing quote.
  1487. UploadFormDataItems items = {
  1488. {"dir\\", "x", "a.txt", "text/plain"},
  1489. {"b", "y", "a\\\\b.txt", "text/plain"},
  1490. };
  1491. Client cli(HOST, port);
  1492. auto res = cli.Post("/upload", items);
  1493. ASSERT_TRUE(res);
  1494. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1495. }
  1496. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1497. // Server::read_content() keeps a FormFields::iterator alive across the
  1498. // content callbacks that fill the part it points at. The container is
  1499. // vector-backed, so a later emplace can reallocate and invalidate an older
  1500. // iterator; 64 parts grow the vector through seven reallocations, which
  1501. // checks that every part's content still lands in its own entry.
  1502. const size_t part_count = 64;
  1503. // One formula for both the parts sent and the values expected back, so the
  1504. // two cannot drift apart.
  1505. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1506. auto content_of = [](size_t i) {
  1507. return std::string(64, static_cast<char>('a' + (i % 26)));
  1508. };
  1509. Server svr;
  1510. std::vector<std::pair<std::string, std::string>> received;
  1511. svr.Post("/many", [&](const Request &req, Response &res) {
  1512. for (const auto &field : req.form.fields) {
  1513. received.emplace_back(field.first, field.second.content);
  1514. }
  1515. res.set_content("ok", "text/plain");
  1516. });
  1517. auto port = svr.bind_to_any_port(HOST);
  1518. thread t = thread([&] { svr.listen_after_bind(); });
  1519. auto se = detail::scope_exit([&] {
  1520. svr.stop();
  1521. t.join();
  1522. ASSERT_FALSE(svr.is_running());
  1523. });
  1524. svr.wait_until_ready();
  1525. UploadFormDataItems items;
  1526. for (size_t i = 0; i < part_count; i++) {
  1527. items.push_back({name_of(i), content_of(i), "", ""});
  1528. }
  1529. Client cli(HOST, port);
  1530. auto res = cli.Post("/many", items);
  1531. ASSERT_TRUE(res);
  1532. ASSERT_EQ(part_count, received.size());
  1533. for (size_t i = 0; i < part_count; i++) {
  1534. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1535. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1536. }
  1537. }
  1538. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1539. string content_type = "multipart/form-data; boundary=something";
  1540. string boundary;
  1541. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1542. EXPECT_TRUE(ret);
  1543. EXPECT_EQ(boundary, "something");
  1544. }
  1545. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1546. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1547. string boundary;
  1548. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1549. EXPECT_TRUE(ret);
  1550. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1551. }
  1552. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1553. string content_type =
  1554. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1555. string boundary;
  1556. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1557. EXPECT_TRUE(ret);
  1558. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1559. }
  1560. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1561. string content_type =
  1562. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1563. string boundary;
  1564. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1565. EXPECT_TRUE(ret);
  1566. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1567. }
  1568. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1569. const string boundary(70, 'a');
  1570. string content_type = "multipart/form-data; boundary=" + boundary;
  1571. string parsed;
  1572. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1573. EXPECT_TRUE(ret);
  1574. EXPECT_EQ(parsed, boundary);
  1575. }
  1576. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1577. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1578. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1579. string parsed;
  1580. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1581. EXPECT_FALSE(ret);
  1582. }
  1583. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1584. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1585. // is 72 characters on the wire and still valid.
  1586. const string boundary(70, 'a');
  1587. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1588. string parsed;
  1589. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1590. EXPECT_EQ(parsed, boundary);
  1591. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1592. parsed.clear();
  1593. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1594. }
  1595. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1596. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1597. // The parameter parser must not treat that '=' as the key/value separator.
  1598. string content_type =
  1599. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1600. "charset=UTF-8";
  1601. string parsed;
  1602. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1603. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1604. }
  1605. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1606. // A ';' inside the quoted-string is part of the value, not a parameter
  1607. // separator, so it must not truncate the boundary.
  1608. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1609. string parsed;
  1610. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1611. EXPECT_EQ(parsed, "a;b");
  1612. }
  1613. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1614. string parsed;
  1615. EXPECT_TRUE(detail::parse_multipart_boundary(
  1616. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1617. EXPECT_EQ("a\\b", parsed);
  1618. EXPECT_TRUE(detail::parse_multipart_boundary(
  1619. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1620. EXPECT_EQ("a\"b", parsed);
  1621. }
  1622. TEST(ParseDispositionParamsTest, QuotedValues) {
  1623. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1624. // ';' and '=' are ordinary characters inside one.
  1625. struct {
  1626. const char *value;
  1627. std::vector<std::pair<const char *, const char *>> expected;
  1628. } cases[] = {
  1629. {"name=\"file1\"; filename=\"a.txt\"",
  1630. {{"name", "file1"}, {"filename", "a.txt"}}},
  1631. // Whitespace around '=' and ';' is still trimmed
  1632. {"name=\"file2\" ;filename = \"a.html\"",
  1633. {{"name", "file2"}, {"filename", "a.html"}}},
  1634. // '=' inside the value used to leave only the text after the last one
  1635. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1636. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1637. {"name=\"x=y\"", {{"name", "x=y"}}},
  1638. // ';' inside the value used to truncate the pair and leave a bogus one
  1639. {"name=\"file3\"; filename=\"a;b.txt\"",
  1640. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1641. // An unquoted value keeps working, and so does filename*
  1642. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1643. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1644. // A parameter with no key is dropped rather than turned into one whose
  1645. // key is the value
  1646. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1647. // An escaped quote does not end the value
  1648. {"name=\"a\\\"; filename=evil.php\"",
  1649. {{"name", "a\"; filename=evil.php"}}},
  1650. // Other backslashes, as in a Windows path, are kept
  1651. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1652. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1653. };
  1654. for (const auto &c : cases) {
  1655. Params params;
  1656. detail::parse_disposition_params(c.value, params);
  1657. for (const auto &kv : c.expected) {
  1658. auto it = params.find(kv.first);
  1659. ASSERT_NE(it, params.end())
  1660. << "value: " << c.value << ", key: " << kv.first;
  1661. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1662. }
  1663. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1664. }
  1665. }
  1666. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1667. Server svr;
  1668. std::string filename;
  1669. std::string content;
  1670. svr.Post("/upload", [&](const Request &req, Response &) {
  1671. const auto &file = req.form.get_file("file");
  1672. filename = file.filename;
  1673. content = file.content;
  1674. });
  1675. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1676. auto se = detail::scope_exit([&] {
  1677. svr.stop();
  1678. thread.join();
  1679. ASSERT_FALSE(svr.is_running());
  1680. });
  1681. svr.wait_until_ready();
  1682. std::string body = "--B\r\n"
  1683. "Content-Disposition: form-data; name=\"file\"; "
  1684. "filename=\"a.txt\"\r\n"
  1685. "Content-Type: text/plain\r\n"
  1686. "\r\n"
  1687. "hello\r\n"
  1688. "--B--\r\n";
  1689. Client cli(HOST, PORT);
  1690. auto res = cli.Post(
  1691. "/upload",
  1692. [&](size_t offset, DataSink &sink) {
  1693. if (offset < body.size()) {
  1694. sink.write(&body[offset], 1);
  1695. } else {
  1696. sink.done();
  1697. }
  1698. return true;
  1699. },
  1700. "multipart/form-data; boundary=B");
  1701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1702. EXPECT_EQ(StatusCode::OK_200, res->status);
  1703. EXPECT_EQ("a.txt", filename);
  1704. EXPECT_EQ("hello", content);
  1705. }
  1706. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1707. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1708. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1709. Server svr;
  1710. std::string field_value, file_name, file_filename;
  1711. bool has_field = false, has_file = false;
  1712. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1713. has_field = req.form.has_field("x=y");
  1714. field_value = req.form.get_field("x=y");
  1715. has_file = req.form.has_file("file1");
  1716. const auto &file = req.form.get_file("file1");
  1717. file_name = file.name;
  1718. file_filename = file.filename;
  1719. res.set_content("ok", "text/plain");
  1720. });
  1721. auto port = svr.bind_to_any_port(HOST);
  1722. thread t = thread([&] { svr.listen_after_bind(); });
  1723. auto se = detail::scope_exit([&] {
  1724. svr.stop();
  1725. t.join();
  1726. ASSERT_FALSE(svr.is_running());
  1727. });
  1728. svr.wait_until_ready();
  1729. UploadFormDataItems items = {
  1730. {"x=y", "field-value", "", ""},
  1731. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1732. };
  1733. Client cli(HOST, port);
  1734. auto res = cli.Post("/quoted", items);
  1735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1736. ASSERT_EQ(StatusCode::OK_200, res->status);
  1737. EXPECT_TRUE(has_field);
  1738. EXPECT_EQ("field-value", field_value);
  1739. EXPECT_TRUE(has_file);
  1740. EXPECT_EQ("file1", file_name);
  1741. EXPECT_EQ("a;b=report.pdf", file_filename);
  1742. }
  1743. TEST(GetHeaderValueTest, DefaultValue) {
  1744. Headers headers = {{"Dummy", "Dummy"}};
  1745. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1746. EXPECT_STREQ("text/plain", val);
  1747. }
  1748. TEST(GetHeaderValueTest, DefaultValueInt) {
  1749. Headers headers = {{"Dummy", "Dummy"}};
  1750. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1751. EXPECT_EQ(100ull, val);
  1752. }
  1753. TEST(GetHeaderValueTest, RegularValue) {
  1754. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1755. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1756. EXPECT_STREQ("text/html", val);
  1757. }
  1758. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1759. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1760. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1761. EXPECT_STREQ("text/html", val);
  1762. }
  1763. TEST(GetHeaderValueTest, SetContent) {
  1764. Response res;
  1765. res.set_content("html", "text/html");
  1766. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1767. res.set_content("text", "text/plain");
  1768. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1769. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1770. }
  1771. TEST(GetHeaderValueTest, RegularValueInt) {
  1772. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1773. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1774. EXPECT_EQ(100ull, val);
  1775. }
  1776. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1777. Headers headers = {{"Content-Length", "x"}};
  1778. auto is_invalid_value = false;
  1779. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1780. is_invalid_value);
  1781. EXPECT_EQ(0ull, val);
  1782. EXPECT_TRUE(is_invalid_value);
  1783. }
  1784. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1785. // An all-digit value that overflows size_t must be reported as invalid, not
  1786. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1787. // a large length to a small one on 32-bit builds, leaving the framing length
  1788. // wrong while is_invalid_value stayed false.
  1789. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1790. auto is_invalid_value = false;
  1791. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1792. is_invalid_value);
  1793. EXPECT_TRUE(is_invalid_value);
  1794. // A well-formed length is unaffected.
  1795. Headers ok = {{"Content-Length", "1234"}};
  1796. is_invalid_value = false;
  1797. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1798. is_invalid_value);
  1799. EXPECT_EQ(1234ull, val);
  1800. EXPECT_FALSE(is_invalid_value);
  1801. }
  1802. TEST(GetHeaderValueTest, Range) {
  1803. {
  1804. Headers headers = {make_range_header({{1, -1}})};
  1805. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1806. EXPECT_STREQ("bytes=1-", val);
  1807. }
  1808. {
  1809. Headers headers = {make_range_header({{-1, 1}})};
  1810. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1811. EXPECT_STREQ("bytes=-1", val);
  1812. }
  1813. {
  1814. Headers headers = {make_range_header({{1, 10}})};
  1815. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1816. EXPECT_STREQ("bytes=1-10", val);
  1817. }
  1818. {
  1819. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1820. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1821. EXPECT_STREQ("bytes=1-10, 100-", val);
  1822. }
  1823. {
  1824. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1825. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1826. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1827. }
  1828. {
  1829. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1830. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1831. EXPECT_STREQ("bytes=0-0, -1", val);
  1832. }
  1833. }
  1834. TEST(BearerTokenAuthTest, SchemeValidation) {
  1835. // A value shorter than "Bearer " must not throw from the fixed-length
  1836. // substr, and a non-Bearer scheme must not be reported as a token.
  1837. struct {
  1838. const char *value;
  1839. const char *expected;
  1840. } cases[] = {
  1841. {"x", ""},
  1842. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1843. {"Bearer abc123", "abc123"},
  1844. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1845. };
  1846. for (const auto &c : cases) {
  1847. Request req;
  1848. req.set_header("Authorization", c.value);
  1849. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1850. }
  1851. }
  1852. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1853. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1854. // to depend on the standard library (libstdc++ handed back duplicates in
  1855. // reverse insertion order, libc++ in insertion order).
  1856. Request req;
  1857. req.set_header("Accept-Encoding", "gzip");
  1858. req.set_header("Accept-Encoding", "deflate");
  1859. req.set_header("Accept-Encoding", "br");
  1860. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1861. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1862. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1863. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1864. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1865. }
  1866. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1867. Request req;
  1868. req.set_header("X-Test", "only");
  1869. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1870. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1871. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1872. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1873. }
  1874. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1875. Request req;
  1876. req.set_header("X-First", "1");
  1877. req.set_header("X-Test", "2");
  1878. req.params.emplace("first", "1");
  1879. req.params.emplace("test", "2");
  1880. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1881. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1882. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1883. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1884. // The second one is negative when read as a signed value
  1885. const auto max_id = (std::numeric_limits<size_t>::max)();
  1886. for (auto id : {max_id / 2, max_id}) {
  1887. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1888. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1889. EXPECT_EQ("", req.get_param_value("test", id));
  1890. EXPECT_EQ("", req.form.get_field("test", id));
  1891. EXPECT_EQ("", req.form.get_file("test", id).content);
  1892. }
  1893. }
  1894. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1895. Headers headers;
  1896. headers.emplace("Host", "example.com");
  1897. headers.emplace("Accept-Encoding", "gzip");
  1898. headers.emplace("User-Agent", "test");
  1899. headers.emplace("Accept-Encoding", "deflate");
  1900. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1901. "Accept-Encoding=deflate ",
  1902. entries_to_string(headers));
  1903. }
  1904. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1905. Headers headers = {{"Content-Type", "text/html"},
  1906. {"CONTENT-TYPE", "text/xml"}};
  1907. EXPECT_EQ(2U, headers.count("content-type"));
  1908. auto it = headers.find("content-type");
  1909. ASSERT_TRUE(it != headers.end());
  1910. EXPECT_EQ("text/html", it->second);
  1911. }
  1912. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1913. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1914. // drop only those fields and leave everything positioned between them.
  1915. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1916. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1917. auto rng = headers.equal_range("a");
  1918. headers.erase(rng.first, rng.second);
  1919. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1920. }
  1921. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1922. Headers headers = {
  1923. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1924. EXPECT_EQ(3U, headers.erase("A"));
  1925. EXPECT_EQ(0U, headers.count("A"));
  1926. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1927. }
  1928. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1929. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1930. headers.emplace_front("Host", "example.com");
  1931. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1932. entries_to_string(headers));
  1933. }
  1934. TEST(ParseHeaderValueTest, Range) {
  1935. {
  1936. Ranges ranges;
  1937. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1938. EXPECT_TRUE(ret);
  1939. EXPECT_EQ(1u, ranges.size());
  1940. EXPECT_EQ(1u, ranges[0].first);
  1941. EXPECT_EQ(-1, ranges[0].second);
  1942. }
  1943. {
  1944. Ranges ranges;
  1945. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1946. EXPECT_TRUE(ret);
  1947. EXPECT_EQ(1u, ranges.size());
  1948. EXPECT_EQ(-1, ranges[0].first);
  1949. EXPECT_EQ(1u, ranges[0].second);
  1950. }
  1951. {
  1952. Ranges ranges;
  1953. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1954. EXPECT_TRUE(ret);
  1955. EXPECT_EQ(1u, ranges.size());
  1956. EXPECT_EQ(1u, ranges[0].first);
  1957. EXPECT_EQ(10u, ranges[0].second);
  1958. }
  1959. {
  1960. Ranges ranges;
  1961. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1962. EXPECT_FALSE(ret);
  1963. }
  1964. {
  1965. Ranges ranges;
  1966. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1967. EXPECT_TRUE(ret);
  1968. EXPECT_EQ(2u, ranges.size());
  1969. EXPECT_EQ(1u, ranges[0].first);
  1970. EXPECT_EQ(10u, ranges[0].second);
  1971. EXPECT_EQ(100u, ranges[1].first);
  1972. EXPECT_EQ(-1, ranges[1].second);
  1973. }
  1974. {
  1975. Ranges ranges;
  1976. auto ret =
  1977. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1978. EXPECT_TRUE(ret);
  1979. EXPECT_EQ(3u, ranges.size());
  1980. EXPECT_EQ(1u, ranges[0].first);
  1981. EXPECT_EQ(10u, ranges[0].second);
  1982. EXPECT_EQ(100u, ranges[1].first);
  1983. EXPECT_EQ(200u, ranges[1].second);
  1984. EXPECT_EQ(300u, ranges[2].first);
  1985. EXPECT_EQ(400u, ranges[2].second);
  1986. }
  1987. {
  1988. Ranges ranges;
  1989. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1990. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1991. EXPECT_FALSE(detail::parse_range_header("bytes=0", 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=,", 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=a-b", ranges));
  1998. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1999. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2000. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2001. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2002. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2003. EXPECT_FALSE(
  2004. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2005. EXPECT_TRUE(ranges.empty());
  2006. }
  2007. {
  2008. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2009. // remainder of the representation, so it stays accepted.
  2010. Ranges ranges;
  2011. auto ret =
  2012. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2013. EXPECT_TRUE(ret);
  2014. ASSERT_EQ(1u, ranges.size());
  2015. EXPECT_EQ(0, ranges[0].first);
  2016. EXPECT_EQ(-1, ranges[0].second);
  2017. }
  2018. // RFC 9110 14.1: range unit names are case-insensitive.
  2019. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2020. Ranges ranges;
  2021. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2022. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2023. }
  2024. }
  2025. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2026. Request req;
  2027. req.set_header("Accept-Encoding", "gzip");
  2028. Response res;
  2029. res.set_header("Content-Type", "text/plain");
  2030. auto ret = detail::encoding_type(req, res);
  2031. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2032. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2033. #else
  2034. EXPECT_TRUE(ret == detail::EncodingType::None);
  2035. #endif
  2036. }
  2037. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2038. Request req;
  2039. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2040. Response res;
  2041. res.set_header("Content-Type", "text/plain");
  2042. auto ret = detail::encoding_type(req, res);
  2043. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2044. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2045. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2046. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2047. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2048. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2049. #else
  2050. EXPECT_TRUE(ret == detail::EncodingType::None);
  2051. #endif
  2052. }
  2053. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2054. Request req;
  2055. req.set_header("Accept-Encoding",
  2056. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2057. Response res;
  2058. res.set_header("Content-Type", "text/plain");
  2059. auto ret = detail::encoding_type(req, res);
  2060. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2061. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2062. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2063. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2064. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2065. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2066. #else
  2067. EXPECT_TRUE(ret == detail::EncodingType::None);
  2068. #endif
  2069. }
  2070. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2071. // All supported encodings rejected with q=0 should return None
  2072. Request req;
  2073. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2074. Response res;
  2075. res.set_header("Content-Type", "text/plain");
  2076. auto ret = detail::encoding_type(req, res);
  2077. EXPECT_TRUE(ret == detail::EncodingType::None);
  2078. }
  2079. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2080. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2081. Request req;
  2082. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2083. Response res;
  2084. res.set_header("Content-Type", "text/plain");
  2085. auto ret = detail::encoding_type(req, res);
  2086. EXPECT_TRUE(ret == detail::EncodingType::None);
  2087. }
  2088. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2089. Request req;
  2090. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2091. Response res;
  2092. res.set_header("Content-Type", "text/plain");
  2093. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2094. }
  2095. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2096. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2097. Request req;
  2098. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2099. Response res;
  2100. res.set_header("Content-Type", "text/plain");
  2101. auto ret = detail::encoding_type(req, res);
  2102. EXPECT_TRUE(ret == detail::EncodingType::None);
  2103. }
  2104. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2105. // RFC 7231: Accept-Encoding values are case-insensitive
  2106. Request req;
  2107. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2108. Response res;
  2109. res.set_header("Content-Type", "text/plain");
  2110. auto ret = detail::encoding_type(req, res);
  2111. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2112. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2113. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2114. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2115. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2116. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2117. #else
  2118. EXPECT_TRUE(ret == detail::EncodingType::None);
  2119. #endif
  2120. }
  2121. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2122. // q value should determine priority, not hardcoded order
  2123. Request req;
  2124. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2125. Response res;
  2126. res.set_header("Content-Type", "text/plain");
  2127. auto ret = detail::encoding_type(req, res);
  2128. // gzip has highest q=1.0, so it should be selected even though
  2129. // br and zstd are also supported
  2130. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2131. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2132. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2133. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2134. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2135. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2136. #else
  2137. EXPECT_TRUE(ret == detail::EncodingType::None);
  2138. #endif
  2139. }
  2140. TEST(BufferStreamTest, read) {
  2141. detail::BufferStream strm1;
  2142. Stream &strm = strm1;
  2143. EXPECT_EQ(5, strm.write("hello"));
  2144. char buf[512];
  2145. EXPECT_EQ(2, strm.read(buf, 2));
  2146. EXPECT_EQ('h', buf[0]);
  2147. EXPECT_EQ('e', buf[1]);
  2148. EXPECT_EQ(2, strm.read(buf, 2));
  2149. EXPECT_EQ('l', buf[0]);
  2150. EXPECT_EQ('l', buf[1]);
  2151. EXPECT_EQ(1, strm.read(buf, 1));
  2152. EXPECT_EQ('o', buf[0]);
  2153. EXPECT_EQ(0, strm.read(buf, 1));
  2154. }
  2155. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2156. auto host = "www.httpwatch.com";
  2157. auto ip = hosted_at(host);
  2158. EXPECT_EQ("23.96.13.243", ip);
  2159. std::vector<std::string> addrs;
  2160. hosted_at(host, addrs);
  2161. EXPECT_EQ(1u, addrs.size());
  2162. }
  2163. #if 0 // It depends on each test environment...
  2164. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2165. auto host = "www.youtube.com";
  2166. std::vector<std::string> addrs;
  2167. hosted_at(host, addrs);
  2168. EXPECT_EQ(20u, addrs.size());
  2169. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2170. EXPECT_TRUE(it != addrs.end());
  2171. }
  2172. #endif
  2173. class ChunkedEncodingTest : public ::testing::Test {
  2174. protected:
  2175. ChunkedEncodingTest()
  2176. : cli_(HOST, PORT)
  2177. #ifdef CPPHTTPLIB_SSL_ENABLED
  2178. ,
  2179. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2180. #endif
  2181. {
  2182. cli_.set_connection_timeout(2);
  2183. #ifdef CPPHTTPLIB_SSL_ENABLED
  2184. cli_.enable_server_certificate_verification(false);
  2185. #endif
  2186. }
  2187. virtual void SetUp() {
  2188. read_file("./image.jpg", image_data_);
  2189. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2190. res.set_content("Hello World!", "text/plain");
  2191. });
  2192. svr_.Get(
  2193. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2194. res.set_chunked_content_provider(
  2195. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2196. size_t remaining = image_data_.size() - offset;
  2197. if (remaining == 0) {
  2198. sink.done();
  2199. } else {
  2200. constexpr size_t CHUNK_SIZE = 1024;
  2201. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2202. sink.write(&image_data_[offset], send_size);
  2203. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2204. }
  2205. return true;
  2206. });
  2207. });
  2208. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2209. svr_.wait_until_ready();
  2210. }
  2211. virtual void TearDown() {
  2212. svr_.stop();
  2213. if (!request_threads_.empty()) {
  2214. std::this_thread::sleep_for(std::chrono::seconds(1));
  2215. for (auto &t : request_threads_) {
  2216. t.join();
  2217. }
  2218. }
  2219. t_.join();
  2220. }
  2221. #ifdef CPPHTTPLIB_SSL_ENABLED
  2222. SSLClient cli_;
  2223. SSLServer svr_;
  2224. #else
  2225. Client cli_;
  2226. Server svr_;
  2227. #endif
  2228. thread t_;
  2229. std::vector<thread> request_threads_;
  2230. std::string image_data_;
  2231. };
  2232. TEST_F(ChunkedEncodingTest, NormalGet) {
  2233. auto res = cli_.Get("/chunked");
  2234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2235. std::string out;
  2236. read_file("./image.jpg", out);
  2237. EXPECT_EQ(StatusCode::OK_200, res->status);
  2238. EXPECT_EQ(out, res->body);
  2239. }
  2240. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2241. std::string body;
  2242. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2243. body.append(data, data_length);
  2244. return true;
  2245. });
  2246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2247. std::string out;
  2248. read_file("./image.jpg", out);
  2249. EXPECT_EQ(StatusCode::OK_200, res->status);
  2250. EXPECT_EQ(out, body);
  2251. }
  2252. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2253. std::string body;
  2254. auto res = cli_.Get(
  2255. "/chunked",
  2256. [&](const Response &response) {
  2257. EXPECT_EQ(StatusCode::OK_200, response.status);
  2258. return true;
  2259. },
  2260. [&](const char *data, size_t data_length) {
  2261. body.append(data, data_length);
  2262. return true;
  2263. });
  2264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2265. std::string out;
  2266. read_file("./image.jpg", out);
  2267. EXPECT_EQ(StatusCode::OK_200, res->status);
  2268. EXPECT_EQ(out, body);
  2269. }
  2270. TEST(RangeTest, FromHTTPBin_Online) {
  2271. auto host = "httpbingo.org";
  2272. auto path = std::string{"/range/32"};
  2273. #ifdef CPPHTTPLIB_SSL_ENABLED
  2274. auto port = 443;
  2275. SSLClient cli(host, port);
  2276. #else
  2277. auto port = 80;
  2278. Client cli(host, port);
  2279. #endif
  2280. cli.set_connection_timeout(5);
  2281. {
  2282. auto res = cli.Get(path);
  2283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2284. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2285. EXPECT_EQ(StatusCode::OK_200, res->status);
  2286. }
  2287. {
  2288. Headers headers = {make_range_header({{1, -1}})};
  2289. auto res = cli.Get(path, headers);
  2290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2291. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2292. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2293. }
  2294. {
  2295. Headers headers = {make_range_header({{1, 10}})};
  2296. auto res = cli.Get(path, headers);
  2297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2298. EXPECT_EQ("bcdefghijk", res->body);
  2299. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2300. }
  2301. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2302. // entire resource, while the original httpbin returned 200. Both are
  2303. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2304. {
  2305. Headers headers = {make_range_header({{0, 31}})};
  2306. auto res = cli.Get(path, headers);
  2307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2308. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2309. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2310. res->status == StatusCode::PartialContent_206);
  2311. }
  2312. {
  2313. Headers headers = {make_range_header({{0, -1}})};
  2314. auto res = cli.Get(path, headers);
  2315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2316. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2317. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2318. res->status == StatusCode::PartialContent_206);
  2319. }
  2320. // go-httpbin returns 206 with clamped range for over-range requests,
  2321. // while the original httpbin returned 416. Both behaviors are observed
  2322. // in real servers, so we only verify the request succeeds.
  2323. {
  2324. Headers headers = {make_range_header({{0, 32}})};
  2325. auto res = cli.Get(path, headers);
  2326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2327. }
  2328. }
  2329. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2330. auto host = "unresolvableaddress.local";
  2331. auto path = std::string{"/"};
  2332. #ifdef CPPHTTPLIB_SSL_ENABLED
  2333. auto port = 443;
  2334. SSLClient cli(host, port);
  2335. #else
  2336. auto port = 80;
  2337. Client cli(host, port);
  2338. #endif
  2339. cli.set_connection_timeout(1);
  2340. {
  2341. auto res = cli.Get(path);
  2342. ASSERT_FALSE(res);
  2343. }
  2344. std::this_thread::sleep_for(std::chrono::seconds(8));
  2345. }
  2346. #if defined(__linux__) && defined(__GLIBC__) && \
  2347. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2348. // Forward declaration: in split builds split.py strips `inline` and moves the
  2349. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2350. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2351. // against the symbol in both header-only and split builds.
  2352. namespace httplib {
  2353. namespace detail {
  2354. int getaddrinfo_with_timeout(const char *node, const char *service,
  2355. const struct addrinfo *hints,
  2356. struct addrinfo **res, time_t timeout_sec);
  2357. } // namespace detail
  2358. } // namespace httplib
  2359. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2360. //
  2361. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2362. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2363. // gai_suspend() call hits the connection timeout the function calls
  2364. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2365. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2366. // still alive and still references the now-destroyed stack frame.
  2367. //
  2368. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2369. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2370. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2371. // and runs them in a container.
  2372. namespace {
  2373. bool should_run_issue_2431_tests() {
  2374. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2375. return v && *v && std::string(v) != "0";
  2376. }
  2377. std::string unique_unresolvable_host(int n) {
  2378. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2379. // glibc still asks the configured nameserver — which is exactly the path
  2380. // we want to exercise. A unique label per call avoids the resolver cache.
  2381. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2382. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2383. std::to_string(n) + ".invalid";
  2384. }
  2385. } // namespace
  2386. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2387. if (!should_run_issue_2431_tests()) {
  2388. GTEST_SKIP()
  2389. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2390. }
  2391. for (int i = 0; i < 8; ++i) {
  2392. struct addrinfo hints;
  2393. memset(&hints, 0, sizeof(hints));
  2394. hints.ai_family = AF_UNSPEC;
  2395. hints.ai_socktype = SOCK_STREAM;
  2396. auto host = unique_unresolvable_host(i);
  2397. struct addrinfo *result = nullptr;
  2398. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2399. &result, /*timeout_sec=*/1);
  2400. if (rc == 0 && result) { freeaddrinfo(result); }
  2401. }
  2402. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2403. // stack region they still believe holds their gaicb.
  2404. std::this_thread::sleep_for(std::chrono::seconds(3));
  2405. }
  2406. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2407. if (!should_run_issue_2431_tests()) {
  2408. GTEST_SKIP()
  2409. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2410. }
  2411. std::atomic<bool> stop{false};
  2412. std::vector<std::thread> threads;
  2413. for (int t = 0; t < 8; ++t) {
  2414. threads.emplace_back([t, &stop] {
  2415. int i = 0;
  2416. while (!stop.load(std::memory_order_relaxed)) {
  2417. struct addrinfo hints;
  2418. memset(&hints, 0, sizeof(hints));
  2419. hints.ai_family = AF_UNSPEC;
  2420. hints.ai_socktype = SOCK_STREAM;
  2421. auto host = unique_unresolvable_host(t * 100000 + i++);
  2422. struct addrinfo *result = nullptr;
  2423. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2424. &result, /*timeout_sec=*/1);
  2425. if (rc == 0 && result) { freeaddrinfo(result); }
  2426. }
  2427. });
  2428. }
  2429. std::this_thread::sleep_for(std::chrono::seconds(8));
  2430. stop.store(true, std::memory_order_relaxed);
  2431. for (auto &th : threads) {
  2432. th.join();
  2433. }
  2434. std::this_thread::sleep_for(std::chrono::seconds(3));
  2435. }
  2436. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2437. if (!should_run_issue_2431_tests()) {
  2438. GTEST_SKIP()
  2439. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2440. }
  2441. std::atomic<bool> stop{false};
  2442. std::vector<std::thread> threads;
  2443. for (int t = 0; t < 8; ++t) {
  2444. threads.emplace_back([t, &stop] {
  2445. int i = 0;
  2446. while (!stop.load(std::memory_order_relaxed)) {
  2447. auto host = unique_unresolvable_host(t * 100000 + i++);
  2448. Client cli(host, 80);
  2449. cli.set_connection_timeout(1, 0);
  2450. cli.set_read_timeout(1, 0);
  2451. cli.set_write_timeout(1, 0);
  2452. (void)cli.Get("/");
  2453. }
  2454. });
  2455. }
  2456. std::this_thread::sleep_for(std::chrono::seconds(8));
  2457. stop.store(true, std::memory_order_relaxed);
  2458. for (auto &th : threads) {
  2459. th.join();
  2460. }
  2461. std::this_thread::sleep_for(std::chrono::seconds(3));
  2462. }
  2463. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2464. TEST(ConnectionErrorTest, InvalidHost) {
  2465. auto host = "-abcde.com";
  2466. #ifdef CPPHTTPLIB_SSL_ENABLED
  2467. auto port = 443;
  2468. SSLClient cli(host, port);
  2469. #else
  2470. auto port = 80;
  2471. Client cli(host, port);
  2472. #endif
  2473. cli.set_connection_timeout(std::chrono::seconds(2));
  2474. auto res = cli.Get("/");
  2475. ASSERT_TRUE(!res);
  2476. EXPECT_EQ(Error::Connection, res.error());
  2477. }
  2478. TEST(ConnectionErrorTest, InvalidHost2) {
  2479. auto host = "httpcan.org/";
  2480. #ifdef CPPHTTPLIB_SSL_ENABLED
  2481. SSLClient cli(host);
  2482. #else
  2483. Client cli(host);
  2484. #endif
  2485. cli.set_connection_timeout(std::chrono::seconds(2));
  2486. auto res = cli.Get("/");
  2487. ASSERT_TRUE(!res);
  2488. EXPECT_EQ(Error::Connection, res.error());
  2489. }
  2490. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2491. auto host = "httpcan.org/";
  2492. #ifdef CPPHTTPLIB_SSL_ENABLED
  2493. SSLClient cli(host);
  2494. #else
  2495. Client cli(host);
  2496. #endif
  2497. cli.set_connection_timeout(std::chrono::seconds(2));
  2498. auto res = cli.Get("/");
  2499. ASSERT_TRUE(!res);
  2500. stringstream s;
  2501. s << "error code: " << res.error();
  2502. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2503. }
  2504. TEST(ConnectionErrorTest, InvalidPort) {
  2505. auto host = "localhost";
  2506. auto port = 44380;
  2507. #ifdef CPPHTTPLIB_SSL_ENABLED
  2508. SSLClient cli(host, port);
  2509. #else
  2510. Client cli(host, port);
  2511. #endif
  2512. cli.set_connection_timeout(std::chrono::seconds(2));
  2513. auto res = cli.Get("/");
  2514. ASSERT_TRUE(!res);
  2515. EXPECT_TRUE(Error::Connection == res.error() ||
  2516. Error::ConnectionTimeout == res.error());
  2517. }
  2518. TEST(ConnectionErrorTest, Timeout_Online) {
  2519. auto host = "google.com";
  2520. #ifdef CPPHTTPLIB_SSL_ENABLED
  2521. auto port = 44380;
  2522. SSLClient cli(host, port);
  2523. #else
  2524. auto port = 8080;
  2525. Client cli(host, port);
  2526. #endif
  2527. cli.set_connection_timeout(std::chrono::seconds(2));
  2528. // only probe one address type so that the error reason
  2529. // correlates to the timed-out IPv4, not the unsupported
  2530. // IPv6 connection attempt
  2531. cli.set_address_family(AF_INET);
  2532. auto res = cli.Get("/");
  2533. ASSERT_TRUE(!res);
  2534. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2535. }
  2536. TEST(CancelTest, NoCancel_Online) {
  2537. auto host = "httpbingo.org";
  2538. auto path = std::string{"/range/32"};
  2539. #ifdef CPPHTTPLIB_SSL_ENABLED
  2540. auto port = 443;
  2541. SSLClient cli(host, port);
  2542. #else
  2543. auto port = 80;
  2544. Client cli(host, port);
  2545. #endif
  2546. cli.set_connection_timeout(std::chrono::seconds(5));
  2547. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2549. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2550. EXPECT_EQ(StatusCode::OK_200, res->status);
  2551. }
  2552. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2553. // Use /bytes with a large payload so that the DownloadProgress callback
  2554. // (which only fires for Content-Length responses) is invoked before the
  2555. // entire body is received, giving cancellation a chance to fire.
  2556. auto host = "httpbingo.org";
  2557. auto path = std::string{"/bytes/524288"};
  2558. #ifdef CPPHTTPLIB_SSL_ENABLED
  2559. auto port = 443;
  2560. SSLClient cli(host, port);
  2561. #else
  2562. auto port = 80;
  2563. Client cli(host, port);
  2564. #endif
  2565. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2566. cli.set_connection_timeout(std::chrono::seconds(5));
  2567. ASSERT_TRUE(!res);
  2568. EXPECT_EQ(Error::Canceled, res.error());
  2569. }
  2570. TEST(CancelTest, WithCancelLargePayload_Online) {
  2571. auto host = "httpbingo.org";
  2572. auto path = std::string{"/bytes/524288"};
  2573. #ifdef CPPHTTPLIB_SSL_ENABLED
  2574. auto port = 443;
  2575. SSLClient cli(host, port);
  2576. #else
  2577. auto port = 80;
  2578. Client cli(host, port);
  2579. #endif
  2580. cli.set_connection_timeout(std::chrono::seconds(5));
  2581. uint32_t count = 0;
  2582. auto res =
  2583. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2584. ASSERT_TRUE(!res);
  2585. EXPECT_EQ(Error::Canceled, res.error());
  2586. }
  2587. TEST(CancelTest, NoCancelPost) {
  2588. Server svr;
  2589. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2590. res.set_content("Hello World!", "text/plain");
  2591. });
  2592. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2593. auto se = detail::scope_exit([&] {
  2594. svr.stop();
  2595. thread.join();
  2596. ASSERT_FALSE(svr.is_running());
  2597. });
  2598. svr.wait_until_ready();
  2599. Client cli(HOST, PORT);
  2600. cli.set_connection_timeout(std::chrono::seconds(5));
  2601. auto res =
  2602. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2603. "application/json", [](uint64_t, uint64_t) { return true; });
  2604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2605. EXPECT_EQ("Hello World!", res->body);
  2606. EXPECT_EQ(StatusCode::OK_200, res->status);
  2607. }
  2608. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2609. Server svr;
  2610. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2611. res.set_content("Hello World!", "text/plain");
  2612. });
  2613. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2614. auto se = detail::scope_exit([&] {
  2615. svr.stop();
  2616. thread.join();
  2617. ASSERT_FALSE(svr.is_running());
  2618. });
  2619. svr.wait_until_ready();
  2620. Client cli(HOST, PORT);
  2621. cli.set_connection_timeout(std::chrono::seconds(5));
  2622. auto res =
  2623. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2624. "application/json", [](uint64_t, uint64_t) { return false; });
  2625. ASSERT_TRUE(!res);
  2626. EXPECT_EQ(Error::Canceled, res.error());
  2627. }
  2628. TEST(CancelTest, WithCancelLargePayloadPost) {
  2629. Server svr;
  2630. svr.set_payload_max_length(200 * 1024 * 1024);
  2631. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2632. res.set_content(LARGE_DATA, "text/plain");
  2633. });
  2634. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2635. auto se = detail::scope_exit([&] {
  2636. svr.stop();
  2637. thread.join();
  2638. ASSERT_FALSE(svr.is_running());
  2639. });
  2640. svr.wait_until_ready();
  2641. Client cli(HOST, PORT);
  2642. cli.set_payload_max_length(200 * 1024 * 1024);
  2643. cli.set_connection_timeout(std::chrono::seconds(5));
  2644. auto res =
  2645. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2646. "application/json", [](uint64_t, uint64_t) { return false; });
  2647. ASSERT_TRUE(!res);
  2648. EXPECT_EQ(Error::Canceled, res.error());
  2649. }
  2650. TEST(CancelTest, NoCancelPut) {
  2651. Server svr;
  2652. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2653. res.set_content("Hello World!", "text/plain");
  2654. });
  2655. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2656. auto se = detail::scope_exit([&] {
  2657. svr.stop();
  2658. thread.join();
  2659. ASSERT_FALSE(svr.is_running());
  2660. });
  2661. svr.wait_until_ready();
  2662. Client cli(HOST, PORT);
  2663. cli.set_connection_timeout(std::chrono::seconds(5));
  2664. auto res =
  2665. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2666. "application/json", [](uint64_t, uint64_t) { return true; });
  2667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2668. EXPECT_EQ("Hello World!", res->body);
  2669. EXPECT_EQ(StatusCode::OK_200, res->status);
  2670. }
  2671. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2672. Server svr;
  2673. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2674. res.set_content("Hello World!", "text/plain");
  2675. });
  2676. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2677. auto se = detail::scope_exit([&] {
  2678. svr.stop();
  2679. thread.join();
  2680. ASSERT_FALSE(svr.is_running());
  2681. });
  2682. svr.wait_until_ready();
  2683. Client cli(HOST, PORT);
  2684. cli.set_connection_timeout(std::chrono::seconds(5));
  2685. auto res =
  2686. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2687. "application/json", [](uint64_t, uint64_t) { return false; });
  2688. ASSERT_TRUE(!res);
  2689. EXPECT_EQ(Error::Canceled, res.error());
  2690. }
  2691. TEST(CancelTest, WithCancelLargePayloadPut) {
  2692. Server svr;
  2693. svr.set_payload_max_length(200 * 1024 * 1024);
  2694. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2695. res.set_content(LARGE_DATA, "text/plain");
  2696. });
  2697. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2698. auto se = detail::scope_exit([&] {
  2699. svr.stop();
  2700. thread.join();
  2701. ASSERT_FALSE(svr.is_running());
  2702. });
  2703. svr.wait_until_ready();
  2704. Client cli(HOST, PORT);
  2705. cli.set_payload_max_length(200 * 1024 * 1024);
  2706. cli.set_connection_timeout(std::chrono::seconds(5));
  2707. auto res =
  2708. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2709. "application/json", [](uint64_t, uint64_t) { return false; });
  2710. ASSERT_TRUE(!res);
  2711. EXPECT_EQ(Error::Canceled, res.error());
  2712. }
  2713. TEST(CancelTest, NoCancelPatch) {
  2714. Server svr;
  2715. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2716. res.set_content("Hello World!", "text/plain");
  2717. });
  2718. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2719. auto se = detail::scope_exit([&] {
  2720. svr.stop();
  2721. thread.join();
  2722. ASSERT_FALSE(svr.is_running());
  2723. });
  2724. svr.wait_until_ready();
  2725. Client cli(HOST, PORT);
  2726. cli.set_connection_timeout(std::chrono::seconds(5));
  2727. auto res =
  2728. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2729. "application/json", [](uint64_t, uint64_t) { return true; });
  2730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2731. EXPECT_EQ("Hello World!", res->body);
  2732. EXPECT_EQ(StatusCode::OK_200, res->status);
  2733. }
  2734. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2735. Server svr;
  2736. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2737. res.set_content("Hello World!", "text/plain");
  2738. });
  2739. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2740. auto se = detail::scope_exit([&] {
  2741. svr.stop();
  2742. thread.join();
  2743. ASSERT_FALSE(svr.is_running());
  2744. });
  2745. svr.wait_until_ready();
  2746. Client cli(HOST, PORT);
  2747. cli.set_connection_timeout(std::chrono::seconds(5));
  2748. auto res =
  2749. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2750. "application/json", [](uint64_t, uint64_t) { return false; });
  2751. ASSERT_TRUE(!res);
  2752. EXPECT_EQ(Error::Canceled, res.error());
  2753. }
  2754. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2755. Server svr;
  2756. svr.set_payload_max_length(200 * 1024 * 1024);
  2757. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2758. res.set_content(LARGE_DATA, "text/plain");
  2759. });
  2760. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2761. auto se = detail::scope_exit([&] {
  2762. svr.stop();
  2763. thread.join();
  2764. ASSERT_FALSE(svr.is_running());
  2765. });
  2766. svr.wait_until_ready();
  2767. Client cli(HOST, PORT);
  2768. cli.set_payload_max_length(200 * 1024 * 1024);
  2769. cli.set_connection_timeout(std::chrono::seconds(5));
  2770. auto res =
  2771. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2772. "application/json", [](uint64_t, uint64_t) { return false; });
  2773. ASSERT_TRUE(!res);
  2774. EXPECT_EQ(Error::Canceled, res.error());
  2775. }
  2776. TEST(CancelTest, NoCancelDelete) {
  2777. Server svr;
  2778. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2779. res.set_content("Hello World!", "text/plain");
  2780. });
  2781. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2782. auto se = detail::scope_exit([&] {
  2783. svr.stop();
  2784. thread.join();
  2785. ASSERT_FALSE(svr.is_running());
  2786. });
  2787. svr.wait_until_ready();
  2788. Client cli(HOST, PORT);
  2789. cli.set_connection_timeout(std::chrono::seconds(5));
  2790. auto res =
  2791. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2792. "application/json", [](uint64_t, uint64_t) { return true; });
  2793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2794. EXPECT_EQ("Hello World!", res->body);
  2795. EXPECT_EQ(StatusCode::OK_200, res->status);
  2796. }
  2797. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2798. Server svr;
  2799. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2800. res.set_content("Hello World!", "text/plain");
  2801. });
  2802. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2803. auto se = detail::scope_exit([&] {
  2804. svr.stop();
  2805. thread.join();
  2806. ASSERT_FALSE(svr.is_running());
  2807. });
  2808. svr.wait_until_ready();
  2809. Client cli(HOST, PORT);
  2810. cli.set_connection_timeout(std::chrono::seconds(5));
  2811. auto res =
  2812. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2813. "application/json", [](uint64_t, uint64_t) { return false; });
  2814. ASSERT_TRUE(!res);
  2815. EXPECT_EQ(Error::Canceled, res.error());
  2816. }
  2817. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2818. Server svr;
  2819. svr.set_payload_max_length(200 * 1024 * 1024);
  2820. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2821. res.set_content(LARGE_DATA, "text/plain");
  2822. });
  2823. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2824. auto se = detail::scope_exit([&] {
  2825. svr.stop();
  2826. thread.join();
  2827. ASSERT_FALSE(svr.is_running());
  2828. });
  2829. svr.wait_until_ready();
  2830. Client cli(HOST, PORT);
  2831. cli.set_payload_max_length(200 * 1024 * 1024);
  2832. cli.set_connection_timeout(std::chrono::seconds(5));
  2833. auto res =
  2834. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2835. "application/json", [](uint64_t, uint64_t) { return false; });
  2836. ASSERT_TRUE(!res);
  2837. EXPECT_EQ(Error::Canceled, res.error());
  2838. }
  2839. static std::string remove_whitespace(const std::string &input) {
  2840. std::string output;
  2841. output.reserve(input.size());
  2842. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2843. [](unsigned char c) { return !std::isspace(c); });
  2844. return output;
  2845. }
  2846. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2847. auto host = "httpbingo.org";
  2848. auto path = std::string{"/basic-auth/hello/world"};
  2849. #ifdef CPPHTTPLIB_SSL_ENABLED
  2850. auto port = 443;
  2851. SSLClient cli(host, port);
  2852. #else
  2853. auto port = 80;
  2854. Client cli(host, port);
  2855. #endif
  2856. {
  2857. auto res = cli.Get(path);
  2858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2859. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2860. }
  2861. {
  2862. auto res = cli.Get(
  2863. path, Headers{make_basic_authentication_header("hello", "world")});
  2864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2865. auto body = remove_whitespace(res->body);
  2866. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2867. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2868. EXPECT_EQ(StatusCode::OK_200, res->status);
  2869. }
  2870. {
  2871. cli.set_basic_auth("hello", "world");
  2872. auto res = cli.Get(path);
  2873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2874. auto body = remove_whitespace(res->body);
  2875. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2876. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2877. EXPECT_EQ(StatusCode::OK_200, res->status);
  2878. }
  2879. {
  2880. cli.set_basic_auth("hello", "bad");
  2881. auto res = cli.Get(path);
  2882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2883. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2884. }
  2885. {
  2886. cli.set_basic_auth("bad", "world");
  2887. auto res = cli.Get(path);
  2888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2889. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2890. }
  2891. }
  2892. #ifdef CPPHTTPLIB_SSL_ENABLED
  2893. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2894. auto host = "httpbingo.org";
  2895. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2896. auto paths = std::vector<std::string>{
  2897. "/digest-auth/auth/hello/world/MD5",
  2898. "/digest-auth/auth/hello/world/SHA-256",
  2899. };
  2900. auto port = 443;
  2901. SSLClient cli(host, port);
  2902. {
  2903. auto res = cli.Get(unauth_path);
  2904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2905. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2906. }
  2907. {
  2908. cli.set_digest_auth("hello", "world");
  2909. for (const auto &path : paths) {
  2910. auto res = cli.Get(path.c_str());
  2911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2912. auto body = remove_whitespace(res->body);
  2913. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2914. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2915. EXPECT_EQ(StatusCode::OK_200, res->status);
  2916. }
  2917. cli.set_digest_auth("hello", "bad");
  2918. for (const auto &path : paths) {
  2919. auto res = cli.Get(path.c_str());
  2920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2921. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2922. }
  2923. }
  2924. }
  2925. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2926. // comma-separated list of challenges, and each challenge may itself carry a
  2927. // comma-separated auth-param list, so a server can legally offer Basic
  2928. // before Digest, either as two field lines or packed into one. Runs one 401
  2929. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2930. // value() joins them in receipt order) and checks that the retry carries a
  2931. // well-formed Digest Authorization header naming expected_realm.
  2932. static void
  2933. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2934. const std::string &expected_realm) {
  2935. std::atomic<int> hits{0};
  2936. Server svr;
  2937. svr.Get("/x", [&](const Request &req, Response &res) {
  2938. if (++hits == 1) {
  2939. res.status = StatusCode::Unauthorized_401;
  2940. for (const auto &challenge : challenges) {
  2941. res.set_header("WWW-Authenticate", challenge);
  2942. }
  2943. } else {
  2944. auto authorization = req.get_header_value("Authorization");
  2945. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2946. EXPECT_NE(std::string::npos,
  2947. authorization.find("realm=\"" + expected_realm + "\""));
  2948. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2949. res.set_content("ok", "text/plain");
  2950. }
  2951. });
  2952. auto port = svr.bind_to_any_port(HOST);
  2953. std::thread t([&]() { svr.listen_after_bind(); });
  2954. auto se = detail::scope_exit([&] {
  2955. svr.stop();
  2956. t.join();
  2957. });
  2958. svr.wait_until_ready();
  2959. Client cli(HOST, port);
  2960. cli.set_digest_auth("hello", "world");
  2961. auto res = cli.Get("/x");
  2962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2963. EXPECT_EQ(2, hits.load());
  2964. }
  2965. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2966. static const char *kDigestChallenge =
  2967. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2968. "algorithm=MD5";
  2969. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2970. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2971. "testrealm");
  2972. }
  2973. // Same challenge list with the schemes in the opposite order, to make sure
  2974. // the fix above didn't just special-case "Basic first".
  2975. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2976. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2977. "testrealm");
  2978. }
  2979. // A comma inside a quoted auth-param value must not be mistaken for the
  2980. // separator between two challenges (or two auth-params).
  2981. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2982. run_digest_challenge_list_test(
  2983. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2984. "algorithm=MD5"},
  2985. "test,realm");
  2986. }
  2987. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  2988. // the params and leaves out the fragment.
  2989. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  2990. Server svr;
  2991. std::string uri, target;
  2992. svr.Get("/a b", [&](const Request &req, Response &res) {
  2993. auto auth = req.get_header_value("Authorization");
  2994. if (auth.empty()) {
  2995. res.status = StatusCode::Unauthorized_401;
  2996. res.set_header("WWW-Authenticate",
  2997. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  2998. return;
  2999. }
  3000. auto b = auth.find("uri=\"") + 5;
  3001. uri = auth.substr(b, auth.find('"', b) - b);
  3002. target = req.target;
  3003. });
  3004. auto port = svr.bind_to_any_port(HOST);
  3005. std::thread t([&]() { svr.listen_after_bind(); });
  3006. auto se = detail::scope_exit([&] {
  3007. svr.stop();
  3008. t.join();
  3009. });
  3010. svr.wait_until_ready();
  3011. Client cli(HOST, port);
  3012. cli.set_digest_auth("hello", "world");
  3013. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3015. EXPECT_EQ("/a%20b?x=1", target);
  3016. EXPECT_EQ(target, uri);
  3017. }
  3018. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3019. // make_digest_authentication_header() dereferences both unconditionally, so
  3020. // a server sending a challenge missing either one must not be treated as
  3021. // usable -- doing so used to crash the client with std::out_of_range.
  3022. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3023. Server svr;
  3024. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3025. res.status = StatusCode::Unauthorized_401;
  3026. res.set_header("WWW-Authenticate", challenge);
  3027. });
  3028. auto port = svr.bind_to_any_port(HOST);
  3029. std::thread t([&]() { svr.listen_after_bind(); });
  3030. auto se = detail::scope_exit([&] {
  3031. svr.stop();
  3032. t.join();
  3033. });
  3034. svr.wait_until_ready();
  3035. Client cli(HOST, port);
  3036. cli.set_digest_auth("hello", "world");
  3037. auto res = cli.Get("/x");
  3038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3039. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3040. }
  3041. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3042. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3043. }
  3044. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3045. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3046. }
  3047. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3048. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3049. }
  3050. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3051. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3052. // when storing the values, so the header builder has to re-escape them (and
  3053. // keep algorithm a bare token); otherwise the value breaks out of its
  3054. // quoted-string and injects extra auth-params into the client's Authorization.
  3055. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3056. std::atomic<int> hits{0};
  3057. std::string authorization;
  3058. Server svr;
  3059. svr.Get("/x", [&](const Request &req, Response &res) {
  3060. if (++hits == 1) {
  3061. res.status = StatusCode::Unauthorized_401;
  3062. // On the wire the quotes embedded in the values are backslash-escaped.
  3063. res.set_header("WWW-Authenticate",
  3064. "Digest realm=\"testrealm\", "
  3065. "nonce=\"n\\\"; injected=\\\"x\", "
  3066. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3067. } else {
  3068. authorization = req.get_header_value("Authorization");
  3069. res.set_content("ok", "text/plain");
  3070. }
  3071. });
  3072. auto port = svr.bind_to_any_port(HOST);
  3073. std::thread t([&]() { svr.listen_after_bind(); });
  3074. auto se = detail::scope_exit([&] {
  3075. svr.stop();
  3076. t.join();
  3077. });
  3078. svr.wait_until_ready();
  3079. Client cli(HOST, port);
  3080. cli.set_digest_auth("hello", "world");
  3081. auto res = cli.Get("/x");
  3082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3083. EXPECT_EQ(2, hits.load());
  3084. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3085. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3086. // inside its quoted-string rather than starting an "injected" auth-param.
  3087. EXPECT_NE(std::string::npos,
  3088. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3089. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3090. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3091. }
  3092. #endif
  3093. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3094. auto host = "google.com";
  3095. auto another_host = "example.com";
  3096. auto wrong_ip = "0.0.0.0";
  3097. #ifdef CPPHTTPLIB_SSL_ENABLED
  3098. SSLClient cli(host);
  3099. #else
  3100. Client cli(host);
  3101. #endif
  3102. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3103. auto res = cli.Get("/");
  3104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3105. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3106. }
  3107. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3108. auto host = "google.com";
  3109. auto wrong_ip = "0.0.0.0";
  3110. #ifdef CPPHTTPLIB_SSL_ENABLED
  3111. SSLClient cli(host);
  3112. #else
  3113. Client cli(host);
  3114. #endif
  3115. cli.set_hostname_addr_map({{host, wrong_ip}});
  3116. auto res = cli.Get("/");
  3117. ASSERT_TRUE(!res);
  3118. EXPECT_EQ(Error::Connection, res.error());
  3119. }
  3120. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3121. // A mapped value that is not an IP literal must be resolved. "localhost"
  3122. // resolves from the hosts file, so this test needs no external DNS.
  3123. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3124. auto host = "target.invalid";
  3125. Server svr;
  3126. std::string received_host;
  3127. svr.Get("/hi", [&](const Request &req, Response &res) {
  3128. received_host = req.get_header_value("Host");
  3129. res.set_content("Hello World!", "text/plain");
  3130. });
  3131. auto port = svr.bind_to_any_port(HOST);
  3132. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3133. auto se = detail::scope_exit([&] {
  3134. svr.stop();
  3135. thread.join();
  3136. ASSERT_FALSE(svr.is_running());
  3137. });
  3138. svr.wait_until_ready();
  3139. Client cli(host, port);
  3140. cli.set_hostname_addr_map({{host, HOST}});
  3141. auto res = cli.Get("/hi");
  3142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3143. EXPECT_EQ(StatusCode::OK_200, res->status);
  3144. // The mapping only redirects the connection; the identity stays host_.
  3145. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3146. }
  3147. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3148. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3149. auto host = "target.invalid";
  3150. Server svr;
  3151. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3152. res.set_content("Hello World!", "text/plain");
  3153. });
  3154. auto port = svr.bind_to_any_port("127.0.0.1");
  3155. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3156. auto se = detail::scope_exit([&] {
  3157. svr.stop();
  3158. thread.join();
  3159. ASSERT_FALSE(svr.is_running());
  3160. });
  3161. svr.wait_until_ready();
  3162. Client cli(host, port);
  3163. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3164. auto res = cli.Get("/hi");
  3165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3166. EXPECT_EQ(StatusCode::OK_200, res->status);
  3167. }
  3168. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3169. // An empty mapped value must leave host_ as the connection target. Without
  3170. // that guard the empty value would become the host argument, getaddrinfo
  3171. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3172. // loopback - silently connecting somewhere the caller never asked for.
  3173. // The server listens on loopback, so such a fallback would succeed and is
  3174. // therefore observable as a failure of this test.
  3175. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3176. Server svr;
  3177. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3178. res.set_content("Hello World!", "text/plain");
  3179. });
  3180. auto port = svr.bind_to_any_port(HOST);
  3181. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3182. auto se = detail::scope_exit([&] {
  3183. svr.stop();
  3184. thread.join();
  3185. ASSERT_FALSE(svr.is_running());
  3186. });
  3187. svr.wait_until_ready();
  3188. Client cli(blackhole, port);
  3189. cli.set_hostname_addr_map({{blackhole, ""}});
  3190. cli.set_connection_timeout(1);
  3191. auto res = cli.Get("/hi");
  3192. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3193. }
  3194. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3195. auto host = "httpbingo.org";
  3196. auto path = std::string{"/absolute-redirect/3"};
  3197. #ifdef CPPHTTPLIB_SSL_ENABLED
  3198. SSLClient cli(host);
  3199. #else
  3200. Client cli(host);
  3201. #endif
  3202. cli.set_follow_location(true);
  3203. auto res = cli.Get(path);
  3204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3205. EXPECT_EQ(StatusCode::OK_200, res->status);
  3206. }
  3207. TEST(RedirectTest, Redirect_Online) {
  3208. auto host = "httpbingo.org";
  3209. auto path = std::string{"/redirect/3"};
  3210. #ifdef CPPHTTPLIB_SSL_ENABLED
  3211. SSLClient cli(host);
  3212. #else
  3213. Client cli(host);
  3214. #endif
  3215. cli.set_follow_location(true);
  3216. auto res = cli.Get(path);
  3217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3218. EXPECT_EQ(StatusCode::OK_200, res->status);
  3219. }
  3220. TEST(RelativeRedirectTest, Redirect_Online) {
  3221. auto host = "httpbingo.org";
  3222. auto path = std::string{"/relative-redirect/3"};
  3223. #ifdef CPPHTTPLIB_SSL_ENABLED
  3224. SSLClient cli(host);
  3225. #else
  3226. Client cli(host);
  3227. #endif
  3228. cli.set_follow_location(true);
  3229. auto res = cli.Get(path);
  3230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3231. EXPECT_EQ(StatusCode::OK_200, res->status);
  3232. }
  3233. TEST(TooManyRedirectTest, Redirect_Online) {
  3234. auto host = "httpbingo.org";
  3235. auto path = std::string{"/redirect/21"};
  3236. #ifdef CPPHTTPLIB_SSL_ENABLED
  3237. SSLClient cli(host);
  3238. #else
  3239. Client cli(host);
  3240. #endif
  3241. cli.set_follow_location(true);
  3242. auto res = cli.Get(path);
  3243. ASSERT_TRUE(!res);
  3244. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3245. }
  3246. #ifdef CPPHTTPLIB_SSL_ENABLED
  3247. TEST(YahooRedirectTest, Redirect_Online) {
  3248. Client cli("yahoo.com");
  3249. auto res = cli.Get("/");
  3250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3251. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3252. cli.set_follow_location(true);
  3253. res = cli.Get("/");
  3254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3255. EXPECT_EQ(StatusCode::OK_200, res->status);
  3256. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3257. }
  3258. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3259. #define REDIR_HOST "httpbingo.org"
  3260. #define REDIR_PATH "/redirect-to"
  3261. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3262. SSLClient cli(REDIR_HOST);
  3263. cli.set_follow_location(true);
  3264. auto res =
  3265. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3267. EXPECT_EQ(StatusCode::OK_200, res->status);
  3268. }
  3269. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3270. SSLClient cli(REDIR_HOST);
  3271. cli.set_follow_location(true);
  3272. Params params;
  3273. params.emplace("url", "http://example.com");
  3274. params.emplace("status_code", "302");
  3275. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3277. EXPECT_EQ(StatusCode::OK_200, res->status);
  3278. }
  3279. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3280. SSLClient cli(REDIR_HOST);
  3281. cli.set_follow_location(true);
  3282. Params params;
  3283. params.emplace("url", "http://example.com");
  3284. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3286. EXPECT_EQ(StatusCode::OK_200, res->status);
  3287. }
  3288. TEST(UrlWithSpace, Redirect_Online) {
  3289. SSLClient cli("edge.forgecdn.net");
  3290. cli.set_follow_location(true);
  3291. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3293. EXPECT_EQ(StatusCode::OK_200, res->status);
  3294. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3295. }
  3296. #endif
  3297. #if !defined(_WIN32) && !defined(_WIN64)
  3298. TEST(ReceiveSignals, Signal) {
  3299. auto setupSignalHandlers = []() {
  3300. struct sigaction act;
  3301. sigemptyset(&act.sa_mask);
  3302. act.sa_flags = SA_SIGINFO;
  3303. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3304. switch (sig) {
  3305. case SIGINT:
  3306. default: break;
  3307. }
  3308. };
  3309. ::sigaction(SIGINT, &act, nullptr);
  3310. };
  3311. Server svr;
  3312. int port = 0;
  3313. auto thread = std::thread([&]() {
  3314. setupSignalHandlers();
  3315. port = svr.bind_to_any_port(HOST);
  3316. svr.listen_after_bind();
  3317. });
  3318. auto se = detail::scope_exit([&] {
  3319. svr.stop();
  3320. thread.join();
  3321. ASSERT_FALSE(svr.is_running());
  3322. });
  3323. svr.wait_until_ready();
  3324. ASSERT_TRUE(svr.is_running());
  3325. pthread_kill(thread.native_handle(), SIGINT);
  3326. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3327. ASSERT_TRUE(svr.is_running());
  3328. }
  3329. #endif
  3330. TEST(RedirectToDifferentPort, Redirect) {
  3331. Server svr1;
  3332. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3333. res.set_content("Hello World!", "text/plain");
  3334. });
  3335. int svr1_port = 0;
  3336. auto thread1 = std::thread([&]() {
  3337. svr1_port = svr1.bind_to_any_port(HOST);
  3338. svr1.listen_after_bind();
  3339. });
  3340. Server svr2;
  3341. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3342. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3343. });
  3344. int svr2_port = 0;
  3345. auto thread2 = std::thread([&]() {
  3346. svr2_port = svr2.bind_to_any_port(HOST);
  3347. svr2.listen_after_bind();
  3348. });
  3349. auto se = detail::scope_exit([&] {
  3350. svr2.stop();
  3351. thread2.join();
  3352. svr1.stop();
  3353. thread1.join();
  3354. ASSERT_FALSE(svr2.is_running());
  3355. ASSERT_FALSE(svr1.is_running());
  3356. });
  3357. svr1.wait_until_ready();
  3358. svr2.wait_until_ready();
  3359. Client cli("localhost", svr2_port);
  3360. cli.set_follow_location(true);
  3361. auto res = cli.Get("/2");
  3362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3363. EXPECT_EQ(StatusCode::OK_200, res->status);
  3364. EXPECT_EQ("Hello World!", res->body);
  3365. }
  3366. // GET /redir on one server redirects to /target on another port, so the
  3367. // client follows it with a new client.
  3368. static Result
  3369. GetThroughRedirectToDifferentPort(Server::Handler target,
  3370. const std::function<void(Client &)> &setup,
  3371. const Headers &headers = Headers()) {
  3372. Server target_svr;
  3373. target_svr.Get("/target", target);
  3374. int target_port = 0;
  3375. auto target_thread = std::thread([&]() {
  3376. target_port = target_svr.bind_to_any_port(HOST);
  3377. target_svr.listen_after_bind();
  3378. });
  3379. Server origin_svr;
  3380. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3381. res.set_redirect(
  3382. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3383. });
  3384. int origin_port = 0;
  3385. auto origin_thread = std::thread([&]() {
  3386. origin_port = origin_svr.bind_to_any_port(HOST);
  3387. origin_svr.listen_after_bind();
  3388. });
  3389. auto se = detail::scope_exit([&] {
  3390. origin_svr.stop();
  3391. origin_thread.join();
  3392. target_svr.stop();
  3393. target_thread.join();
  3394. });
  3395. target_svr.wait_until_ready();
  3396. origin_svr.wait_until_ready();
  3397. Client cli("localhost", origin_port);
  3398. cli.set_follow_location(true);
  3399. setup(cli);
  3400. return cli.Get("/redir", headers);
  3401. }
  3402. static void
  3403. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3404. std::string captured_authorization;
  3405. auto result = GetThroughRedirectToDifferentPort(
  3406. [&](const Request &req, Response &res) {
  3407. captured_authorization = req.get_header_value("Authorization");
  3408. res.set_content("OK", "text/plain");
  3409. },
  3410. set_auth);
  3411. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3412. EXPECT_EQ(StatusCode::OK_200, result->status);
  3413. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3414. EXPECT_TRUE(captured_authorization.empty());
  3415. }
  3416. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3417. TestDoNotForwardCredentialsOnRedirect(
  3418. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3419. }
  3420. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3421. TestDoNotForwardCredentialsOnRedirect(
  3422. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3423. }
  3424. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3425. std::string captured_cookie;
  3426. auto result = GetThroughRedirectToDifferentPort(
  3427. [&](const Request &req, Response &res) {
  3428. captured_cookie = req.get_header_value("Cookie");
  3429. res.set_content("OK", "text/plain");
  3430. },
  3431. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3432. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3433. EXPECT_EQ(StatusCode::OK_200, result->status);
  3434. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3435. EXPECT_TRUE(captured_cookie.empty());
  3436. }
  3437. TEST(RedirectToSamePort, ForwardCookie) {
  3438. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3439. // header so that ordinary session flows keep working.
  3440. Server svr;
  3441. std::string captured_cookie;
  3442. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3443. res.set_redirect("/target", 302);
  3444. });
  3445. svr.Get("/target", [&](const Request &req, Response &res) {
  3446. captured_cookie = req.get_header_value("Cookie");
  3447. res.set_content("OK", "text/plain");
  3448. });
  3449. auto port = svr.bind_to_any_port(HOST);
  3450. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3451. auto se = detail::scope_exit([&] {
  3452. svr.stop();
  3453. thread.join();
  3454. ASSERT_FALSE(svr.is_running());
  3455. });
  3456. svr.wait_until_ready();
  3457. Client cli(HOST, port);
  3458. cli.set_follow_location(true);
  3459. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3460. auto res = cli.Get("/redir", headers);
  3461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3462. EXPECT_EQ(StatusCode::OK_200, res->status);
  3463. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3464. }
  3465. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3466. std::string authorization;
  3467. std::string trace_id;
  3468. auto result = GetThroughRedirectToDifferentPort(
  3469. [&](const Request &req, Response &res) {
  3470. authorization = req.get_header_value("Authorization");
  3471. trace_id = req.get_header_value("X-Trace-Id");
  3472. res.set_content("OK", "text/plain");
  3473. },
  3474. [](Client &cli) {
  3475. cli.set_default_headers(
  3476. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3477. });
  3478. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3479. EXPECT_EQ(StatusCode::OK_200, result->status);
  3480. // Like a header given with the request, a default one goes along unless it
  3481. // carries credentials (RFC 9110 15.4).
  3482. EXPECT_TRUE(authorization.empty());
  3483. EXPECT_EQ("42", trace_id);
  3484. }
  3485. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3486. auto result = GetThroughRedirectToDifferentPort(
  3487. [](const Request &, Response &res) {
  3488. res.set_content(std::string(2048, 'x'), "text/plain");
  3489. },
  3490. [](Client &cli) { cli.set_payload_max_length(1024); });
  3491. EXPECT_FALSE(result);
  3492. }
  3493. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3494. auto result = GetThroughRedirectToDifferentPort(
  3495. [](const Request &req, Response &res) {
  3496. // Answer after a second, or once the client gives up.
  3497. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3498. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3499. }
  3500. res.set_content("late", "text/plain");
  3501. },
  3502. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3503. ASSERT_FALSE(result);
  3504. EXPECT_EQ(Error::Read, result.error());
  3505. }
  3506. #ifdef CPPHTTPLIB_SSL_ENABLED
  3507. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3508. auto result = GetThroughRedirectToDifferentPort(
  3509. [](const Request &, Response &res) {
  3510. res.status = StatusCode::Unauthorized_401;
  3511. res.set_header("WWW-Authenticate",
  3512. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3513. },
  3514. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3515. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3516. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3517. }
  3518. #endif
  3519. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3520. Server svr;
  3521. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3522. // Port number that overflows int — should not crash
  3523. res.set_redirect("http://localhost:99999999999999999999/target");
  3524. });
  3525. auto port = svr.bind_to_any_port(HOST);
  3526. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3527. auto se = detail::scope_exit([&] {
  3528. svr.stop();
  3529. thread.join();
  3530. ASSERT_FALSE(svr.is_running());
  3531. });
  3532. svr.wait_until_ready();
  3533. Client cli(HOST, port);
  3534. cli.set_follow_location(true);
  3535. auto res = cli.Get("/redir");
  3536. // Should fail gracefully, not crash (no valid response due to bad port)
  3537. EXPECT_FALSE(res);
  3538. }
  3539. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3540. Server svr;
  3541. auto port = svr.bind_to_any_port(HOST);
  3542. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3543. // The server's own port followed by junk must not be followed
  3544. res.set_redirect("http://" + std::string(HOST) + ":" +
  3545. std::to_string(port) + "junk/target");
  3546. });
  3547. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3548. res.set_content("target", "text/plain");
  3549. });
  3550. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3551. auto se = detail::scope_exit([&] {
  3552. svr.stop();
  3553. thread.join();
  3554. ASSERT_FALSE(svr.is_running());
  3555. });
  3556. svr.wait_until_ready();
  3557. Client cli(HOST, port);
  3558. cli.set_follow_location(true);
  3559. auto res = cli.Get("/redir");
  3560. EXPECT_FALSE(res);
  3561. }
  3562. TEST(RedirectFromPageWithContent, Redirect) {
  3563. Server svr;
  3564. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3565. res.set_content("___", "text/plain");
  3566. res.set_redirect("/2");
  3567. });
  3568. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3569. res.set_content("Hello World!", "text/plain");
  3570. });
  3571. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3572. auto se = detail::scope_exit([&] {
  3573. svr.stop();
  3574. th.join();
  3575. ASSERT_FALSE(svr.is_running());
  3576. });
  3577. svr.wait_until_ready();
  3578. {
  3579. Client cli("localhost", PORT);
  3580. cli.set_follow_location(true);
  3581. std::string body;
  3582. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3583. body.append(data, data_length);
  3584. return true;
  3585. });
  3586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3587. EXPECT_EQ(StatusCode::OK_200, res->status);
  3588. EXPECT_EQ("Hello World!", body);
  3589. }
  3590. {
  3591. Client cli("localhost", PORT);
  3592. std::string body;
  3593. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3594. body.append(data, data_length);
  3595. return true;
  3596. });
  3597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3598. EXPECT_EQ(StatusCode::Found_302, res->status);
  3599. EXPECT_EQ("___", body);
  3600. }
  3601. }
  3602. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3603. Server svr;
  3604. auto port_str = std::to_string(PORT);
  3605. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3606. auto expected_host = "[::1]:" + port_str;
  3607. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3608. res.set_content("___", "text/plain");
  3609. // res.set_redirect("/2");
  3610. res.set_redirect(redirect_url);
  3611. });
  3612. svr.Get("/2", [&](const Request &req, Response &res) {
  3613. auto host_header = req.headers.find("Host");
  3614. ASSERT_TRUE(host_header != req.headers.end());
  3615. EXPECT_EQ(expected_host, host_header->second);
  3616. res.set_content("Hello World!", "text/plain");
  3617. });
  3618. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3619. auto se = detail::scope_exit([&] {
  3620. svr.stop();
  3621. th.join();
  3622. ASSERT_FALSE(svr.is_running());
  3623. });
  3624. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3625. // actually starts anything, so the condition !svr.is_running() will
  3626. // always remain true, and the loop never stops.
  3627. // This basically counts how many milliseconds have passed since the
  3628. // call to svr.listen(), and if after 5 seconds nothing started yet
  3629. // aborts the test.
  3630. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3631. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3632. ASSERT_LT(milliseconds, 5000U);
  3633. }
  3634. {
  3635. Client cli("::1", PORT);
  3636. cli.set_follow_location(true);
  3637. std::string body;
  3638. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3639. body.append(data, data_length);
  3640. return true;
  3641. });
  3642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3643. EXPECT_EQ(StatusCode::OK_200, res->status);
  3644. EXPECT_EQ("Hello World!", body);
  3645. }
  3646. {
  3647. Client cli("::1", PORT);
  3648. std::string body;
  3649. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3650. body.append(data, data_length);
  3651. return true;
  3652. });
  3653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3654. EXPECT_EQ(StatusCode::Found_302, res->status);
  3655. EXPECT_EQ("___", body);
  3656. }
  3657. }
  3658. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3659. Server svr;
  3660. svr.Get("/foo", [](const Request &req, Response &res) {
  3661. auto a = req.params.find("a");
  3662. if (a != req.params.end()) {
  3663. res.set_content((*a).second, "text/plain");
  3664. res.status = StatusCode::OK_200;
  3665. } else {
  3666. res.status = StatusCode::BadRequest_400;
  3667. }
  3668. });
  3669. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3670. auto se = detail::scope_exit([&] {
  3671. svr.stop();
  3672. thread.join();
  3673. ASSERT_FALSE(svr.is_running());
  3674. });
  3675. svr.wait_until_ready();
  3676. {
  3677. Client cli(HOST, PORT);
  3678. cli.set_path_encode(false);
  3679. auto res = cli.Get("/foo?a=explicitly+encoded");
  3680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3681. EXPECT_EQ(StatusCode::OK_200, res->status);
  3682. // This expects it back with a space, as the `+` won't have been
  3683. // url-encoded, and server-side the params get decoded turning `+`
  3684. // into spaces.
  3685. EXPECT_EQ("explicitly encoded", res->body);
  3686. }
  3687. }
  3688. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3689. // When path encoding is disabled the client must transmit the supplied
  3690. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3691. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3692. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3693. // than a space (0x20). Assert on the raw wire target to catch this.
  3694. Server svr;
  3695. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3696. svr.Get("/foo", [&](const Request &req, Response &res) {
  3697. EXPECT_EQ(expected_target, req.target);
  3698. res.status = StatusCode::OK_200;
  3699. });
  3700. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3701. auto se = detail::scope_exit([&] {
  3702. svr.stop();
  3703. thread.join();
  3704. ASSERT_FALSE(svr.is_running());
  3705. });
  3706. svr.wait_until_ready();
  3707. {
  3708. Client cli(HOST, PORT);
  3709. cli.set_path_encode(false);
  3710. auto res = cli.Get(expected_target.c_str());
  3711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3712. EXPECT_EQ(StatusCode::OK_200, res->status);
  3713. }
  3714. }
  3715. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3716. // `open_stream()` used to skip the path encoding that the buffered send
  3717. // path applies, so the same `path` produced different bytes in the request
  3718. // line depending on which API was used. Assert the two agree.
  3719. Server svr;
  3720. std::string target;
  3721. svr.Get(".*", [&](const Request &req, Response &res) {
  3722. target = req.target;
  3723. res.status = StatusCode::OK_200;
  3724. });
  3725. auto port = svr.bind_to_any_port(HOST);
  3726. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3727. auto se = detail::scope_exit([&] {
  3728. svr.stop();
  3729. thread.join();
  3730. ASSERT_FALSE(svr.is_running());
  3731. });
  3732. svr.wait_until_ready();
  3733. struct {
  3734. const char *path;
  3735. const char *expected;
  3736. } cases[] = {
  3737. {"/a b?x=1", "/a%20b?x=1"},
  3738. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3739. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3740. };
  3741. for (const auto &c : cases) {
  3742. Client cli(HOST, port);
  3743. target.clear();
  3744. auto res = cli.Get(c.path);
  3745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3746. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3747. auto buffered_target = target;
  3748. target.clear();
  3749. auto handle = cli.open_stream("GET", c.path);
  3750. EXPECT_TRUE(handle.is_valid())
  3751. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3752. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3753. }
  3754. }
  3755. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3756. // The `set_path_encode(false)` contract — transmit the supplied target
  3757. // verbatim — must hold for the streaming API too.
  3758. Server svr;
  3759. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3760. std::string target;
  3761. svr.Get("/foo", [&](const Request &req, Response &res) {
  3762. target = req.target;
  3763. res.status = StatusCode::OK_200;
  3764. });
  3765. auto port = svr.bind_to_any_port(HOST);
  3766. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3767. auto se = detail::scope_exit([&] {
  3768. svr.stop();
  3769. thread.join();
  3770. ASSERT_FALSE(svr.is_running());
  3771. });
  3772. svr.wait_until_ready();
  3773. {
  3774. Client cli(HOST, port);
  3775. cli.set_path_encode(false);
  3776. auto handle = cli.open_stream("GET", expected_target);
  3777. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3778. EXPECT_EQ(expected_target, target);
  3779. }
  3780. }
  3781. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3782. // With path encoding enabled a CR/LF in the target is percent-encoded
  3783. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3784. // write_request_line still backstops `set_path_encode(false)`, which is
  3785. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3786. Server svr;
  3787. // Captured before routing: the decoded path contains a newline, which a
  3788. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3789. std::string target;
  3790. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3791. target = req.target;
  3792. res.status = StatusCode::OK_200;
  3793. return Server::HandlerResponse::Handled;
  3794. });
  3795. auto port = svr.bind_to_any_port(HOST);
  3796. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3797. auto se = detail::scope_exit([&] {
  3798. svr.stop();
  3799. thread.join();
  3800. ASSERT_FALSE(svr.is_running());
  3801. });
  3802. svr.wait_until_ready();
  3803. {
  3804. Client cli(HOST, port);
  3805. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3806. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3807. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3808. }
  3809. }
  3810. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3811. // Every control character is percent-encoded, not just CR/LF, so the target
  3812. // passes the request-target check in write_request_line.
  3813. Server svr;
  3814. std::string target;
  3815. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3816. target = req.target;
  3817. res.status = StatusCode::OK_200;
  3818. return Server::HandlerResponse::Handled;
  3819. });
  3820. auto port = svr.bind_to_any_port(HOST);
  3821. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3822. auto se = detail::scope_exit([&] {
  3823. svr.stop();
  3824. thread.join();
  3825. ASSERT_FALSE(svr.is_running());
  3826. });
  3827. svr.wait_until_ready();
  3828. {
  3829. Client cli(HOST, port);
  3830. auto res = cli.Get("/a\tb\x1b\x7f");
  3831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3832. EXPECT_EQ("/a%09b%1B%7F", target);
  3833. }
  3834. }
  3835. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3836. // Nothing may reach the wire: a raw CR/LF target would split the request
  3837. // line and inject headers.
  3838. Server svr;
  3839. // Pre-routing so that "not called" means nothing reached the server at all,
  3840. // rather than merely failing to match a handler pattern.
  3841. auto handler_called = false;
  3842. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3843. handler_called = true;
  3844. res.status = StatusCode::OK_200;
  3845. return Server::HandlerResponse::Handled;
  3846. });
  3847. auto port = svr.bind_to_any_port(HOST);
  3848. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3849. auto se = detail::scope_exit([&] {
  3850. svr.stop();
  3851. thread.join();
  3852. ASSERT_FALSE(svr.is_running());
  3853. });
  3854. svr.wait_until_ready();
  3855. {
  3856. Client cli(HOST, port);
  3857. cli.set_path_encode(false);
  3858. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3859. EXPECT_FALSE(handle.is_valid());
  3860. EXPECT_EQ(Error::Write, handle.error);
  3861. EXPECT_FALSE(handler_called);
  3862. }
  3863. }
  3864. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3865. // Which of the two branches runs is decided by whether the query component
  3866. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3867. // an empty query and must still fall back to building one from
  3868. // `req.params`, while a non-empty query must win over `req.params`.
  3869. Server svr;
  3870. std::string target;
  3871. svr.Get("/foo", [&](const Request &req, Response &res) {
  3872. target = req.target;
  3873. res.status = StatusCode::OK_200;
  3874. });
  3875. auto port = svr.bind_to_any_port(HOST);
  3876. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3877. auto se = detail::scope_exit([&] {
  3878. svr.stop();
  3879. thread.join();
  3880. ASSERT_FALSE(svr.is_running());
  3881. });
  3882. svr.wait_until_ready();
  3883. {
  3884. // Trailing `?` -> empty query component -> `req.params` is used.
  3885. Client cli(HOST, port);
  3886. Request req;
  3887. req.method = "GET";
  3888. req.path = "/foo?";
  3889. req.params.emplace("a", "1");
  3890. target.clear();
  3891. auto res = cli.send(req);
  3892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3893. EXPECT_EQ("/foo?a=1", target);
  3894. }
  3895. {
  3896. // Non-empty query in `req.path` -> `req.params` is not appended.
  3897. Client cli(HOST, port);
  3898. Request req;
  3899. req.method = "GET";
  3900. req.path = "/foo?b=2";
  3901. req.params.emplace("a", "1");
  3902. target.clear();
  3903. auto res = cli.send(req);
  3904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3905. EXPECT_EQ("/foo?b=2", target);
  3906. }
  3907. }
  3908. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3909. Server svr;
  3910. svr.Get("/", [](const Request &req, Response &) {
  3911. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3912. });
  3913. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3914. auto se = detail::scope_exit([&] {
  3915. svr.stop();
  3916. thread.join();
  3917. ASSERT_FALSE(svr.is_running());
  3918. });
  3919. svr.wait_until_ready();
  3920. {
  3921. Client cli(HOST, PORT);
  3922. cli.set_path_encode(false);
  3923. auto res = cli.Get("/?something=%0A");
  3924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3925. EXPECT_EQ(StatusCode::OK_200, res->status);
  3926. }
  3927. }
  3928. TEST(BindServerTest, BindDualStack) {
  3929. Server svr;
  3930. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3931. res.set_content("Hello World!", "text/plain");
  3932. });
  3933. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3934. auto se = detail::scope_exit([&] {
  3935. svr.stop();
  3936. thread.join();
  3937. ASSERT_FALSE(svr.is_running());
  3938. });
  3939. svr.wait_until_ready();
  3940. {
  3941. Client cli("127.0.0.1", PORT);
  3942. auto res = cli.Get("/1");
  3943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3944. EXPECT_EQ(StatusCode::OK_200, res->status);
  3945. EXPECT_EQ("Hello World!", res->body);
  3946. }
  3947. {
  3948. Client cli("::1", PORT);
  3949. auto res = cli.Get("/1");
  3950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3951. EXPECT_EQ(StatusCode::OK_200, res->status);
  3952. EXPECT_EQ("Hello World!", res->body);
  3953. }
  3954. }
  3955. TEST(BindServerTest, BindAndListenSeparately) {
  3956. Server svr;
  3957. int port = svr.bind_to_any_port("0.0.0.0");
  3958. ASSERT_TRUE(svr.is_valid());
  3959. ASSERT_TRUE(port > 0);
  3960. svr.stop();
  3961. }
  3962. // Reports whether anything is still listening on a loopback port. A plain
  3963. // connect() is used instead of a Client request because a socket left bound by
  3964. // mistake accepts the connection into its backlog and never answers, which
  3965. // would hang the test instead of failing it.
  3966. static bool is_loopback_port_accepting(int port) {
  3967. sockaddr_in addr{};
  3968. addr.sin_family = AF_INET;
  3969. addr.sin_port = htons(static_cast<uint16_t>(port));
  3970. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3971. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3972. EXPECT_NE(sock, INVALID_SOCKET);
  3973. if (sock == INVALID_SOCKET) { return false; }
  3974. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3975. static_cast<socklen_t>(sizeof(addr)));
  3976. detail::close_socket(sock);
  3977. return ret == 0;
  3978. }
  3979. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3980. Server svr;
  3981. auto port = svr.bind_to_any_port("127.0.0.1");
  3982. ASSERT_TRUE(port > 0);
  3983. svr.stop();
  3984. // bind_to_any_port() already called listen(2), so until stop() closed the
  3985. // descriptor the port kept accepting connections into the backlog. ASSERT
  3986. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3987. // below blocks forever in the accept loop.
  3988. ASSERT_FALSE(is_loopback_port_accepting(port));
  3989. // Nothing is left to accept on, so listen_after_bind() must report failure
  3990. // instead of returning success without ever serving.
  3991. EXPECT_FALSE(svr.listen_after_bind());
  3992. // The failed listen marks the server decommissioned, so a waiter returns
  3993. // instead of spinning forever.
  3994. svr.wait_until_ready();
  3995. }
  3996. #ifdef CPPHTTPLIB_SSL_ENABLED
  3997. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3998. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3999. CLIENT_CA_CERT_DIR);
  4000. int port = svr.bind_to_any_port("0.0.0.0");
  4001. ASSERT_TRUE(svr.is_valid());
  4002. ASSERT_TRUE(port > 0);
  4003. svr.stop();
  4004. }
  4005. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4006. // or a rejected CustomRoute() registration would not stop the server binding.
  4007. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4008. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4009. CLIENT_CA_CERT_DIR);
  4010. ASSERT_TRUE(svr.is_valid());
  4011. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4012. EXPECT_FALSE(svr.is_valid());
  4013. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4014. }
  4015. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4016. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4017. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4018. int port = svr.bind_to_any_port("0.0.0.0");
  4019. ASSERT_TRUE(svr.is_valid());
  4020. ASSERT_TRUE(port > 0);
  4021. svr.stop();
  4022. }
  4023. TEST(BindServerTest, UpdateCertsPem) {
  4024. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4025. int port = svr.bind_to_any_port("0.0.0.0");
  4026. ASSERT_TRUE(svr.is_valid());
  4027. ASSERT_TRUE(port > 0);
  4028. // Read PEM files
  4029. std::string cert_pem, key_pem, ca_pem;
  4030. read_file(SERVER_CERT_FILE, cert_pem);
  4031. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4032. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4033. // Update server certificates using PEM API
  4034. ASSERT_TRUE(
  4035. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4036. ASSERT_TRUE(svr.is_valid());
  4037. svr.stop();
  4038. }
  4039. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4040. // Start server with client CA (enables client auth)
  4041. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4042. ASSERT_TRUE(svr.is_valid());
  4043. bool handler_called = false;
  4044. svr.Get("/test", [&](const Request &req, Response &res) {
  4045. handler_called = true;
  4046. // Verify client certificate is present
  4047. auto cert = req.peer_cert();
  4048. EXPECT_TRUE(static_cast<bool>(cert));
  4049. res.set_content("ok", "text/plain");
  4050. });
  4051. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4052. auto se = detail::scope_exit([&] {
  4053. svr.stop();
  4054. t.join();
  4055. ASSERT_FALSE(svr.is_running());
  4056. });
  4057. svr.wait_until_ready();
  4058. // Read PEM files
  4059. std::string cert_pem, key_pem, ca_pem;
  4060. read_file(SERVER_CERT_FILE, cert_pem);
  4061. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4062. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4063. // Update server certificates and client CA using PEM API while server running
  4064. ASSERT_TRUE(
  4065. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4066. // Connect with client certificate
  4067. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4068. cli.enable_server_certificate_verification(false);
  4069. cli.set_connection_timeout(30);
  4070. auto res = cli.Get("/test");
  4071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4072. ASSERT_EQ(StatusCode::OK_200, res->status);
  4073. ASSERT_TRUE(handler_called);
  4074. EXPECT_EQ("ok", res->body);
  4075. }
  4076. // Puts a CA that did not sign the client's certificate in the old one's place.
  4077. static bool replace_client_ca(SSLServer &svr) {
  4078. std::string cert_pem, key_pem, ca_pem;
  4079. read_file(SERVER_CERT_FILE, cert_pem);
  4080. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4081. read_file(SERVER_CERT2_FILE, ca_pem);
  4082. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4083. ca_pem.c_str());
  4084. }
  4085. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4086. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4087. ASSERT_TRUE(svr.is_valid());
  4088. svr.Get("/test", [](const Request &, Response &res) {
  4089. res.set_content("ok", "text/plain");
  4090. });
  4091. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4092. auto se = detail::scope_exit([&] {
  4093. svr.stop();
  4094. t.join();
  4095. ASSERT_FALSE(svr.is_running());
  4096. });
  4097. svr.wait_until_ready();
  4098. auto get = [] {
  4099. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4100. cli.enable_server_certificate_verification(false);
  4101. return cli.Get("/test");
  4102. };
  4103. ASSERT_TRUE(get());
  4104. ASSERT_TRUE(replace_client_ca(svr));
  4105. EXPECT_FALSE(get());
  4106. }
  4107. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4108. // A client that resumes its session gets through, but not once the client CA
  4109. // has changed, as a resumed session does not show the certificate again.
  4110. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4111. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4112. ASSERT_TRUE(svr.is_valid());
  4113. svr.Get("/test", [](const Request &, Response &res) {
  4114. res.set_content("ok", "text/plain");
  4115. });
  4116. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4117. auto se = detail::scope_exit([&] {
  4118. svr.stop();
  4119. t.join();
  4120. ASSERT_FALSE(svr.is_running());
  4121. });
  4122. svr.wait_until_ready();
  4123. auto ctx = SSL_CTX_new(TLS_client_method());
  4124. auto ctx_se = detail::scope_exit([&] { SSL_CTX_free(ctx); });
  4125. ASSERT_EQ(
  4126. 1, SSL_CTX_use_certificate_file(ctx, CLIENT_CERT_FILE, SSL_FILETYPE_PEM));
  4127. ASSERT_EQ(1, SSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4128. SSL_FILETYPE_PEM));
  4129. SSL_SESSION *session = nullptr;
  4130. auto session_se = detail::scope_exit([&] { SSL_SESSION_free(session); });
  4131. // A request over a new connection, resuming `session` when there is one and
  4132. // keeping the connection's own in its place. Tells whether it was answered.
  4133. auto reused = false;
  4134. auto get = [&]() {
  4135. auto error = Error::Success;
  4136. auto sock = detail::create_client_socket(
  4137. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4138. /*connection_timeout_sec=*/5, 0,
  4139. /*read_timeout_sec=*/5, 0,
  4140. /*write_timeout_sec=*/5, 0, std::string(), error);
  4141. if (sock == INVALID_SOCKET) { return false; }
  4142. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4143. auto ssl = SSL_new(ctx);
  4144. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4145. SSL_set_fd(ssl, static_cast<int>(sock));
  4146. if (session) { SSL_set_session(ssl, session); }
  4147. if (SSL_connect(ssl) != 1) { return false; }
  4148. reused = SSL_session_reused(ssl) == 1;
  4149. // Reading the response also takes in a TLS 1.3 session ticket.
  4150. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4151. "Connection: close\r\n\r\n";
  4152. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4153. std::string res;
  4154. char buf[256];
  4155. int n;
  4156. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4157. res.append(buf, static_cast<size_t>(n));
  4158. }
  4159. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4160. SSL_shutdown(ssl);
  4161. SSL_SESSION_free(session);
  4162. session = SSL_get1_session(ssl);
  4163. return res.find("200 OK") != std::string::npos;
  4164. };
  4165. ASSERT_TRUE(get());
  4166. ASSERT_TRUE(get());
  4167. EXPECT_TRUE(reused);
  4168. ASSERT_TRUE(replace_client_ca(svr));
  4169. EXPECT_FALSE(get());
  4170. }
  4171. #endif
  4172. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4173. // wolfSSL shares its session cache between contexts, so a resumed session
  4174. // could carry a client certificate checked against another server's CA, or
  4175. // against a client CA since replaced.
  4176. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4177. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4178. ASSERT_TRUE(svr.is_valid());
  4179. // Trusts a CA that did not sign the client's certificate.
  4180. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4181. ASSERT_TRUE(other.is_valid());
  4182. for (auto s : {&svr, &other}) {
  4183. s->Get("/test", [](const Request &, Response &res) {
  4184. res.set_content("ok", "text/plain");
  4185. });
  4186. }
  4187. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4188. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4189. auto se = detail::scope_exit([&] {
  4190. other.stop();
  4191. svr.stop();
  4192. t2.join();
  4193. t.join();
  4194. });
  4195. svr.wait_until_ready();
  4196. other.wait_until_ready();
  4197. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4198. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4199. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4200. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4201. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4202. ASSERT_EQ(WOLFSSL_SUCCESS,
  4203. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4204. WOLFSSL_FILETYPE_PEM));
  4205. WOLFSSL_SESSION *session = nullptr;
  4206. auto session_se = detail::scope_exit([&] {
  4207. if (session) { wolfSSL_SESSION_free(session); }
  4208. });
  4209. // A request over a new connection, resuming `session` when there is one and
  4210. // keeping the connection's own in its place. Tells whether it was answered.
  4211. auto get = [&](int port) {
  4212. auto error = Error::Success;
  4213. auto sock = detail::create_client_socket(
  4214. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4215. /*connection_timeout_sec=*/5, 0,
  4216. /*read_timeout_sec=*/5, 0,
  4217. /*write_timeout_sec=*/5, 0, std::string(), error);
  4218. if (sock == INVALID_SOCKET) { return false; }
  4219. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4220. auto ssl = wolfSSL_new(ctx);
  4221. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4222. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4223. if (session) { wolfSSL_set_session(ssl, session); }
  4224. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4225. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4226. "Connection: close\r\n\r\n";
  4227. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4228. std::string res;
  4229. char buf[256];
  4230. int n;
  4231. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4232. res.append(buf, static_cast<size_t>(n));
  4233. }
  4234. wolfSSL_shutdown(ssl);
  4235. if (session) { wolfSSL_SESSION_free(session); }
  4236. session = wolfSSL_get1_session(ssl);
  4237. return res.find("200 OK") != std::string::npos;
  4238. };
  4239. ASSERT_TRUE(get(PORT));
  4240. EXPECT_FALSE(get(PORT + 1));
  4241. ASSERT_TRUE(get(PORT));
  4242. ASSERT_TRUE(replace_client_ca(svr));
  4243. EXPECT_FALSE(get(PORT));
  4244. }
  4245. #endif
  4246. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4247. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4248. ASSERT_TRUE(svr.is_valid());
  4249. svr.Get("/test", [](const Request &, Response &res) {
  4250. res.set_content("ok", "text/plain");
  4251. });
  4252. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4253. auto se = detail::scope_exit([&] {
  4254. svr.stop();
  4255. t.join();
  4256. ASSERT_FALSE(svr.is_running());
  4257. });
  4258. svr.wait_until_ready();
  4259. // A connection that sends no ClientHello keeps its handshake in progress,
  4260. // once the server has had a moment to start it.
  4261. auto error = Error::Success;
  4262. auto sock = detail::create_client_socket(
  4263. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4264. /*connection_timeout_sec=*/5, 0,
  4265. /*read_timeout_sec=*/5, 0,
  4266. /*write_timeout_sec=*/5, 0, std::string(), error);
  4267. ASSERT_NE(INVALID_SOCKET, sock);
  4268. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4269. std::string cert_pem, key_pem;
  4270. read_file(SERVER_CERT_FILE, cert_pem);
  4271. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4272. auto update = std::async(std::launch::async, [&]() {
  4273. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4274. });
  4275. EXPECT_EQ(std::future_status::timeout,
  4276. update.wait_for(std::chrono::milliseconds(200)));
  4277. detail::close_socket(sock);
  4278. EXPECT_TRUE(update.get());
  4279. SSLClient cli(HOST, PORT);
  4280. cli.enable_server_certificate_verification(false);
  4281. auto res = cli.Get("/test");
  4282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4283. EXPECT_EQ(StatusCode::OK_200, res->status);
  4284. }
  4285. #endif
  4286. TEST(ErrorHandlerTest, ContentLength) {
  4287. Server svr;
  4288. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4289. res.status = StatusCode::OK_200;
  4290. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4291. "text/html"); // <= Content-Length still 13
  4292. });
  4293. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4294. res.set_content("Hello World!\n", "text/plain");
  4295. res.status = 524;
  4296. });
  4297. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4298. auto se = detail::scope_exit([&] {
  4299. svr.stop();
  4300. thread.join();
  4301. ASSERT_FALSE(svr.is_running());
  4302. });
  4303. svr.wait_until_ready();
  4304. {
  4305. Client cli(HOST, PORT);
  4306. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4308. EXPECT_EQ(StatusCode::OK_200, res->status);
  4309. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4310. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4311. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4312. }
  4313. }
  4314. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4315. TEST(ExceptionTest, WithoutExceptionHandler) {
  4316. Server svr;
  4317. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4318. throw std::runtime_error("exception...");
  4319. });
  4320. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4321. throw std::runtime_error("exception\r\n...");
  4322. });
  4323. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4324. auto se = detail::scope_exit([&] {
  4325. svr.stop();
  4326. listen_thread.join();
  4327. ASSERT_FALSE(svr.is_running());
  4328. });
  4329. svr.wait_until_ready();
  4330. Client cli("localhost", PORT);
  4331. {
  4332. auto res = cli.Get("/exception");
  4333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4334. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4335. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4336. }
  4337. {
  4338. auto res = cli.Get("/unknown");
  4339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4340. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4341. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4342. }
  4343. }
  4344. TEST(ExceptionTest, WithExceptionHandler) {
  4345. Server svr;
  4346. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4347. std::exception_ptr ep) {
  4348. EXPECT_FALSE(ep == nullptr);
  4349. try {
  4350. std::rethrow_exception(ep);
  4351. } catch (std::exception &e) {
  4352. EXPECT_EQ("abc", std::string(e.what()));
  4353. } catch (...) {}
  4354. res.status = StatusCode::InternalServerError_500;
  4355. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4356. "text/html"); // <= Content-Length still 13 at this point
  4357. });
  4358. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4359. res.set_content("Hello World!\n", "text/plain");
  4360. throw std::runtime_error("abc");
  4361. });
  4362. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4363. auto se = detail::scope_exit([&] {
  4364. svr.stop();
  4365. thread.join();
  4366. ASSERT_FALSE(svr.is_running());
  4367. });
  4368. svr.wait_until_ready();
  4369. for (size_t i = 0; i < 10; i++) {
  4370. Client cli(HOST, PORT);
  4371. for (size_t j = 0; j < 100; j++) {
  4372. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4374. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4375. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4376. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4377. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4378. }
  4379. cli.set_keep_alive(true);
  4380. for (size_t j = 0; j < 100; j++) {
  4381. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4383. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4384. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4385. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4386. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4387. }
  4388. }
  4389. }
  4390. TEST(ExceptionTest, AndErrorHandler) {
  4391. Server svr;
  4392. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4393. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4394. });
  4395. svr.set_exception_handler(
  4396. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4397. EXPECT_FALSE(ep == nullptr);
  4398. try {
  4399. std::rethrow_exception(ep);
  4400. } catch (std::exception &e) {
  4401. res.set_content(e.what(), "text/html");
  4402. } catch (...) {}
  4403. res.status = StatusCode::InternalServerError_500;
  4404. });
  4405. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4406. throw std::runtime_error("EXCEPTION");
  4407. });
  4408. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4409. res.set_content("ERROR", "text/html");
  4410. res.status = StatusCode::InternalServerError_500;
  4411. });
  4412. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4413. auto se = detail::scope_exit([&] {
  4414. svr.stop();
  4415. thread.join();
  4416. ASSERT_FALSE(svr.is_running());
  4417. });
  4418. svr.wait_until_ready();
  4419. Client cli(HOST, PORT);
  4420. {
  4421. auto res = cli.Get("/exception");
  4422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4423. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4424. EXPECT_EQ("EXCEPTION", res->body);
  4425. }
  4426. {
  4427. auto res = cli.Get("/error");
  4428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4429. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4430. EXPECT_EQ("ERROR", res->body);
  4431. }
  4432. {
  4433. auto res = cli.Get("/invalid");
  4434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4435. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4436. EXPECT_EQ("NOT_FOUND", res->body);
  4437. }
  4438. }
  4439. #endif
  4440. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4441. // process_request() wraps only routing() in a try/catch, so an exception from
  4442. // any other user callback used to unwind into the task queue - which does not
  4443. // catch - and terminate the process. Each test below runs the server on a
  4444. // single worker thread: a guard that catches the exception but still loses the
  4445. // thread would otherwise be hidden by a spare worker serving the follow-up
  4446. // request. Note that a regression here aborts the whole test binary rather
  4447. // than failing one test.
  4448. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4449. Server svr;
  4450. svr.new_task_queue = [] { return new ThreadPool(1); };
  4451. std::atomic<int> reported{0};
  4452. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4453. if (err == Error::UserCallbackException) { reported++; }
  4454. });
  4455. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4456. res.set_content_provider(
  4457. 1024, "text/plain",
  4458. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4459. sink.write("hello", 5);
  4460. throw std::runtime_error("from the content provider");
  4461. });
  4462. });
  4463. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4464. res.set_content("ok", "text/plain");
  4465. });
  4466. auto port = svr.bind_to_any_port(HOST);
  4467. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4468. auto se = detail::scope_exit([&] {
  4469. svr.stop();
  4470. listen_thread.join();
  4471. ASSERT_FALSE(svr.is_running());
  4472. });
  4473. svr.wait_until_ready();
  4474. {
  4475. Client cli(HOST, port);
  4476. cli.set_read_timeout(5, 0);
  4477. EXPECT_FALSE(cli.Get("/throw"));
  4478. }
  4479. EXPECT_TRUE(svr.is_running());
  4480. EXPECT_EQ(1, reported.load());
  4481. // A request on a fresh connection is still served.
  4482. {
  4483. Client cli(HOST, port);
  4484. auto res = cli.Get("/ok");
  4485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4486. EXPECT_EQ(StatusCode::OK_200, res->status);
  4487. EXPECT_EQ("ok", res->body);
  4488. }
  4489. }
  4490. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4491. Server svr;
  4492. svr.new_task_queue = [] { return new ThreadPool(1); };
  4493. std::atomic<bool> should_throw{true};
  4494. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4495. res.set_content("hi", "text/plain");
  4496. });
  4497. svr.set_post_routing_handler(
  4498. [&](const Request & /*req*/, Response & /*res*/) {
  4499. if (should_throw) {
  4500. throw std::runtime_error("from the post-routing handler");
  4501. }
  4502. });
  4503. auto port = svr.bind_to_any_port(HOST);
  4504. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4505. auto se = detail::scope_exit([&] {
  4506. svr.stop();
  4507. listen_thread.join();
  4508. ASSERT_FALSE(svr.is_running());
  4509. });
  4510. svr.wait_until_ready();
  4511. {
  4512. Client cli(HOST, port);
  4513. cli.set_read_timeout(5, 0);
  4514. EXPECT_FALSE(cli.Get("/hi"));
  4515. }
  4516. EXPECT_TRUE(svr.is_running());
  4517. should_throw = false;
  4518. {
  4519. Client cli(HOST, port);
  4520. auto res = cli.Get("/hi");
  4521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4522. EXPECT_EQ(StatusCode::OK_200, res->status);
  4523. EXPECT_EQ("hi", res->body);
  4524. }
  4525. }
  4526. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4527. // The guard reports the caught exception through the error logger, which is
  4528. // a user callback too. A logger that throws has to be contained as well, or
  4529. // the process would terminate from inside the catch.
  4530. Server svr;
  4531. svr.new_task_queue = [] { return new ThreadPool(1); };
  4532. std::atomic<int> reported{0};
  4533. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4534. if (err == Error::UserCallbackException) {
  4535. reported++;
  4536. throw std::runtime_error("from the error logger");
  4537. }
  4538. });
  4539. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4540. res.set_content_provider(
  4541. 1024, "text/plain",
  4542. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4543. sink.write("hello", 5);
  4544. throw std::runtime_error("from the content provider");
  4545. });
  4546. });
  4547. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4548. res.set_content("ok", "text/plain");
  4549. });
  4550. auto port = svr.bind_to_any_port(HOST);
  4551. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4552. auto se = detail::scope_exit([&] {
  4553. svr.stop();
  4554. listen_thread.join();
  4555. ASSERT_FALSE(svr.is_running());
  4556. });
  4557. svr.wait_until_ready();
  4558. {
  4559. Client cli(HOST, port);
  4560. cli.set_read_timeout(5, 0);
  4561. EXPECT_FALSE(cli.Get("/throw"));
  4562. }
  4563. EXPECT_TRUE(svr.is_running());
  4564. EXPECT_EQ(1, reported.load());
  4565. {
  4566. Client cli(HOST, port);
  4567. auto res = cli.Get("/ok");
  4568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4569. EXPECT_EQ(StatusCode::OK_200, res->status);
  4570. EXPECT_EQ("ok", res->body);
  4571. }
  4572. }
  4573. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4574. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4575. // so the exception unwinds through the ws::WebSocket object on its way to
  4576. // the guard. None of the HTTP cases above cross that.
  4577. Server svr;
  4578. svr.new_task_queue = [] { return new ThreadPool(1); };
  4579. std::atomic<int> reported{0};
  4580. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4581. if (err == Error::UserCallbackException) { reported++; }
  4582. });
  4583. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4584. throw std::runtime_error("from the WebSocket handler");
  4585. });
  4586. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4587. res.set_content("ok", "text/plain");
  4588. });
  4589. auto port = svr.bind_to_any_port(HOST);
  4590. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4591. auto se = detail::scope_exit([&] {
  4592. svr.stop();
  4593. listen_thread.join();
  4594. ASSERT_FALSE(svr.is_running());
  4595. });
  4596. svr.wait_until_ready();
  4597. {
  4598. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4599. "/ws");
  4600. auto res = client.connect();
  4601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4602. // The server dropped the connection instead of dying.
  4603. std::string msg;
  4604. EXPECT_FALSE(client.read(msg));
  4605. client.close();
  4606. }
  4607. EXPECT_TRUE(svr.is_running());
  4608. EXPECT_EQ(1, reported.load());
  4609. {
  4610. Client cli(HOST, port);
  4611. auto res = cli.Get("/ok");
  4612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4613. EXPECT_EQ(StatusCode::OK_200, res->status);
  4614. EXPECT_EQ("ok", res->body);
  4615. }
  4616. }
  4617. #ifdef CPPHTTPLIB_SSL_ENABLED
  4618. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4619. // SSLServer::process_and_close_socket() is a separate overload with its own
  4620. // guard, so it is exercised on its own.
  4621. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4622. ASSERT_TRUE(svr.is_valid());
  4623. svr.new_task_queue = [] { return new ThreadPool(1); };
  4624. std::atomic<int> reported{0};
  4625. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4626. if (err == Error::UserCallbackException) { reported++; }
  4627. });
  4628. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4629. res.set_content_provider(
  4630. 1024, "text/plain",
  4631. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4632. sink.write("hello", 5);
  4633. throw std::runtime_error("from the content provider");
  4634. });
  4635. });
  4636. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4637. res.set_content("ok", "text/plain");
  4638. });
  4639. auto port = svr.bind_to_any_port(HOST);
  4640. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4641. auto se = detail::scope_exit([&] {
  4642. svr.stop();
  4643. listen_thread.join();
  4644. ASSERT_FALSE(svr.is_running());
  4645. });
  4646. svr.wait_until_ready();
  4647. {
  4648. SSLClient cli(HOST, port);
  4649. cli.enable_server_certificate_verification(false);
  4650. cli.set_read_timeout(5, 0);
  4651. EXPECT_FALSE(cli.Get("/throw"));
  4652. }
  4653. EXPECT_TRUE(svr.is_running());
  4654. EXPECT_EQ(1, reported.load());
  4655. {
  4656. SSLClient cli(HOST, port);
  4657. cli.enable_server_certificate_verification(false);
  4658. auto res = cli.Get("/ok");
  4659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4660. EXPECT_EQ(StatusCode::OK_200, res->status);
  4661. EXPECT_EQ("ok", res->body);
  4662. }
  4663. }
  4664. #endif
  4665. #endif
  4666. TEST(NoContentTest, ContentLength) {
  4667. Server svr;
  4668. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4669. res.status = StatusCode::NoContent_204;
  4670. });
  4671. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4672. auto se = detail::scope_exit([&] {
  4673. svr.stop();
  4674. thread.join();
  4675. ASSERT_FALSE(svr.is_running());
  4676. });
  4677. svr.wait_until_ready();
  4678. {
  4679. Client cli(HOST, PORT);
  4680. auto res = cli.Get("/hi");
  4681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4682. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4683. // RFC 9110 8.6: none in a 204 response
  4684. EXPECT_FALSE(res->has_header("Content-Length"));
  4685. }
  4686. }
  4687. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4688. Server svr;
  4689. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4690. res.set_header("Content-Length", "5");
  4691. res.set_content("hello world", "text/plain");
  4692. });
  4693. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4694. // A body that reads as the last chunk, were it taken as chunked
  4695. res.set_header("Transfer-Encoding", "chunked");
  4696. res.set_content("0\r\n\r\n", "text/plain");
  4697. });
  4698. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4699. res.set_header("Content-Length", "2");
  4700. res.set_content_provider(5, "text/plain",
  4701. [](size_t offset, size_t length, DataSink &sink) {
  4702. sink.write(&"hello"[offset], length);
  4703. return true;
  4704. });
  4705. });
  4706. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4707. res.set_header("Content-Length", "1234");
  4708. });
  4709. thread t = thread([&] { svr.listen(HOST, PORT); });
  4710. auto se = detail::scope_exit([&] {
  4711. svr.stop();
  4712. t.join();
  4713. ASSERT_FALSE(svr.is_running());
  4714. });
  4715. svr.wait_until_ready();
  4716. Client cli(HOST, PORT);
  4717. cli.set_read_timeout(1, 0);
  4718. auto expect_body = [&](const Result &res, const std::string &body) {
  4719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4720. EXPECT_EQ(body, res->body);
  4721. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4722. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4723. };
  4724. Headers identity{{"Accept-Encoding", ""}};
  4725. expect_body(cli.Get("/body", identity), "hello world");
  4726. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4727. expect_body(cli.Get("/body",
  4728. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4729. "he");
  4730. expect_body(cli.Get("/provider", identity), "hello");
  4731. expect_body(cli.Get("/empty", identity), "");
  4732. // A HEAD response may give the length of the body a GET would get.
  4733. auto res = cli.Head("/empty");
  4734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4735. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4736. }
  4737. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4738. Server svr;
  4739. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4740. res.set_content("short", "text/plain");
  4741. });
  4742. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4743. res.body += " with a footer";
  4744. res.set_header("Transfer-Encoding", "chunked");
  4745. });
  4746. thread t = thread([&] { svr.listen(HOST, PORT); });
  4747. auto se = detail::scope_exit([&] {
  4748. svr.stop();
  4749. t.join();
  4750. ASSERT_FALSE(svr.is_running());
  4751. });
  4752. svr.wait_until_ready();
  4753. Client cli(HOST, PORT);
  4754. cli.set_read_timeout(1, 0);
  4755. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4757. EXPECT_EQ("short with a footer", res->body);
  4758. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4759. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4760. }
  4761. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4762. #ifdef CPPHTTPLIB_SSL_ENABLED
  4763. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4764. ASSERT_TRUE(svr.is_valid());
  4765. #else
  4766. Server svr;
  4767. #endif
  4768. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4769. if (req.path == "/routing_handler") {
  4770. res.set_header("PRE_ROUTING", "on");
  4771. res.set_content("Routing Handler", "text/plain");
  4772. return httplib::Server::HandlerResponse::Handled;
  4773. }
  4774. return httplib::Server::HandlerResponse::Unhandled;
  4775. });
  4776. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4777. res.set_content("Error", "text/html");
  4778. });
  4779. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4780. if (req.path == "/routing_handler") {
  4781. res.set_header("POST_ROUTING", "on");
  4782. }
  4783. });
  4784. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4785. res.set_content("Hello World!\n", "text/plain");
  4786. });
  4787. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4788. auto se = detail::scope_exit([&] {
  4789. svr.stop();
  4790. thread.join();
  4791. ASSERT_FALSE(svr.is_running());
  4792. });
  4793. svr.wait_until_ready();
  4794. {
  4795. #ifdef CPPHTTPLIB_SSL_ENABLED
  4796. SSLClient cli(HOST, PORT);
  4797. cli.enable_server_certificate_verification(false);
  4798. #else
  4799. Client cli(HOST, PORT);
  4800. #endif
  4801. auto res = cli.Get("/routing_handler");
  4802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4803. EXPECT_EQ(StatusCode::OK_200, res->status);
  4804. EXPECT_EQ("Routing Handler", res->body);
  4805. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4806. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4807. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4808. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4809. }
  4810. {
  4811. #ifdef CPPHTTPLIB_SSL_ENABLED
  4812. SSLClient cli(HOST, PORT);
  4813. cli.enable_server_certificate_verification(false);
  4814. #else
  4815. Client cli(HOST, PORT);
  4816. #endif
  4817. auto res = cli.Get("/hi");
  4818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4819. EXPECT_EQ(StatusCode::OK_200, res->status);
  4820. EXPECT_EQ("Hello World!\n", res->body);
  4821. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4822. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4823. }
  4824. {
  4825. #ifdef CPPHTTPLIB_SSL_ENABLED
  4826. SSLClient cli(HOST, PORT);
  4827. cli.enable_server_certificate_verification(false);
  4828. #else
  4829. Client cli(HOST, PORT);
  4830. #endif
  4831. auto res = cli.Get("/aaa");
  4832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4833. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4834. EXPECT_EQ("Error", res->body);
  4835. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4836. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4837. }
  4838. }
  4839. TEST(RequestHandlerTest, PreRequestHandler) {
  4840. auto route_path = "/user/:user";
  4841. Server svr;
  4842. svr.Get("/hi", [](const Request &, Response &res) {
  4843. res.set_content("hi", "text/plain");
  4844. });
  4845. svr.Get(route_path, [](const Request &req, Response &res) {
  4846. res.set_content(req.path_params.at("user"), "text/plain");
  4847. });
  4848. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4849. if (req.matched_route == route_path) {
  4850. auto user = req.path_params.at("user");
  4851. if (user != "john") {
  4852. res.status = StatusCode::Forbidden_403;
  4853. res.set_content("error", "text/html");
  4854. return Server::HandlerResponse::Handled;
  4855. }
  4856. }
  4857. return Server::HandlerResponse::Unhandled;
  4858. });
  4859. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4860. auto se = detail::scope_exit([&] {
  4861. svr.stop();
  4862. thread.join();
  4863. ASSERT_FALSE(svr.is_running());
  4864. });
  4865. svr.wait_until_ready();
  4866. Client cli(HOST, PORT);
  4867. {
  4868. auto res = cli.Get("/hi");
  4869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4870. EXPECT_EQ(StatusCode::OK_200, res->status);
  4871. EXPECT_EQ("hi", res->body);
  4872. }
  4873. {
  4874. auto res = cli.Get("/user/john");
  4875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4876. EXPECT_EQ(StatusCode::OK_200, res->status);
  4877. EXPECT_EQ("john", res->body);
  4878. }
  4879. {
  4880. auto res = cli.Get("/user/invalid-user");
  4881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4882. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4883. EXPECT_EQ("error", res->body);
  4884. }
  4885. }
  4886. // The pre-request handler must run before the request body is read, so a
  4887. // rejected request never forces the server to buffer a (potentially large)
  4888. // body. Here the posted body is larger than the payload limit: if the body
  4889. // were read first the server would answer 413, but because the pre-request
  4890. // handler runs first it answers 403 and the body is never read.
  4891. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4892. Server svr;
  4893. svr.set_payload_max_length(8);
  4894. auto handler_ran = false;
  4895. svr.Post("/reject", [&](const Request &req, Response &res) {
  4896. handler_ran = true;
  4897. res.set_content(req.body, "text/plain");
  4898. });
  4899. svr.Post("/accept", [](const Request &req, Response &res) {
  4900. res.set_content(req.body, "text/plain");
  4901. });
  4902. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4903. if (req.matched_route == "/reject") {
  4904. res.status = StatusCode::Forbidden_403;
  4905. res.set_content("denied", "text/plain");
  4906. return Server::HandlerResponse::Handled;
  4907. }
  4908. return Server::HandlerResponse::Unhandled;
  4909. });
  4910. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4911. auto se = detail::scope_exit([&] {
  4912. svr.stop();
  4913. thread.join();
  4914. ASSERT_FALSE(svr.is_running());
  4915. });
  4916. svr.wait_until_ready();
  4917. Client cli(HOST, PORT);
  4918. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4919. // rejects with 403 before the body is read, so 413 is never reached.
  4920. {
  4921. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4923. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4924. EXPECT_EQ("denied", res->body);
  4925. EXPECT_FALSE(handler_ran);
  4926. }
  4927. // An approved route still reads the body and enforces the payload limit.
  4928. {
  4929. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4931. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4932. }
  4933. }
  4934. TEST(UserDataTest, BasicOperations) {
  4935. httplib::UserData ud;
  4936. // Initially empty
  4937. EXPECT_FALSE(ud.has("key"));
  4938. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4939. // set and get
  4940. ud.set("key", 42);
  4941. EXPECT_TRUE(ud.has("key"));
  4942. auto *p = ud.get<int>("key");
  4943. ASSERT_NE(nullptr, p);
  4944. EXPECT_EQ(42, *p);
  4945. // Type mismatch → nullptr
  4946. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4947. // Overwrite with different type
  4948. ud.set("key", std::string("hello"));
  4949. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4950. auto *s = ud.get<std::string>("key");
  4951. ASSERT_NE(nullptr, s);
  4952. EXPECT_EQ("hello", *s);
  4953. // erase
  4954. ud.erase("key");
  4955. EXPECT_FALSE(ud.has("key"));
  4956. // clear
  4957. ud.set("a", 1);
  4958. ud.set("b", 2);
  4959. ud.clear();
  4960. EXPECT_FALSE(ud.has("a"));
  4961. EXPECT_FALSE(ud.has("b"));
  4962. }
  4963. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4964. struct AuthCtx {
  4965. std::string user_id;
  4966. };
  4967. Server svr;
  4968. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4969. res.user_data.set("auth", AuthCtx{"alice"});
  4970. return Server::HandlerResponse::Unhandled;
  4971. });
  4972. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4973. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4974. ASSERT_NE(nullptr, ctx);
  4975. res.set_content("Hello " + ctx->user_id, "text/plain");
  4976. });
  4977. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4978. auto se = detail::scope_exit([&] {
  4979. svr.stop();
  4980. thread.join();
  4981. ASSERT_FALSE(svr.is_running());
  4982. });
  4983. svr.wait_until_ready();
  4984. Client cli(HOST, PORT);
  4985. auto res = cli.Get("/me");
  4986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4987. EXPECT_EQ(StatusCode::OK_200, res->status);
  4988. EXPECT_EQ("Hello alice", res->body);
  4989. }
  4990. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4991. struct RoleCtx {
  4992. std::string role;
  4993. };
  4994. Server svr;
  4995. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4996. res.user_data.set("role", RoleCtx{"admin"});
  4997. return Server::HandlerResponse::Unhandled;
  4998. });
  4999. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5000. auto *ctx = res.user_data.get<RoleCtx>("role");
  5001. ASSERT_NE(nullptr, ctx);
  5002. res.set_content(ctx->role, "text/plain");
  5003. });
  5004. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5005. auto se = detail::scope_exit([&] {
  5006. svr.stop();
  5007. thread.join();
  5008. ASSERT_FALSE(svr.is_running());
  5009. });
  5010. svr.wait_until_ready();
  5011. Client cli(HOST, PORT);
  5012. auto res = cli.Get("/role");
  5013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5014. EXPECT_EQ(StatusCode::OK_200, res->status);
  5015. EXPECT_EQ("admin", res->body);
  5016. }
  5017. TEST(InvalidFormatTest, StatusCode) {
  5018. Server svr;
  5019. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5020. res.set_content("Hello World!\n", "text/plain");
  5021. res.status = 9999; // Status should be a three-digit code...
  5022. });
  5023. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5024. auto se = detail::scope_exit([&] {
  5025. svr.stop();
  5026. thread.join();
  5027. ASSERT_FALSE(svr.is_running());
  5028. });
  5029. svr.wait_until_ready();
  5030. {
  5031. Client cli(HOST, PORT);
  5032. auto res = cli.Get("/hi");
  5033. ASSERT_FALSE(res);
  5034. }
  5035. }
  5036. TEST(URLFragmentTest, WithFragment) {
  5037. Server svr;
  5038. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5039. EXPECT_TRUE(req.target == "/hi");
  5040. });
  5041. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5042. auto se = detail::scope_exit([&] {
  5043. svr.stop();
  5044. thread.join();
  5045. ASSERT_FALSE(svr.is_running());
  5046. });
  5047. svr.wait_until_ready();
  5048. {
  5049. Client cli(HOST, PORT);
  5050. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5051. EXPECT_TRUE(res);
  5052. EXPECT_EQ(StatusCode::OK_200, res->status);
  5053. res = cli.Get("/hi%23key1=val1=key2=val2");
  5054. EXPECT_TRUE(res);
  5055. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5056. }
  5057. }
  5058. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5059. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5060. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5061. Server svr;
  5062. std::vector<std::string> targets;
  5063. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5064. targets.push_back(req.target);
  5065. });
  5066. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5067. auto se = detail::scope_exit([&] {
  5068. svr.stop();
  5069. thread.join();
  5070. ASSERT_FALSE(svr.is_running());
  5071. });
  5072. svr.wait_until_ready();
  5073. Client cli(HOST, PORT);
  5074. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5075. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5076. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5077. // A '?' after the '#' belongs to the fragment, not to the query.
  5078. Request req;
  5079. req.method = "GET";
  5080. req.path = "/hi#f?x=1";
  5081. req.params.emplace("a", "1");
  5082. Response res;
  5083. auto error = Error::Success;
  5084. EXPECT_TRUE(cli.send(req, res, error));
  5085. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5086. "/hi?a=1"}),
  5087. targets);
  5088. }
  5089. TEST(HeaderWriter, SetHeaderWriter) {
  5090. Server svr;
  5091. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5092. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5093. return detail::write_headers(strm, hdrs);
  5094. });
  5095. svr.Get("/hi", [](const Request &req, Response &res) {
  5096. auto it = req.headers.find("CustomClientHeader");
  5097. EXPECT_TRUE(it != req.headers.end());
  5098. EXPECT_EQ(it->second, "CustomClientValue");
  5099. res.set_content("Hello World!\n", "text/plain");
  5100. });
  5101. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5102. auto se = detail::scope_exit([&] {
  5103. svr.stop();
  5104. thread.join();
  5105. ASSERT_FALSE(svr.is_running());
  5106. });
  5107. svr.wait_until_ready();
  5108. {
  5109. Client cli(HOST, PORT);
  5110. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5111. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5112. return detail::write_headers(strm, hdrs);
  5113. });
  5114. auto res = cli.Get("/hi");
  5115. EXPECT_TRUE(res);
  5116. EXPECT_EQ(StatusCode::OK_200, res->status);
  5117. auto it = res->headers.find("CustomServerHeader");
  5118. EXPECT_TRUE(it != res->headers.end());
  5119. EXPECT_EQ(it->second, "CustomServerValue");
  5120. }
  5121. }
  5122. class ServerTest : public ::testing::Test {
  5123. protected:
  5124. ServerTest()
  5125. : cli_(HOST, PORT)
  5126. #ifdef CPPHTTPLIB_SSL_ENABLED
  5127. ,
  5128. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5129. #endif
  5130. {
  5131. #ifdef CPPHTTPLIB_SSL_ENABLED
  5132. cli_.enable_server_certificate_verification(false);
  5133. #endif
  5134. // Allow LARGE_DATA (100MB) responses
  5135. cli_.set_payload_max_length(200 * 1024 * 1024);
  5136. }
  5137. virtual void SetUp() {
  5138. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5139. svr_.set_payload_max_length(200 * 1024 * 1024);
  5140. svr_.set_mount_point("/", "./www");
  5141. svr_.set_mount_point("/mount", "./www2");
  5142. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5143. svr_.Get("/hi",
  5144. [&](const Request & /*req*/, Response &res) {
  5145. res.set_content("Hello World!", "text/plain");
  5146. })
  5147. .Get("/file_content",
  5148. [&](const Request & /*req*/, Response &res) {
  5149. res.set_file_content("./www/dir/test.html");
  5150. })
  5151. .Get("/file_content_with_content_type",
  5152. [&](const Request & /*req*/, Response &res) {
  5153. res.set_file_content("./www/file", "text/plain");
  5154. })
  5155. .Get("/invalid_file_content",
  5156. [&](const Request & /*req*/, Response &res) {
  5157. res.set_file_content("./www/dir/invalid_file_path");
  5158. })
  5159. .Get("/http_response_splitting",
  5160. [&](const Request & /*req*/, Response &res) {
  5161. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5162. EXPECT_EQ(0U, res.headers.size());
  5163. EXPECT_FALSE(res.has_header("a"));
  5164. res.set_header("a", "1\nSet-Cookie: a=1");
  5165. EXPECT_EQ(0U, res.headers.size());
  5166. EXPECT_FALSE(res.has_header("a"));
  5167. res.set_header("a", "1\rSet-Cookie: a=1");
  5168. EXPECT_EQ(0U, res.headers.size());
  5169. EXPECT_FALSE(res.has_header("a"));
  5170. res.set_header("a\r\nb", "0");
  5171. EXPECT_EQ(0U, res.headers.size());
  5172. EXPECT_FALSE(res.has_header("a"));
  5173. res.set_header("a\rb", "0");
  5174. EXPECT_EQ(0U, res.headers.size());
  5175. EXPECT_FALSE(res.has_header("a"));
  5176. res.set_header("a\nb", "0");
  5177. EXPECT_EQ(0U, res.headers.size());
  5178. EXPECT_FALSE(res.has_header("a"));
  5179. res.set_redirect("1\r\nSet-Cookie: a=1");
  5180. EXPECT_EQ(0U, res.headers.size());
  5181. EXPECT_FALSE(res.has_header("Location"));
  5182. })
  5183. .Get("/slow",
  5184. [&](const Request & /*req*/, Response &res) {
  5185. std::this_thread::sleep_for(std::chrono::seconds(4));
  5186. res.set_content("slow", "text/plain");
  5187. })
  5188. #if 0
  5189. .Post("/slowpost",
  5190. [&](const Request & /*req*/, Response &res) {
  5191. std::this_thread::sleep_for(std::chrono::seconds(2));
  5192. res.set_content("slow", "text/plain");
  5193. })
  5194. #endif
  5195. .Get("/remote_addr",
  5196. [&](const Request &req, Response &res) {
  5197. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5198. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5199. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5200. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5201. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5202. #endif
  5203. res.set_content(req.remote_addr, "text/plain");
  5204. })
  5205. .Get("/local_addr",
  5206. [&](const Request &req, Response &res) {
  5207. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5208. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5209. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5210. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5211. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5212. #endif
  5213. auto local_addr = req.local_addr;
  5214. auto local_port = std::to_string(req.local_port);
  5215. res.set_content(local_addr.append(":").append(local_port),
  5216. "text/plain");
  5217. })
  5218. .Get("/endwith%",
  5219. [&](const Request & /*req*/, Response &res) {
  5220. res.set_content("Hello World!", "text/plain");
  5221. })
  5222. .Get("/a\\+\\+b",
  5223. [&](const Request &req, Response &res) {
  5224. ASSERT_TRUE(req.has_param("a +b"));
  5225. auto val = req.get_param_value("a +b");
  5226. res.set_content(val, "text/plain");
  5227. })
  5228. .Get("/", [&](const Request & /*req*/,
  5229. Response &res) { res.set_redirect("/hi"); })
  5230. .Post("/1",
  5231. [](const Request & /*req*/, Response &res) {
  5232. res.set_redirect("/2", StatusCode::SeeOther_303);
  5233. })
  5234. .Get("/2",
  5235. [](const Request & /*req*/, Response &res) {
  5236. res.set_content("redirected.", "text/plain");
  5237. res.status = StatusCode::OK_200;
  5238. })
  5239. .Post("/person",
  5240. [&](const Request &req, Response &res) {
  5241. if (req.has_param("name") && req.has_param("note")) {
  5242. persons_[req.get_param_value("name")] =
  5243. req.get_param_value("note");
  5244. } else {
  5245. res.status = StatusCode::BadRequest_400;
  5246. }
  5247. })
  5248. .Put("/person",
  5249. [&](const Request &req, Response &res) {
  5250. if (req.has_param("name") && req.has_param("note")) {
  5251. persons_[req.get_param_value("name")] =
  5252. req.get_param_value("note");
  5253. } else {
  5254. res.status = StatusCode::BadRequest_400;
  5255. }
  5256. })
  5257. .Get("/person/(.*)",
  5258. [&](const Request &req, Response &res) {
  5259. string name = req.matches[1];
  5260. if (persons_.find(name) != persons_.end()) {
  5261. auto note = persons_[name];
  5262. res.set_content(note, "text/plain");
  5263. } else {
  5264. res.status = StatusCode::NotFound_404;
  5265. }
  5266. })
  5267. .Delete("/person",
  5268. [&](const Request &req, Response &res) {
  5269. if (req.has_param("name")) {
  5270. string name = req.get_param_value("name");
  5271. if (persons_.find(name) != persons_.end()) {
  5272. persons_.erase(name);
  5273. res.set_content("DELETED", "text/plain");
  5274. } else {
  5275. res.status = StatusCode::NotFound_404;
  5276. }
  5277. } else {
  5278. res.status = StatusCode::BadRequest_400;
  5279. }
  5280. })
  5281. .Post("/x-www-form-urlencoded-json",
  5282. [&](const Request &req, Response &res) {
  5283. auto json = req.get_param_value("json");
  5284. ASSERT_EQ(JSON_DATA, json);
  5285. res.set_content(json, "appliation/json");
  5286. res.status = StatusCode::OK_200;
  5287. })
  5288. .Get("/streamed-chunked",
  5289. [&](const Request & /*req*/, Response &res) {
  5290. res.set_chunked_content_provider(
  5291. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5292. sink.os << "123";
  5293. sink.os << "456";
  5294. sink.os << "789";
  5295. sink.done();
  5296. return true;
  5297. });
  5298. })
  5299. .Get("/streamed-chunked-with-prohibited-trailer",
  5300. [&](const Request & /*req*/, Response &res) {
  5301. auto i = new int(0);
  5302. // Declare both a prohibited trailer (Content-Length) and an
  5303. // allowed one
  5304. res.set_header("Trailer", "Content-Length, X-Allowed");
  5305. res.set_chunked_content_provider(
  5306. "text/plain",
  5307. [i](size_t /*offset*/, DataSink &sink) {
  5308. switch (*i) {
  5309. case 0: sink.os << "123"; break;
  5310. case 1: sink.os << "456"; break;
  5311. case 2: sink.os << "789"; break;
  5312. case 3: {
  5313. sink.done_with_trailer(
  5314. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5315. } break;
  5316. }
  5317. (*i)++;
  5318. return true;
  5319. },
  5320. [i](bool success) {
  5321. EXPECT_TRUE(success);
  5322. delete i;
  5323. });
  5324. })
  5325. .Get("/streamed-chunked2",
  5326. [&](const Request & /*req*/, Response &res) {
  5327. auto i = new int(0);
  5328. res.set_chunked_content_provider(
  5329. "text/plain",
  5330. [i](size_t /*offset*/, DataSink &sink) {
  5331. switch (*i) {
  5332. case 0: sink.os << "123"; break;
  5333. case 1: sink.os << "456"; break;
  5334. case 2: sink.os << "789"; break;
  5335. case 3: sink.done(); break;
  5336. }
  5337. (*i)++;
  5338. return true;
  5339. },
  5340. [i](bool success) {
  5341. EXPECT_TRUE(success);
  5342. delete i;
  5343. });
  5344. })
  5345. .Get("/streamed-chunked-with-trailer",
  5346. [&](const Request & /*req*/, Response &res) {
  5347. auto i = new int(0);
  5348. res.set_header("Trailer", "Dummy1, Dummy2");
  5349. res.set_chunked_content_provider(
  5350. "text/plain",
  5351. [i](size_t /*offset*/, DataSink &sink) {
  5352. switch (*i) {
  5353. case 0: sink.os << "123"; break;
  5354. case 1: sink.os << "456"; break;
  5355. case 2: sink.os << "789"; break;
  5356. case 3: {
  5357. sink.done_with_trailer(
  5358. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5359. } break;
  5360. }
  5361. (*i)++;
  5362. return true;
  5363. },
  5364. [i](bool success) {
  5365. EXPECT_TRUE(success);
  5366. delete i;
  5367. });
  5368. })
  5369. .Get("/streamed",
  5370. [&](const Request & /*req*/, Response &res) {
  5371. res.set_content_provider(
  5372. 6, "text/plain",
  5373. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5374. sink.os << (offset < 3 ? "a" : "b");
  5375. return true;
  5376. });
  5377. })
  5378. .Get("/streamed-without-length",
  5379. [&](const Request & /*req*/, Response &res) {
  5380. auto data = new std::string("abcdefg");
  5381. res.set_content_provider(
  5382. "text/plain",
  5383. [data](size_t offset, DataSink &sink) {
  5384. if (offset < data->size()) {
  5385. sink.os << data->substr(offset);
  5386. }
  5387. sink.done();
  5388. return true;
  5389. },
  5390. [data](bool success) {
  5391. EXPECT_TRUE(success);
  5392. delete data;
  5393. });
  5394. })
  5395. .Get("/streamed-with-range",
  5396. [&](const Request &req, Response &res) {
  5397. auto data = new std::string("abcdefg");
  5398. // An explicit status keeps the server from picking the 206 it
  5399. // would otherwise choose for a ranged request, so the response
  5400. // is not a partial representation.
  5401. auto status = req.get_param_value("status");
  5402. if (status == "200") {
  5403. res.status = StatusCode::OK_200;
  5404. } else if (status == "403") {
  5405. res.status = StatusCode::Forbidden_403;
  5406. }
  5407. res.set_content_provider(
  5408. data->size(), "text/plain",
  5409. [data](size_t offset, size_t length, DataSink &sink) {
  5410. size_t DATA_CHUNK_SIZE = 4;
  5411. const auto &d = *data;
  5412. auto out_len =
  5413. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5414. auto ret =
  5415. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5416. EXPECT_TRUE(ret);
  5417. return true;
  5418. },
  5419. [data, &req](bool success) {
  5420. EXPECT_EQ(success, !req.has_param("error"));
  5421. delete data;
  5422. });
  5423. })
  5424. .Get("/streamed-cancel",
  5425. [&](const Request & /*req*/, Response &res) {
  5426. res.set_content_provider(
  5427. size_t(-1), "text/plain",
  5428. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5429. sink.os << "data_chunk";
  5430. return true;
  5431. });
  5432. })
  5433. .Get("/regex-with-delimiter",
  5434. [&](const Request &req, Response & /*res*/) {
  5435. ASSERT_TRUE(req.has_param("key"));
  5436. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5437. })
  5438. .Get("/with-range",
  5439. [&](const Request & /*req*/, Response &res) {
  5440. res.set_content("abcdefg", "text/plain");
  5441. })
  5442. .Get("/test-start-time",
  5443. [&](const Request &req, Response & /*res*/) {
  5444. EXPECT_NE(req.start_time_,
  5445. std::chrono::steady_clock::time_point::min());
  5446. })
  5447. .Get("/with-range-customized-response",
  5448. [&](const Request & /*req*/, Response &res) {
  5449. res.status = StatusCode::BadRequest_400;
  5450. res.set_content(JSON_DATA, "application/json");
  5451. })
  5452. .Post("/chunked",
  5453. [&](const Request &req, Response & /*res*/) {
  5454. EXPECT_EQ(req.body, "dechunked post body");
  5455. })
  5456. .Post("/large-chunked",
  5457. [&](const Request &req, Response & /*res*/) {
  5458. std::string expected(6 * 30 * 1024u, 'a');
  5459. EXPECT_EQ(req.body, expected);
  5460. })
  5461. .Post("/multipart",
  5462. [&](const Request &req, Response & /*res*/) {
  5463. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5464. req.form.get_field_count("text2") +
  5465. req.form.get_field_count("file3") +
  5466. req.form.get_field_count("file4"));
  5467. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5468. req.form.get_file_count("file2"));
  5469. ASSERT_TRUE(!req.form.has_file("???"));
  5470. ASSERT_TRUE(!req.form.has_field("???"));
  5471. ASSERT_TRUE(req.body.empty());
  5472. {
  5473. const auto &text = req.form.get_field("text1");
  5474. EXPECT_EQ("text default", text);
  5475. }
  5476. {
  5477. const auto &text = req.form.get_field("text2");
  5478. EXPECT_EQ("aωb", text);
  5479. }
  5480. {
  5481. const auto &file = req.form.get_file("file1");
  5482. EXPECT_EQ("hello.txt", file.filename);
  5483. EXPECT_EQ("text/plain", file.content_type);
  5484. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5485. }
  5486. {
  5487. const auto &file = req.form.get_file("file2");
  5488. EXPECT_EQ("world.json", file.filename);
  5489. EXPECT_EQ("application/json", file.content_type);
  5490. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5491. }
  5492. {
  5493. const auto &text = req.form.get_field("file3");
  5494. EXPECT_EQ(0u, text.size());
  5495. }
  5496. {
  5497. const auto &text = req.form.get_field("file4");
  5498. EXPECT_EQ(0u, text.size());
  5499. }
  5500. })
  5501. .Post("/multipart/multi_file_values",
  5502. [&](const Request &req, Response & /*res*/) {
  5503. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5504. req.form.get_field_count("multi_text1"));
  5505. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5506. ASSERT_TRUE(!req.form.has_file("???"));
  5507. ASSERT_TRUE(!req.form.has_field("???"));
  5508. ASSERT_TRUE(req.body.empty());
  5509. {
  5510. const auto &text = req.form.get_field("text");
  5511. EXPECT_EQ("default text", text);
  5512. }
  5513. {
  5514. const auto &text1_values = req.form.get_fields("multi_text1");
  5515. EXPECT_EQ(2u, text1_values.size());
  5516. EXPECT_EQ("aaaaa", text1_values[0]);
  5517. EXPECT_EQ("bbbbb", text1_values[1]);
  5518. }
  5519. {
  5520. const auto &file1_values = req.form.get_files("multi_file1");
  5521. EXPECT_EQ(2u, file1_values.size());
  5522. auto file1 = file1_values[0];
  5523. EXPECT_EQ(file1.filename, "hello.txt");
  5524. EXPECT_EQ(file1.content_type, "text/plain");
  5525. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5526. auto file2 = file1_values[1];
  5527. EXPECT_EQ(file2.filename, "world.json");
  5528. EXPECT_EQ(file2.content_type, "application/json");
  5529. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5530. }
  5531. })
  5532. .Post("/empty",
  5533. [&](const Request &req, Response &res) {
  5534. EXPECT_EQ(req.body, "");
  5535. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5536. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5537. res.set_content("empty", "text/plain");
  5538. })
  5539. .Post("/empty-no-content-type",
  5540. [&](const Request &req, Response &res) {
  5541. EXPECT_EQ(req.body, "");
  5542. EXPECT_FALSE(req.has_header("Content-Type"));
  5543. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5544. res.set_content("empty-no-content-type", "text/plain");
  5545. })
  5546. .Post("/path-only",
  5547. [&](const Request &req, Response &res) {
  5548. EXPECT_EQ(req.body, "");
  5549. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5550. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5551. res.set_content("path-only", "text/plain");
  5552. })
  5553. .Post("/path-headers-only",
  5554. [&](const Request &req, Response &res) {
  5555. EXPECT_EQ(req.body, "");
  5556. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5557. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5558. EXPECT_EQ("world", req.get_header_value("hello"));
  5559. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5560. res.set_content("path-headers-only", "text/plain");
  5561. })
  5562. .Post("/post-large",
  5563. [&](const Request &req, Response &res) {
  5564. EXPECT_EQ(req.body, LARGE_DATA);
  5565. res.set_content(req.body, "text/plain");
  5566. })
  5567. .Post("/post-loopback",
  5568. [&](const Request &, Response &res,
  5569. ContentReader const &content_reader) {
  5570. std::string body;
  5571. content_reader([&](const char *data, size_t data_length) {
  5572. body.append(data, data_length);
  5573. return true;
  5574. });
  5575. res.set_content(body, "text/plain");
  5576. })
  5577. .Put("/put-loopback",
  5578. [&](const Request &, Response &res,
  5579. ContentReader const &content_reader) {
  5580. std::string body;
  5581. content_reader([&](const char *data, size_t data_length) {
  5582. body.append(data, data_length);
  5583. return true;
  5584. });
  5585. res.set_content(body, "text/plain");
  5586. })
  5587. .Patch("/patch-loopback",
  5588. [&](const Request &, Response &res,
  5589. ContentReader const &content_reader) {
  5590. std::string body;
  5591. content_reader([&](const char *data, size_t data_length) {
  5592. body.append(data, data_length);
  5593. return true;
  5594. });
  5595. res.set_content(body, "text/plain");
  5596. })
  5597. .Put("/empty-no-content-type",
  5598. [&](const Request &req, Response &res) {
  5599. EXPECT_EQ(req.body, "");
  5600. EXPECT_FALSE(req.has_header("Content-Type"));
  5601. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5602. res.set_content("empty-no-content-type", "text/plain");
  5603. })
  5604. .Put("/put",
  5605. [&](const Request &req, Response &res) {
  5606. EXPECT_EQ(req.body, "PUT");
  5607. res.set_content(req.body, "text/plain");
  5608. })
  5609. .Put("/put-large",
  5610. [&](const Request &req, Response &res) {
  5611. EXPECT_EQ(req.body, LARGE_DATA);
  5612. res.set_content(req.body, "text/plain");
  5613. })
  5614. .Patch("/patch",
  5615. [&](const Request &req, Response &res) {
  5616. EXPECT_EQ(req.body, "PATCH");
  5617. res.set_content(req.body, "text/plain");
  5618. })
  5619. .Delete("/delete",
  5620. [&](const Request & /*req*/, Response &res) {
  5621. res.set_content("DELETE", "text/plain");
  5622. })
  5623. .Delete("/delete-body",
  5624. [&](const Request &req, Response &res) {
  5625. EXPECT_EQ(req.body, "content");
  5626. res.set_content(req.body, "text/plain");
  5627. })
  5628. .Options(R"(\*)",
  5629. [&](const Request & /*req*/, Response &res) {
  5630. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5631. })
  5632. .CustomRoute("PROPFIND", "/dav/:id",
  5633. [&](const Request &req, Response &res) {
  5634. res.set_header("x-body-size",
  5635. std::to_string(req.body.size()));
  5636. res.set_header("x-matched-route", req.matched_route);
  5637. res.set_header("x-dav-id", req.path_params.at("id"));
  5638. res.status = StatusCode::MultiStatus_207;
  5639. res.set_content(req.body, "application/xml");
  5640. })
  5641. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5642. [&](const Request &req, Response &res) {
  5643. res.set_header("x-dav-match", req.matches[1]);
  5644. res.status = StatusCode::MultiStatus_207;
  5645. })
  5646. .CustomRoute("MKCOL", "/dav-mkcol",
  5647. [&](const Request &req, Response &res) {
  5648. EXPECT_TRUE(req.body.empty());
  5649. res.status = StatusCode::Created_201;
  5650. })
  5651. .CustomRoute(
  5652. "REPORT", "/dav-report",
  5653. [&](const Request & /*req*/, Response &res,
  5654. const ContentReader &content_reader) {
  5655. std::string body;
  5656. content_reader([&](const char *data, size_t data_length) {
  5657. body.append(data, data_length);
  5658. return true;
  5659. });
  5660. res.set_header("x-body-size", std::to_string(body.size()));
  5661. res.status = StatusCode::MultiStatus_207;
  5662. res.set_content(body, "application/xml");
  5663. })
  5664. .Get("/request-target",
  5665. [&](const Request &req, Response & /*res*/) {
  5666. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5667. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5668. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5669. })
  5670. .Get("/long-query-value",
  5671. [&](const Request &req, Response & /*res*/) {
  5672. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5673. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5674. })
  5675. .Get("/too-long-query-value",
  5676. [&](const Request &req, Response & /*res*/) {
  5677. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5678. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5679. })
  5680. .Get("/array-param",
  5681. [&](const Request &req, Response & /*res*/) {
  5682. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5683. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5684. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5685. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5686. })
  5687. .Get("/array-param-values",
  5688. [&](const Request &req, Response & /*res*/) {
  5689. auto values = req.get_param_values("array");
  5690. EXPECT_EQ(3u, values.size());
  5691. EXPECT_EQ("value1", values[0]);
  5692. EXPECT_EQ("value2", values[1]);
  5693. EXPECT_EQ("value3", values[2]);
  5694. auto empty = req.get_param_values("nonexistent");
  5695. EXPECT_TRUE(empty.empty());
  5696. })
  5697. .Post("/validate-no-multiple-headers",
  5698. [&](const Request &req, Response & /*res*/) {
  5699. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5700. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5701. })
  5702. .Post("/content_receiver",
  5703. [&](const Request &req, Response &res,
  5704. const ContentReader &content_reader) {
  5705. if (req.is_multipart_form_data()) {
  5706. std::vector<FormData> items;
  5707. content_reader(
  5708. [&](const FormData &file) {
  5709. items.push_back(file);
  5710. return true;
  5711. },
  5712. [&](const char *data, size_t data_length) {
  5713. items.back().content.append(data, data_length);
  5714. return true;
  5715. });
  5716. EXPECT_EQ(5u, items.size());
  5717. {
  5718. const auto &file = get_file_value(items, "text1");
  5719. EXPECT_TRUE(file.filename.empty());
  5720. EXPECT_EQ("text default", file.content);
  5721. }
  5722. {
  5723. const auto &file = get_file_value(items, "text2");
  5724. EXPECT_TRUE(file.filename.empty());
  5725. EXPECT_EQ("aωb", file.content);
  5726. }
  5727. {
  5728. const auto &file = get_file_value(items, "file1");
  5729. EXPECT_EQ("hello.txt", file.filename);
  5730. EXPECT_EQ("text/plain", file.content_type);
  5731. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5732. }
  5733. {
  5734. const auto &file = get_file_value(items, "file2");
  5735. EXPECT_EQ("world.json", file.filename);
  5736. EXPECT_EQ("application/json", file.content_type);
  5737. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5738. }
  5739. {
  5740. const auto &file = get_file_value(items, "file3");
  5741. EXPECT_TRUE(file.filename.empty());
  5742. EXPECT_EQ("application/octet-stream", file.content_type);
  5743. EXPECT_EQ(0u, file.content.size());
  5744. }
  5745. } else {
  5746. std::string body;
  5747. content_reader([&](const char *data, size_t data_length) {
  5748. EXPECT_EQ(7U, data_length);
  5749. body.append(data, data_length);
  5750. return true;
  5751. });
  5752. EXPECT_EQ(body, "content");
  5753. res.set_content(body, "text/plain");
  5754. }
  5755. })
  5756. .Put("/content_receiver",
  5757. [&](const Request & /*req*/, Response &res,
  5758. const ContentReader &content_reader) {
  5759. std::string body;
  5760. content_reader([&](const char *data, size_t data_length) {
  5761. body.append(data, data_length);
  5762. return true;
  5763. });
  5764. EXPECT_EQ(body, "content");
  5765. res.set_content(body, "text/plain");
  5766. })
  5767. .Patch("/content_receiver",
  5768. [&](const Request & /*req*/, Response &res,
  5769. const ContentReader &content_reader) {
  5770. std::string body;
  5771. content_reader([&](const char *data, size_t data_length) {
  5772. body.append(data, data_length);
  5773. return true;
  5774. });
  5775. EXPECT_EQ(body, "content");
  5776. res.set_content(body, "text/plain");
  5777. })
  5778. .Post("/query-string-and-body",
  5779. [&](const Request &req, Response & /*res*/) {
  5780. ASSERT_TRUE(req.has_param("key"));
  5781. EXPECT_EQ(req.get_param_value("key"), "value");
  5782. EXPECT_EQ(req.body, "content");
  5783. })
  5784. .Get("/last-request",
  5785. [&](const Request &req, Response & /*res*/) {
  5786. EXPECT_EQ("close", req.get_header_value("Connection"));
  5787. })
  5788. .Get(R"(/redirect/(\d+))",
  5789. [&](const Request &req, Response &res) {
  5790. auto num = std::stoi(req.matches[1]) + 1;
  5791. std::string url = "/redirect/" + std::to_string(num);
  5792. res.set_redirect(url);
  5793. })
  5794. .Post("/binary",
  5795. [&](const Request &req, Response &res) {
  5796. EXPECT_EQ(4U, req.body.size());
  5797. EXPECT_EQ("application/octet-stream",
  5798. req.get_header_value("Content-Type"));
  5799. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5800. res.set_content(req.body, "application/octet-stream");
  5801. })
  5802. .Put("/binary",
  5803. [&](const Request &req, Response &res) {
  5804. EXPECT_EQ(4U, req.body.size());
  5805. EXPECT_EQ("application/octet-stream",
  5806. req.get_header_value("Content-Type"));
  5807. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5808. res.set_content(req.body, "application/octet-stream");
  5809. })
  5810. .Patch("/binary",
  5811. [&](const Request &req, Response &res) {
  5812. EXPECT_EQ(4U, req.body.size());
  5813. EXPECT_EQ("application/octet-stream",
  5814. req.get_header_value("Content-Type"));
  5815. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5816. res.set_content(req.body, "application/octet-stream");
  5817. })
  5818. .Delete("/binary",
  5819. [&](const Request &req, Response &res) {
  5820. EXPECT_EQ(4U, req.body.size());
  5821. EXPECT_EQ("application/octet-stream",
  5822. req.get_header_value("Content-Type"));
  5823. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5824. res.set_content(req.body, "application/octet-stream");
  5825. })
  5826. .Get("/issue1772",
  5827. [&](const Request & /*req*/, Response &res) {
  5828. res.status = 401;
  5829. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5830. })
  5831. .Delete("/issue609",
  5832. [](const httplib::Request &, httplib::Response &res,
  5833. const httplib::ContentReader &) {
  5834. res.set_content("ok", "text/plain");
  5835. })
  5836. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5837. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5838. .Get("/compress",
  5839. [&](const Request & /*req*/, Response &res) {
  5840. res.set_content(
  5841. "12345678901234567890123456789012345678901234567890123456789"
  5842. "01234567890123456789012345678901234567890",
  5843. "text/plain");
  5844. })
  5845. .Get("/compress-with-charset",
  5846. [&](const Request & /*req*/, Response &res) {
  5847. res.set_content(
  5848. "12345678901234567890123456789012345678901234567890123456789"
  5849. "01234567890123456789012345678901234567890",
  5850. "application/json; charset=utf-8");
  5851. })
  5852. .Get("/nocompress",
  5853. [&](const Request & /*req*/, Response &res) {
  5854. res.set_content(
  5855. "12345678901234567890123456789012345678901234567890123456789"
  5856. "01234567890123456789012345678901234567890",
  5857. "application/octet-stream");
  5858. })
  5859. .Post("/compress-multipart",
  5860. [&](const Request &req, Response & /*res*/) {
  5861. EXPECT_EQ(2u, req.form.fields.size());
  5862. ASSERT_TRUE(!req.form.has_field("???"));
  5863. {
  5864. const auto &text = req.form.get_field("key1");
  5865. EXPECT_EQ("test", text);
  5866. }
  5867. {
  5868. const auto &text = req.form.get_field("key2");
  5869. EXPECT_EQ("--abcdefg123", text);
  5870. }
  5871. })
  5872. #endif
  5873. ;
  5874. persons_["john"] = "programmer";
  5875. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5876. svr_.wait_until_ready();
  5877. }
  5878. virtual void TearDown() {
  5879. svr_.stop();
  5880. if (!request_threads_.empty()) {
  5881. std::this_thread::sleep_for(std::chrono::seconds(1));
  5882. for (auto &t : request_threads_) {
  5883. t.join();
  5884. }
  5885. }
  5886. t_.join();
  5887. }
  5888. map<string, string> persons_;
  5889. #ifdef CPPHTTPLIB_SSL_ENABLED
  5890. SSLClient cli_;
  5891. SSLServer svr_;
  5892. #else
  5893. Client cli_;
  5894. Server svr_;
  5895. #endif
  5896. thread t_;
  5897. std::vector<thread> request_threads_;
  5898. };
  5899. TEST_F(ServerTest, GetMethod200) {
  5900. auto res = cli_.Get("/hi");
  5901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5902. EXPECT_EQ("HTTP/1.1", res->version);
  5903. EXPECT_EQ(StatusCode::OK_200, res->status);
  5904. EXPECT_EQ("OK", res->reason);
  5905. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5906. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5907. EXPECT_EQ("Hello World!", res->body);
  5908. }
  5909. TEST_F(ServerTest, GetEmptyFile) {
  5910. auto res = cli_.Get("/empty_file");
  5911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5912. EXPECT_EQ(StatusCode::OK_200, res->status);
  5913. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5914. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5915. EXPECT_EQ("", res->body);
  5916. }
  5917. TEST_F(ServerTest, GetFileContent) {
  5918. auto res = cli_.Get("/file_content");
  5919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5920. EXPECT_EQ(StatusCode::OK_200, res->status);
  5921. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5922. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5923. EXPECT_EQ("test.html", res->body);
  5924. }
  5925. TEST_F(ServerTest, GetFileContentWithRange) {
  5926. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5928. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5929. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5930. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5931. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5932. EXPECT_EQ("est", res->body);
  5933. }
  5934. TEST_F(ServerTest, GetFileContentWithContentType) {
  5935. auto res = cli_.Get("/file_content_with_content_type");
  5936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5937. EXPECT_EQ(StatusCode::OK_200, res->status);
  5938. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5939. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5940. EXPECT_EQ("file\n", res->body);
  5941. }
  5942. TEST_F(ServerTest, GetInvalidFileContent) {
  5943. auto res = cli_.Get("/invalid_file_content");
  5944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5945. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5946. }
  5947. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5948. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5950. EXPECT_EQ("HTTP/1.1", res->version);
  5951. EXPECT_EQ(StatusCode::OK_200, res->status);
  5952. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5953. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5954. EXPECT_EQ("Hello World!", res->body);
  5955. }
  5956. TEST_F(ServerTest, GetMethod302) {
  5957. auto res = cli_.Get("/");
  5958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5959. EXPECT_EQ(StatusCode::Found_302, res->status);
  5960. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5961. }
  5962. TEST_F(ServerTest, GetMethod302Redirect) {
  5963. cli_.set_follow_location(true);
  5964. auto res = cli_.Get("/");
  5965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5966. EXPECT_EQ(StatusCode::OK_200, res->status);
  5967. EXPECT_EQ("Hello World!", res->body);
  5968. EXPECT_EQ("/hi", res->location);
  5969. }
  5970. TEST_F(ServerTest, GetMethod404) {
  5971. auto res = cli_.Get("/invalid");
  5972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5973. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5974. }
  5975. TEST_F(ServerTest, HeadMethod200) {
  5976. auto res = cli_.Head("/hi");
  5977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5978. EXPECT_EQ(StatusCode::OK_200, res->status);
  5979. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5980. EXPECT_TRUE(res->body.empty());
  5981. }
  5982. TEST_F(ServerTest, HeadMethod200Static) {
  5983. auto res = cli_.Head("/mount/dir/index.html");
  5984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5985. EXPECT_EQ(StatusCode::OK_200, res->status);
  5986. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5987. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5988. EXPECT_TRUE(res->body.empty());
  5989. }
  5990. TEST_F(ServerTest, HeadMethod404) {
  5991. auto res = cli_.Head("/invalid");
  5992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5993. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5994. EXPECT_TRUE(res->body.empty());
  5995. }
  5996. TEST_F(ServerTest, GetMethodPersonJohn) {
  5997. auto res = cli_.Get("/person/john");
  5998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5999. EXPECT_EQ(StatusCode::OK_200, res->status);
  6000. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6001. EXPECT_EQ("programmer", res->body);
  6002. }
  6003. TEST_F(ServerTest, PostMethod1) {
  6004. auto res = cli_.Get("/person/john1");
  6005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6006. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6007. res = cli_.Post("/person", "name=john1&note=coder",
  6008. "application/x-www-form-urlencoded");
  6009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6010. ASSERT_EQ(StatusCode::OK_200, res->status);
  6011. res = cli_.Get("/person/john1");
  6012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6013. ASSERT_EQ(StatusCode::OK_200, res->status);
  6014. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6015. ASSERT_EQ("coder", res->body);
  6016. }
  6017. TEST_F(ServerTest, PostMethod2) {
  6018. auto res = cli_.Get("/person/john2");
  6019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6020. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6021. Params params;
  6022. params.emplace("name", "john2");
  6023. params.emplace("note", "coder");
  6024. res = cli_.Post("/person", params);
  6025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6026. ASSERT_EQ(StatusCode::OK_200, res->status);
  6027. res = cli_.Get("/person/john2");
  6028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6029. ASSERT_EQ(StatusCode::OK_200, res->status);
  6030. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6031. ASSERT_EQ("coder", res->body);
  6032. }
  6033. TEST_F(ServerTest, PutMethod3) {
  6034. auto res = cli_.Get("/person/john3");
  6035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6036. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6037. Params params;
  6038. params.emplace("name", "john3");
  6039. params.emplace("note", "coder");
  6040. res = cli_.Put("/person", params);
  6041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6042. ASSERT_EQ(StatusCode::OK_200, res->status);
  6043. res = cli_.Get("/person/john3");
  6044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6045. ASSERT_EQ(StatusCode::OK_200, res->status);
  6046. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6047. ASSERT_EQ("coder", res->body);
  6048. }
  6049. TEST_F(ServerTest, DeleteMethod1) {
  6050. auto res = cli_.Get("/person/john4");
  6051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6052. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6053. Params params;
  6054. params.emplace("name", "john4");
  6055. params.emplace("note", "coder");
  6056. res = cli_.Post("/person", params);
  6057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6058. ASSERT_EQ(StatusCode::OK_200, res->status);
  6059. res = cli_.Get("/person/john4");
  6060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6061. ASSERT_EQ(StatusCode::OK_200, res->status);
  6062. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6063. ASSERT_EQ("coder", res->body);
  6064. Params delete_params;
  6065. delete_params.emplace("name", "john4");
  6066. res = cli_.Delete("/person", delete_params);
  6067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6068. ASSERT_EQ(StatusCode::OK_200, res->status);
  6069. ASSERT_EQ("DELETED", res->body);
  6070. res = cli_.Get("/person/john4");
  6071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6072. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6073. }
  6074. TEST_F(ServerTest, DeleteMethod2) {
  6075. auto res = cli_.Get("/person/john5");
  6076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6077. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6078. Params params;
  6079. params.emplace("name", "john5");
  6080. params.emplace("note", "developer");
  6081. res = cli_.Post("/person", params);
  6082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6083. ASSERT_EQ(StatusCode::OK_200, res->status);
  6084. res = cli_.Get("/person/john5");
  6085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6086. ASSERT_EQ(StatusCode::OK_200, res->status);
  6087. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6088. ASSERT_EQ("developer", res->body);
  6089. Params delete_params;
  6090. delete_params.emplace("name", "john5");
  6091. Headers headers;
  6092. headers.emplace("Custom-Header", "test-value");
  6093. res = cli_.Delete("/person", headers, delete_params);
  6094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6095. ASSERT_EQ(StatusCode::OK_200, res->status);
  6096. ASSERT_EQ("DELETED", res->body);
  6097. res = cli_.Get("/person/john5");
  6098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6099. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6100. }
  6101. TEST_F(ServerTest, DeleteMethod3) {
  6102. auto res = cli_.Get("/person/john6");
  6103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6104. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6105. Params params;
  6106. params.emplace("name", "john6");
  6107. params.emplace("note", "tester");
  6108. res = cli_.Post("/person", params);
  6109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6110. ASSERT_EQ(StatusCode::OK_200, res->status);
  6111. res = cli_.Get("/person/john6");
  6112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6113. ASSERT_EQ(StatusCode::OK_200, res->status);
  6114. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6115. ASSERT_EQ("tester", res->body);
  6116. Params delete_params;
  6117. delete_params.emplace("name", "john6");
  6118. Headers headers;
  6119. headers.emplace("Custom-Header", "test-value");
  6120. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6122. ASSERT_EQ(StatusCode::OK_200, res->status);
  6123. ASSERT_EQ("DELETED", res->body);
  6124. res = cli_.Get("/person/john6");
  6125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6126. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6127. }
  6128. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6129. Params params;
  6130. params.emplace("json", JSON_DATA);
  6131. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6133. ASSERT_EQ(StatusCode::OK_200, res->status);
  6134. ASSERT_EQ(JSON_DATA, res->body);
  6135. }
  6136. TEST_F(ServerTest, PostEmptyContent) {
  6137. auto res = cli_.Post("/empty", "", "text/plain");
  6138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6139. ASSERT_EQ(StatusCode::OK_200, res->status);
  6140. ASSERT_EQ("empty", res->body);
  6141. }
  6142. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6143. auto res = cli_.Post("/empty-no-content-type");
  6144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6145. ASSERT_EQ(StatusCode::OK_200, res->status);
  6146. ASSERT_EQ("empty-no-content-type", res->body);
  6147. }
  6148. TEST_F(ServerTest, PostPathOnly) {
  6149. auto res = cli_.Post("/path-only");
  6150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6151. ASSERT_EQ(StatusCode::OK_200, res->status);
  6152. ASSERT_EQ("path-only", res->body);
  6153. }
  6154. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6155. auto res = cli_.Post("/path-headers-only",
  6156. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6158. ASSERT_EQ(StatusCode::OK_200, res->status);
  6159. ASSERT_EQ("path-headers-only", res->body);
  6160. }
  6161. TEST_F(ServerTest, PostLarge) {
  6162. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6164. ASSERT_EQ(StatusCode::OK_200, res->status);
  6165. EXPECT_EQ(LARGE_DATA, res->body);
  6166. }
  6167. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6168. auto res = cli_.Put("/empty-no-content-type");
  6169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6170. ASSERT_EQ(StatusCode::OK_200, res->status);
  6171. ASSERT_EQ("empty-no-content-type", res->body);
  6172. }
  6173. TEST_F(ServerTest, GetMethodDir) {
  6174. auto res = cli_.Get("/dir/");
  6175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6176. EXPECT_EQ(StatusCode::OK_200, res->status);
  6177. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6178. auto body = R"(<html>
  6179. <head>
  6180. </head>
  6181. <body>
  6182. <a href="/dir/test.html">Test</a>
  6183. <a href="/hi">hi</a>
  6184. </body>
  6185. </html>
  6186. )";
  6187. EXPECT_EQ(body, res->body);
  6188. }
  6189. TEST_F(ServerTest, GetMethodDirTest) {
  6190. auto res = cli_.Get("/dir/test.html");
  6191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6192. EXPECT_EQ(StatusCode::OK_200, res->status);
  6193. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6194. EXPECT_EQ("test.html", res->body);
  6195. }
  6196. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6197. auto res = cli_.Get("/dir/../dir/test.html");
  6198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6199. EXPECT_EQ(StatusCode::OK_200, res->status);
  6200. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6201. EXPECT_EQ("test.html", res->body);
  6202. }
  6203. TEST_F(ServerTest, GetMethodInvalidPath) {
  6204. auto res = cli_.Get("/dir/../test.html");
  6205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6206. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6207. }
  6208. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6209. auto res = cli_.Get("/../www/dir/test.html");
  6210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6211. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6212. }
  6213. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6214. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6216. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6217. }
  6218. TEST_F(ServerTest, GetMethodDirMountTest) {
  6219. auto res = cli_.Get("/mount/dir/test.html");
  6220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6221. EXPECT_EQ(StatusCode::OK_200, res->status);
  6222. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6223. EXPECT_EQ("test.html", res->body);
  6224. }
  6225. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6226. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6228. EXPECT_EQ(StatusCode::OK_200, res->status);
  6229. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6230. EXPECT_EQ("test.html", res->body);
  6231. }
  6232. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6233. auto res = cli_.Get("/mount/dir/../test.html");
  6234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6235. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6236. }
  6237. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6238. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6240. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6241. }
  6242. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6243. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6245. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6246. }
  6247. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6248. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6250. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6251. }
  6252. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6253. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6255. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6256. }
  6257. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6258. auto res = cli_.Get("/mount/dir");
  6259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6260. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6261. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6262. }
  6263. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6264. auto res = cli_.Get("//dir");
  6265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6266. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6267. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6268. }
  6269. TEST_F(ServerTest, PostMethod303) {
  6270. auto res = cli_.Post("/1", "body", "text/plain");
  6271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6272. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6273. EXPECT_EQ("/2", res->get_header_value("Location"));
  6274. }
  6275. TEST_F(ServerTest, PostMethod303Redirect) {
  6276. cli_.set_follow_location(true);
  6277. auto res = cli_.Post("/1", "body", "text/plain");
  6278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6279. EXPECT_EQ(StatusCode::OK_200, res->status);
  6280. EXPECT_EQ("redirected.", res->body);
  6281. EXPECT_EQ("/2", res->location);
  6282. }
  6283. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6284. auto res = cli_.Get("/dir/test.abcde");
  6285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6286. EXPECT_EQ(StatusCode::OK_200, res->status);
  6287. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6288. EXPECT_EQ("abcde", res->body);
  6289. }
  6290. TEST_F(ServerTest, StaticFileRange) {
  6291. auto res =
  6292. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6294. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6295. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6296. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6297. EXPECT_EQ(true, res->has_header("Content-Range"));
  6298. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6299. EXPECT_EQ(std::string("cd"), res->body);
  6300. }
  6301. TEST_F(ServerTest, StaticFileRanges) {
  6302. auto res = cli_.Get("/dir/test.abcde",
  6303. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6305. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6306. EXPECT_TRUE(
  6307. res->get_header_value("Content-Type")
  6308. .find(
  6309. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6310. 0);
  6311. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6312. }
  6313. TEST_F(ServerTest, StaticFileRangeHead) {
  6314. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6316. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6317. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6318. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6319. EXPECT_EQ(true, res->has_header("Content-Range"));
  6320. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6321. }
  6322. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6323. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6325. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6326. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6327. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6328. EXPECT_EQ(true, res->has_header("Content-Range"));
  6329. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6330. res->get_header_value("Content-Range"));
  6331. EXPECT_EQ("LAST\n", res->body);
  6332. }
  6333. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6334. auto res =
  6335. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6337. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6338. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6339. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6340. EXPECT_EQ(true, res->has_header("Content-Range"));
  6341. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6342. }
  6343. TEST_F(ServerTest, StaticFileBigFile) {
  6344. auto res = cli_.Get("/dir/1MB.txt");
  6345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6346. EXPECT_EQ(StatusCode::OK_200, res->status);
  6347. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6348. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6349. }
  6350. TEST_F(ServerTest, InvalidBaseDirMount) {
  6351. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6352. }
  6353. TEST_F(ServerTest, Binary) {
  6354. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6355. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6356. "application/octet-stream");
  6357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6358. ASSERT_EQ(StatusCode::OK_200, res->status);
  6359. ASSERT_EQ(4U, res->body.size());
  6360. res = cli_.Put("/binary", binary.data(), binary.size(),
  6361. "application/octet-stream");
  6362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6363. ASSERT_EQ(StatusCode::OK_200, res->status);
  6364. ASSERT_EQ(4U, res->body.size());
  6365. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6366. "application/octet-stream");
  6367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6368. ASSERT_EQ(StatusCode::OK_200, res->status);
  6369. ASSERT_EQ(4U, res->body.size());
  6370. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6371. "application/octet-stream");
  6372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6373. ASSERT_EQ(StatusCode::OK_200, res->status);
  6374. ASSERT_EQ(4U, res->body.size());
  6375. }
  6376. TEST_F(ServerTest, BinaryString) {
  6377. auto binary = std::string("\x00\x01\x02\x03", 4);
  6378. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6380. ASSERT_EQ(StatusCode::OK_200, res->status);
  6381. ASSERT_EQ(4U, res->body.size());
  6382. res = cli_.Put("/binary", binary, "application/octet-stream");
  6383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6384. ASSERT_EQ(StatusCode::OK_200, res->status);
  6385. ASSERT_EQ(4U, res->body.size());
  6386. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6388. ASSERT_EQ(StatusCode::OK_200, res->status);
  6389. ASSERT_EQ(4U, res->body.size());
  6390. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6392. ASSERT_EQ(StatusCode::OK_200, res->status);
  6393. ASSERT_EQ(4U, res->body.size());
  6394. }
  6395. TEST_F(ServerTest, EmptyRequest) {
  6396. auto res = cli_.Get("");
  6397. ASSERT_TRUE(!res);
  6398. EXPECT_EQ(Error::Connection, res.error());
  6399. }
  6400. TEST_F(ServerTest, LongRequest) {
  6401. std::string request;
  6402. for (size_t i = 0; i < 545; i++) {
  6403. request += "/TooLongRequest";
  6404. }
  6405. request += "OK";
  6406. auto res = cli_.Get(request.c_str());
  6407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6408. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6409. }
  6410. TEST_F(ServerTest, TooLongRequest) {
  6411. std::string request;
  6412. for (size_t i = 0; i < 546; i++) {
  6413. request += "/TooLongRequest";
  6414. }
  6415. request += "_NG";
  6416. auto start = std::chrono::high_resolution_clock::now();
  6417. cli_.set_keep_alive(true);
  6418. auto res = cli_.Get(request.c_str());
  6419. auto end = std::chrono::high_resolution_clock::now();
  6420. auto elapsed =
  6421. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6422. .count();
  6423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6424. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6425. EXPECT_LE(elapsed, 1000);
  6426. EXPECT_EQ("close", res->get_header_value("Connection"));
  6427. EXPECT_FALSE(cli_.is_socket_open());
  6428. }
  6429. TEST_F(ServerTest, AlmostTooLongRequest) {
  6430. // test for #2046 - URI length check shouldn't include other content on req
  6431. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6432. // leading /, space, HTTP/1.1)
  6433. std::string request =
  6434. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6435. auto res = cli_.Get(request.c_str());
  6436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6437. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6438. }
  6439. TEST_F(ServerTest, LongHeader) {
  6440. Request req;
  6441. req.method = "GET";
  6442. req.path = "/hi";
  6443. std::string host_and_port;
  6444. host_and_port += HOST;
  6445. host_and_port += ":";
  6446. host_and_port += std::to_string(PORT);
  6447. req.headers.emplace("Host", host_and_port.c_str());
  6448. req.headers.emplace("Accept", "*/*");
  6449. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6450. req.headers.emplace(
  6451. "Header-Name",
  6452. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6453. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6454. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6455. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6456. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6457. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6458. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6459. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6460. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6461. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6462. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6463. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6464. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6465. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6466. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6467. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6468. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6469. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6470. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6471. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6472. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6473. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6474. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6475. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6476. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6477. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6478. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6479. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6480. "@@@@@@@@@@@@@@@@");
  6481. auto res = std::make_shared<Response>();
  6482. auto error = Error::Success;
  6483. auto ret = cli_.send(req, *res, error);
  6484. ASSERT_TRUE(ret);
  6485. EXPECT_EQ(StatusCode::OK_200, res->status);
  6486. }
  6487. TEST_F(ServerTest, LongQueryValue) {
  6488. auto start = std::chrono::high_resolution_clock::now();
  6489. cli_.set_keep_alive(true);
  6490. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6491. auto end = std::chrono::high_resolution_clock::now();
  6492. auto elapsed =
  6493. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6494. .count();
  6495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6496. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6497. EXPECT_LE(elapsed, 1000);
  6498. EXPECT_EQ("close", res->get_header_value("Connection"));
  6499. EXPECT_FALSE(cli_.is_socket_open());
  6500. }
  6501. TEST_F(ServerTest, TooLongQueryValue) {
  6502. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6503. ASSERT_FALSE(res);
  6504. EXPECT_EQ(Error::Read, res.error());
  6505. }
  6506. TEST_F(ServerTest, TooLongHeader) {
  6507. Request req;
  6508. req.method = "GET";
  6509. req.path = "/hi";
  6510. std::string host_and_port;
  6511. host_and_port += HOST;
  6512. host_and_port += ":";
  6513. host_and_port += std::to_string(PORT);
  6514. req.headers.emplace("Host", host_and_port.c_str());
  6515. req.headers.emplace("Accept", "*/*");
  6516. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6517. req.headers.emplace(
  6518. "Header-Name",
  6519. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6520. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6521. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6522. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6523. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6524. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6525. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6526. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6527. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6528. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6529. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6530. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6531. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6532. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6533. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6534. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6535. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6536. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6537. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6538. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6539. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6540. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6541. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6542. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6543. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6544. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6545. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6546. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6547. "@@@@@@@@@@@@@@@@@");
  6548. auto res = std::make_shared<Response>();
  6549. auto error = Error::Success;
  6550. auto ret = cli_.send(req, *res, error);
  6551. ASSERT_TRUE(ret);
  6552. EXPECT_EQ(StatusCode::OK_200, res->status);
  6553. }
  6554. TEST_F(ServerTest, HeaderCountAtLimit) {
  6555. // Test with headers just under the 100 limit
  6556. httplib::Headers headers;
  6557. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6558. // This should keep us just under the 100 header limit
  6559. for (int i = 0; i < 95; i++) {
  6560. std::string name = "X-Test-Header-" + std::to_string(i);
  6561. std::string value = "value" + std::to_string(i);
  6562. headers.emplace(name, value);
  6563. }
  6564. // This should work fine as we're under the limit
  6565. auto res = cli_.Get("/hi", headers);
  6566. EXPECT_TRUE(res);
  6567. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6568. }
  6569. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6570. // Test with many headers to exceed the 100 limit
  6571. httplib::Headers headers;
  6572. // Add 150 headers to definitely exceed the 100 limit
  6573. for (int i = 0; i < 150; i++) {
  6574. std::string name = "X-Test-Header-" + std::to_string(i);
  6575. std::string value = "value" + std::to_string(i);
  6576. headers.emplace(name, value);
  6577. }
  6578. // This should fail due to exceeding header count limit
  6579. cli_.set_keep_alive(true);
  6580. auto res = cli_.Get("/hi", headers);
  6581. // The server should respond with 400 Bad Request
  6582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6583. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6584. EXPECT_EQ("close", res->get_header_value("Connection"));
  6585. EXPECT_FALSE(cli_.is_socket_open());
  6586. }
  6587. TEST_F(ServerTest, PercentEncoding) {
  6588. auto res = cli_.Get("/e%6edwith%");
  6589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6590. EXPECT_EQ(StatusCode::OK_200, res->status);
  6591. }
  6592. TEST_F(ServerTest, PercentEncodingUnicode) {
  6593. auto res = cli_.Get("/e%u006edwith%");
  6594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6595. EXPECT_EQ(StatusCode::OK_200, res->status);
  6596. }
  6597. TEST_F(ServerTest, InvalidPercentEncoding) {
  6598. auto res = cli_.Get("/%endwith%");
  6599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6600. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6601. }
  6602. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6603. auto res = cli_.Get("/%uendwith%");
  6604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6605. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6606. }
  6607. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6608. auto res = cli_.Get("/hello?aaa=bbb%");
  6609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6610. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6611. }
  6612. TEST_F(ServerTest, PlusSignEncoding) {
  6613. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6615. EXPECT_EQ(StatusCode::OK_200, res->status);
  6616. EXPECT_EQ("a +b", res->body);
  6617. }
  6618. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6619. // This test simulates a potential DoS attack using many headers
  6620. // to verify our security fix prevents memory exhaustion
  6621. httplib::Headers attack_headers;
  6622. // Attempt to add many headers like an attacker would (200 headers to far
  6623. // exceed limit)
  6624. for (int i = 0; i < 200; i++) {
  6625. std::string name = "X-Attack-Header-" + std::to_string(i);
  6626. std::string value = "attack_payload_" + std::to_string(i);
  6627. attack_headers.emplace(name, value);
  6628. }
  6629. // Try to POST with excessive headers
  6630. cli_.set_keep_alive(true);
  6631. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6632. // Should either fail or return 400 Bad Request due to security limit
  6633. if (res) {
  6634. // If we get a response, it should be 400 Bad Request
  6635. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6636. EXPECT_EQ("close", res->get_header_value("Connection"));
  6637. }
  6638. EXPECT_FALSE(cli_.is_socket_open());
  6639. }
  6640. TEST_F(ServerTest, MultipartFormData) {
  6641. UploadFormDataItems items = {
  6642. {"text1", "text default", "", ""},
  6643. {"text2", "aωb", "", ""},
  6644. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6645. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6646. {"file3", "", "", "application/octet-stream"},
  6647. {"file4", "", "", " application/json tmp-string "}};
  6648. auto res = cli_.Post("/multipart", items);
  6649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6650. EXPECT_EQ(StatusCode::OK_200, res->status);
  6651. }
  6652. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6653. UploadFormDataItems items = {
  6654. {"text", "default text", "", ""},
  6655. {"multi_text1", "aaaaa", "", ""},
  6656. {"multi_text1", "bbbbb", "", ""},
  6657. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6658. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6659. "application/json"},
  6660. };
  6661. auto res = cli_.Post("/multipart/multi_file_values", items);
  6662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6663. EXPECT_EQ(StatusCode::OK_200, res->status);
  6664. }
  6665. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6666. auto res = cli_.Get("/hi");
  6667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6668. EXPECT_EQ(StatusCode::OK_200, res->status);
  6669. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6670. EXPECT_EQ("Hello World!", res->body);
  6671. }
  6672. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6673. Request req;
  6674. req.method = "POST";
  6675. req.path = "/chunked";
  6676. std::string host_and_port;
  6677. host_and_port += HOST;
  6678. host_and_port += ":";
  6679. host_and_port += std::to_string(PORT);
  6680. req.headers.emplace("Host", host_and_port.c_str());
  6681. req.headers.emplace("Accept", "*/*");
  6682. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6683. req.headers.emplace("Content-Type", "text/plain");
  6684. req.headers.emplace("Content-Length", "0");
  6685. req.headers.emplace(
  6686. "Transfer-Encoding",
  6687. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6688. // Client does not chunk, so make a chunked body manually.
  6689. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6690. auto res = std::make_shared<Response>();
  6691. auto error = Error::Success;
  6692. auto ret = cli_.send(req, *res, error);
  6693. ASSERT_TRUE(ret);
  6694. EXPECT_EQ(StatusCode::OK_200, res->status);
  6695. }
  6696. template <typename ClientT>
  6697. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6698. int expected_status) {
  6699. Request req;
  6700. req.method = "POST";
  6701. req.path = "/chunked";
  6702. std::string host_and_port;
  6703. host_and_port += HOST;
  6704. host_and_port += ":";
  6705. host_and_port += std::to_string(PORT);
  6706. req.headers.emplace("Host", host_and_port.c_str());
  6707. req.headers.emplace("Content-Length", "0");
  6708. req.headers.emplace("Transfer-Encoding", "chunked");
  6709. req.body = body;
  6710. auto res = std::make_shared<Response>();
  6711. auto error = Error::Success;
  6712. ASSERT_TRUE(cli.send(req, *res, error));
  6713. EXPECT_EQ(expected_status, res->status);
  6714. }
  6715. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6716. // rather than treat them as valid lengths.
  6717. template <typename ClientT>
  6718. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6719. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6720. }
  6721. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6722. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6723. }
  6724. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6725. expect_chunked_body_rejected(
  6726. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6727. }
  6728. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6729. // chunk-size line carries no CR, LF or other control character ahead of its
  6730. // terminator. Such a line must be refused rather than read as extension text.
  6731. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6732. expect_chunked_body_rejected(
  6733. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6734. }
  6735. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6736. expect_chunked_body_rejected(
  6737. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6738. }
  6739. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6740. expect_chunked_body_rejected(
  6741. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6742. }
  6743. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6744. // The literal stays split: a hex escape consumes every hex digit that
  6745. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6746. expect_chunked_body_rejected(
  6747. cli_, "4;a\x01"
  6748. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6749. }
  6750. TEST_F(ServerTest, AcceptsChunkExtension) {
  6751. expect_chunked_body_status(cli_,
  6752. "4;name=value\r\ndech\r\n"
  6753. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6754. "0;last\r\n\r\n",
  6755. StatusCode::OK_200);
  6756. }
  6757. TEST_F(ServerTest, GetStreamed2) {
  6758. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6760. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6761. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6762. EXPECT_EQ(true, res->has_header("Content-Range"));
  6763. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6764. EXPECT_EQ(std::string("ab"), res->body);
  6765. }
  6766. TEST_F(ServerTest, GetStreamed) {
  6767. auto res = cli_.Get("/streamed");
  6768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6769. EXPECT_EQ(StatusCode::OK_200, res->status);
  6770. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6771. EXPECT_EQ(std::string("aaabbb"), res->body);
  6772. }
  6773. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6774. auto res = cli_.Get("/streamed-without-length",
  6775. Headers{make_range_header({{0, -1}})});
  6776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6777. EXPECT_EQ(StatusCode::OK_200, res->status);
  6778. EXPECT_EQ(false, res->has_header("Content-Length"));
  6779. EXPECT_EQ(false, res->has_header("Content-Range"));
  6780. EXPECT_EQ(std::string("abcdefg"), res->body);
  6781. }
  6782. TEST_F(ServerTest, GetStreamedWithRange1) {
  6783. auto res =
  6784. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6786. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6787. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6788. EXPECT_EQ(true, res->has_header("Content-Range"));
  6789. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6790. EXPECT_EQ(std::string("def"), res->body);
  6791. }
  6792. TEST_F(ServerTest, GetStreamedWithRange2) {
  6793. auto res =
  6794. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6796. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6797. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6798. EXPECT_EQ(true, res->has_header("Content-Range"));
  6799. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6800. EXPECT_EQ(std::string("bcdefg"), res->body);
  6801. }
  6802. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6803. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6805. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6806. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6807. EXPECT_EQ(true, res->has_header("Content-Range"));
  6808. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6809. EXPECT_EQ(std::string("efg"), res->body);
  6810. }
  6811. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6812. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6813. // the entire representation.
  6814. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6815. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6817. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6818. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6819. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6820. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6821. }
  6822. }
  6823. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6824. auto res =
  6825. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6827. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6828. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6829. EXPECT_EQ(false, res->has_header("Content-Range"));
  6830. EXPECT_EQ(0U, res->body.size());
  6831. }
  6832. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6833. // Only a 206 is served as a partial representation. Under any other status
  6834. // `apply_ranges()` reported the full content length, so the body must match
  6835. // that header, and the content provider must never be asked for an offset
  6836. // outside the representation.
  6837. auto check = [&](int status, const char *range) {
  6838. auto path =
  6839. std::string("/streamed-with-range?status=") + std::to_string(status);
  6840. auto ctx = path + " Range: " + range;
  6841. auto res = cli_.Get(path, Headers{{"Range", range}});
  6842. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6843. EXPECT_EQ(status, res->status) << ctx;
  6844. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6845. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6846. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6847. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6848. };
  6849. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6850. check(403, "bytes=3-5");
  6851. // The offset is far past the representation.
  6852. check(403, "bytes=100000-100200");
  6853. // `first_pos` is still -1 here, and the bounds asserts in
  6854. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6855. check(403, "bytes=-3");
  6856. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6857. // multipart branch would have written one that is empty.
  6858. check(403, "bytes=1-2, 4-5");
  6859. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6860. // covers the whole representation.
  6861. check(200, "bytes=3-5");
  6862. check(200, "bytes=1-2, 4-5");
  6863. }
  6864. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6865. auto res =
  6866. cli_.Get("/streamed-with-range",
  6867. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6868. "92233720368547758079223372036854775807"}});
  6869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6870. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6871. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6872. EXPECT_EQ(false, res->has_header("Content-Range"));
  6873. EXPECT_EQ(0U, res->body.size());
  6874. }
  6875. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6876. auto res = cli_.Get(
  6877. "/with-range",
  6878. Headers{{"Range",
  6879. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6880. {"Accept-Encoding", ""}});
  6881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6882. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6883. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6884. EXPECT_EQ(true, res->has_header("Content-Range"));
  6885. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6886. EXPECT_EQ(std::string("abcdefg"), res->body);
  6887. }
  6888. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6889. auto res = cli_.Get("/with-range", Headers{
  6890. {"Range", "bytes=0-"},
  6891. {"Accept-Encoding", ""},
  6892. });
  6893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6894. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6895. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6896. EXPECT_EQ(true, res->has_header("Content-Range"));
  6897. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6898. EXPECT_EQ(std::string("abcdefg"), res->body);
  6899. }
  6900. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6901. auto res = cli_.Get("/streamed-with-range",
  6902. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6904. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6905. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6906. EXPECT_EQ(false, res->has_header("Content-Range"));
  6907. EXPECT_EQ(267U, res->body.size());
  6908. // Check that both range contents are present
  6909. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6910. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6911. // Check that Content-Range headers are present for both ranges
  6912. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6913. std::string::npos);
  6914. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6915. std::string::npos);
  6916. }
  6917. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6918. Ranges ranges;
  6919. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6920. ranges.emplace_back(0, -1);
  6921. }
  6922. auto res = cli_.Get("/streamed-with-range?error",
  6923. Headers{{make_range_header(ranges)}});
  6924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6925. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6926. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6927. EXPECT_EQ(false, res->has_header("Content-Range"));
  6928. EXPECT_EQ(0U, res->body.size());
  6929. }
  6930. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6931. auto res = cli_.Get("/streamed-with-range",
  6932. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6934. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6935. EXPECT_EQ(5U, res->body.size());
  6936. // Check that overlapping ranges are coalesced into a single range
  6937. EXPECT_EQ("bcdef", res->body);
  6938. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6939. // Should be single range, not multipart
  6940. EXPECT_TRUE(res->has_header("Content-Range"));
  6941. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6942. }
  6943. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6944. auto res = cli_.Get("/streamed-with-range",
  6945. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6947. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6948. EXPECT_EQ(268U, res->body.size());
  6949. // Check that both range contents are present
  6950. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6951. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6952. // Check that Content-Range headers are present for both ranges
  6953. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6954. std::string::npos);
  6955. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6956. std::string::npos);
  6957. }
  6958. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6959. auto res = cli_.Get("/streamed-with-range",
  6960. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6962. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6963. EXPECT_EQ(269U, res->body.size());
  6964. // Check that both duplicate range contents are present
  6965. size_t first_abc = res->body.find("abc\r\n");
  6966. EXPECT_TRUE(first_abc != std::string::npos);
  6967. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6968. EXPECT_TRUE(second_abc != std::string::npos);
  6969. // Check that Content-Range headers are present for both ranges
  6970. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6971. EXPECT_TRUE(first_range != std::string::npos);
  6972. size_t second_range =
  6973. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6974. EXPECT_TRUE(second_range != std::string::npos);
  6975. }
  6976. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6977. auto res =
  6978. cli_.Get("/streamed-with-range?error",
  6979. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6981. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6982. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6983. EXPECT_EQ(false, res->has_header("Content-Range"));
  6984. EXPECT_EQ(0U, res->body.size());
  6985. }
  6986. TEST_F(ServerTest, GetStreamedEndless) {
  6987. uint64_t offset = 0;
  6988. auto res = cli_.Get("/streamed-cancel",
  6989. [&](const char * /*data*/, uint64_t data_length) {
  6990. if (offset < 100) {
  6991. offset += data_length;
  6992. return true;
  6993. }
  6994. return false;
  6995. });
  6996. ASSERT_TRUE(!res);
  6997. EXPECT_EQ(Error::Canceled, res.error());
  6998. }
  6999. TEST_F(ServerTest, ClientStop) {
  7000. std::atomic_size_t count{4};
  7001. std::vector<std::thread> threads;
  7002. for (auto i = count.load(); i != 0; --i) {
  7003. threads.emplace_back([&]() {
  7004. auto res = cli_.Get("/streamed-cancel",
  7005. [&](const char *, uint64_t) { return true; });
  7006. --count;
  7007. ASSERT_TRUE(!res);
  7008. EXPECT_TRUE(res.error() == Error::Canceled ||
  7009. res.error() == Error::Read || res.error() == Error::Write);
  7010. });
  7011. }
  7012. std::this_thread::sleep_for(std::chrono::seconds(2));
  7013. while (count != 0) {
  7014. cli_.stop();
  7015. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7016. }
  7017. for (auto &t : threads) {
  7018. t.join();
  7019. }
  7020. }
  7021. TEST_F(ServerTest, GetWithRange1) {
  7022. auto res = cli_.Get("/with-range", Headers{
  7023. make_range_header({{3, 5}}),
  7024. {"Accept-Encoding", ""},
  7025. });
  7026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7027. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7028. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7029. EXPECT_EQ(true, res->has_header("Content-Range"));
  7030. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7031. EXPECT_EQ(std::string("def"), res->body);
  7032. }
  7033. TEST_F(ServerTest, GetWithRange2) {
  7034. auto res = cli_.Get("/with-range", Headers{
  7035. make_range_header({{1, -1}}),
  7036. {"Accept-Encoding", ""},
  7037. });
  7038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7039. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7040. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7041. EXPECT_EQ(true, res->has_header("Content-Range"));
  7042. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7043. EXPECT_EQ(std::string("bcdefg"), res->body);
  7044. }
  7045. TEST_F(ServerTest, GetWithRange3) {
  7046. auto res = cli_.Get("/with-range", Headers{
  7047. make_range_header({{0, 0}}),
  7048. {"Accept-Encoding", ""},
  7049. });
  7050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7051. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7052. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7053. EXPECT_EQ(true, res->has_header("Content-Range"));
  7054. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7055. EXPECT_EQ(std::string("a"), res->body);
  7056. }
  7057. TEST_F(ServerTest, GetWithRange4) {
  7058. auto res = cli_.Get("/with-range", Headers{
  7059. make_range_header({{-1, 2}}),
  7060. {"Accept-Encoding", ""},
  7061. });
  7062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7063. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7064. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7065. EXPECT_EQ(true, res->has_header("Content-Range"));
  7066. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7067. EXPECT_EQ(std::string("fg"), res->body);
  7068. }
  7069. TEST_F(ServerTest, GetWithRange5) {
  7070. auto res = cli_.Get("/with-range", Headers{
  7071. make_range_header({{0, 5}}),
  7072. {"Accept-Encoding", ""},
  7073. });
  7074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7075. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7076. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7077. EXPECT_EQ(true, res->has_header("Content-Range"));
  7078. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7079. EXPECT_EQ(std::string("abcdef"), res->body);
  7080. }
  7081. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7082. auto res =
  7083. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7085. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7086. }
  7087. TEST_F(ServerTest, GetWithRangeMultipart) {
  7088. auto res =
  7089. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7091. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7092. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7093. EXPECT_EQ(false, res->has_header("Content-Range"));
  7094. EXPECT_EQ(267U, res->body.size());
  7095. }
  7096. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7097. auto res = cli_.Get("/with-range",
  7098. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7100. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7101. }
  7102. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7103. auto res = cli_.Get("/with-range-customized-response",
  7104. Headers{{make_range_header({{1, 2}})}});
  7105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7106. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7107. EXPECT_EQ(true, res->has_header("Content-Length"));
  7108. EXPECT_EQ(false, res->has_header("Content-Range"));
  7109. EXPECT_EQ(JSON_DATA, res->body);
  7110. }
  7111. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7112. auto res = cli_.Get("/with-range-customized-response",
  7113. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7115. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7116. EXPECT_EQ(true, res->has_header("Content-Length"));
  7117. EXPECT_EQ(false, res->has_header("Content-Range"));
  7118. EXPECT_EQ(JSON_DATA, res->body);
  7119. }
  7120. TEST_F(ServerTest, Issue1772) {
  7121. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7123. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7124. }
  7125. TEST_F(ServerTest, Issue609) {
  7126. auto res = cli_.Delete("/issue609");
  7127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7128. EXPECT_EQ(StatusCode::OK_200, res->status);
  7129. EXPECT_EQ(std::string("ok"), res->body);
  7130. }
  7131. TEST_F(ServerTest, GetStreamedChunked) {
  7132. auto res = cli_.Get("/streamed-chunked");
  7133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7134. EXPECT_EQ(StatusCode::OK_200, res->status);
  7135. EXPECT_EQ(std::string("123456789"), res->body);
  7136. }
  7137. TEST_F(ServerTest, GetStreamedChunked2) {
  7138. auto res = cli_.Get("/streamed-chunked2");
  7139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7140. EXPECT_EQ(StatusCode::OK_200, res->status);
  7141. EXPECT_EQ(std::string("123456789"), res->body);
  7142. }
  7143. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7144. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7146. EXPECT_EQ(StatusCode::OK_200, res->status);
  7147. EXPECT_EQ(std::string("123456789"), res->body);
  7148. EXPECT_TRUE(res->has_header("Trailer"));
  7149. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7150. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7151. // Trailers are now stored separately from headers (security fix)
  7152. EXPECT_EQ(2U, res->trailers.size());
  7153. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7154. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7155. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7156. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7157. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7158. // Verify trailers are NOT in headers (security verification)
  7159. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7160. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7161. }
  7162. TEST_F(ServerTest, LargeChunkedPost) {
  7163. Request req;
  7164. req.method = "POST";
  7165. req.path = "/large-chunked";
  7166. std::string host_and_port;
  7167. host_and_port += HOST;
  7168. host_and_port += ":";
  7169. host_and_port += std::to_string(PORT);
  7170. req.headers.emplace("Host", host_and_port.c_str());
  7171. req.headers.emplace("Accept", "*/*");
  7172. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7173. req.headers.emplace("Content-Type", "text/plain");
  7174. req.headers.emplace("Content-Length", "0");
  7175. req.headers.emplace("Transfer-Encoding", "chunked");
  7176. std::string long_string(30 * 1024u, 'a');
  7177. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7178. // Attempt to make a large enough post to exceed OS buffers, to test that
  7179. // the server handles short reads if the full chunk data isn't available.
  7180. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7181. auto res = std::make_shared<Response>();
  7182. auto error = Error::Success;
  7183. auto ret = cli_.send(req, *res, error);
  7184. ASSERT_TRUE(ret);
  7185. EXPECT_EQ(StatusCode::OK_200, res->status);
  7186. }
  7187. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7188. auto res = cli_.Get("/remote_addr");
  7189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7190. EXPECT_EQ(StatusCode::OK_200, res->status);
  7191. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7192. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7193. }
  7194. TEST_F(ServerTest, GetMethodLocalAddr) {
  7195. auto res = cli_.Get("/local_addr");
  7196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7197. EXPECT_EQ(StatusCode::OK_200, res->status);
  7198. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7199. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7200. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7201. }
  7202. TEST_F(ServerTest, HTTPResponseSplitting) {
  7203. auto res = cli_.Get("/http_response_splitting");
  7204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7205. EXPECT_EQ(StatusCode::OK_200, res->status);
  7206. }
  7207. TEST_F(ServerTest, SlowRequest) {
  7208. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7209. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7210. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7211. }
  7212. #if 0
  7213. TEST_F(ServerTest, SlowPost) {
  7214. char buffer[64 * 1024];
  7215. memset(buffer, 0x42, sizeof(buffer));
  7216. auto res = cli_.Post(
  7217. "/slowpost", 64 * 1024 * 1024,
  7218. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7219. auto ret = sink.write(buffer, sizeof(buffer));
  7220. EXPECT_TRUE(ret);
  7221. return true;
  7222. },
  7223. "text/plain");
  7224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7225. EXPECT_EQ(StatusCode::OK_200, res->status);
  7226. }
  7227. TEST_F(ServerTest, SlowPostFail) {
  7228. char buffer[64 * 1024];
  7229. memset(buffer, 0x42, sizeof(buffer));
  7230. cli_.set_write_timeout(std::chrono::seconds(0));
  7231. auto res = cli_.Post(
  7232. "/slowpost", 64 * 1024 * 1024,
  7233. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7234. sink.write(buffer, sizeof(buffer));
  7235. return true;
  7236. },
  7237. "text/plain");
  7238. ASSERT_TRUE(!res);
  7239. EXPECT_EQ(Error::Write, res.error());
  7240. }
  7241. #endif
  7242. TEST_F(ServerTest, Put) {
  7243. auto res = cli_.Put("/put", "PUT", "text/plain");
  7244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7245. EXPECT_EQ(StatusCode::OK_200, res->status);
  7246. EXPECT_EQ("PUT", res->body);
  7247. }
  7248. TEST_F(ServerTest, PutWithContentProvider) {
  7249. auto res = cli_.Put(
  7250. "/put", 3,
  7251. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7252. sink.os << "PUT";
  7253. return true;
  7254. },
  7255. "text/plain");
  7256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7257. EXPECT_EQ(StatusCode::OK_200, res->status);
  7258. EXPECT_EQ("PUT", res->body);
  7259. }
  7260. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7261. auto res = cli_.Post(
  7262. "/post", 42,
  7263. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7264. return false;
  7265. },
  7266. "text/plain");
  7267. ASSERT_TRUE(!res);
  7268. EXPECT_EQ(Error::Canceled, res.error());
  7269. }
  7270. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7271. auto res = cli_.Put(
  7272. "/put",
  7273. [](size_t /*offset*/, DataSink &sink) {
  7274. sink.os << "PUT";
  7275. sink.done();
  7276. return true;
  7277. },
  7278. "text/plain");
  7279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7280. EXPECT_EQ(StatusCode::OK_200, res->status);
  7281. EXPECT_EQ("PUT", res->body);
  7282. }
  7283. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7284. auto res = cli_.Post(
  7285. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7286. "text/plain");
  7287. ASSERT_TRUE(!res);
  7288. EXPECT_EQ(Error::Canceled, res.error());
  7289. }
  7290. TEST_F(ServerTest, PostLoopBack) {
  7291. std::string body;
  7292. auto res = cli_.Post(
  7293. "/post-loopback", 9,
  7294. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7295. EXPECT_EQ(9u, length);
  7296. sink.write("123", 3);
  7297. sink.write("456", 3);
  7298. sink.write("789", 3);
  7299. return true;
  7300. },
  7301. "text/plain",
  7302. [&body](const char *data, size_t data_length) {
  7303. body.append(data, data_length);
  7304. return true;
  7305. });
  7306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7307. EXPECT_EQ(StatusCode::OK_200, res->status);
  7308. EXPECT_EQ("123456789", body);
  7309. }
  7310. TEST_F(ServerTest, PutLoopBack) {
  7311. std::string body;
  7312. auto res = cli_.Put(
  7313. "/put-loopback", 9,
  7314. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7315. EXPECT_EQ(9u, length);
  7316. sink.write("123", 3);
  7317. sink.write("456", 3);
  7318. sink.write("789", 3);
  7319. return true;
  7320. },
  7321. "text/plain",
  7322. [&body](const char *data, size_t data_length) {
  7323. body.append(data, data_length);
  7324. return true;
  7325. });
  7326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7327. EXPECT_EQ(StatusCode::OK_200, res->status);
  7328. EXPECT_EQ("123456789", body);
  7329. }
  7330. TEST_F(ServerTest, PatchLoopBack) {
  7331. std::string body;
  7332. auto res = cli_.Patch(
  7333. "/patch-loopback", 9,
  7334. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7335. EXPECT_EQ(9u, length);
  7336. sink.write("123", 3);
  7337. sink.write("456", 3);
  7338. sink.write("789", 3);
  7339. return true;
  7340. },
  7341. "text/plain",
  7342. [&body](const char *data, size_t data_length) {
  7343. body.append(data, data_length);
  7344. return true;
  7345. });
  7346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7347. EXPECT_EQ(StatusCode::OK_200, res->status);
  7348. EXPECT_EQ("123456789", body);
  7349. }
  7350. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7351. std::string body;
  7352. auto res = cli_.Post(
  7353. "/post-loopback",
  7354. [](size_t /*offset*/, DataSink &sink) {
  7355. sink.write("123", 3);
  7356. sink.write("456", 3);
  7357. sink.write("789", 3);
  7358. sink.done();
  7359. return true;
  7360. },
  7361. "text/plain",
  7362. [&body](const char *data, size_t data_length) {
  7363. body.append(data, data_length);
  7364. return true;
  7365. });
  7366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7367. EXPECT_EQ(StatusCode::OK_200, res->status);
  7368. EXPECT_EQ("123456789", body);
  7369. }
  7370. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7371. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7372. cli_.set_compress(true);
  7373. auto res = cli_.Put(
  7374. "/put", 3,
  7375. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7376. sink.os << "PUT";
  7377. return true;
  7378. },
  7379. "text/plain");
  7380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7381. EXPECT_EQ(StatusCode::OK_200, res->status);
  7382. EXPECT_EQ("PUT", res->body);
  7383. }
  7384. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7385. cli_.set_compress(true);
  7386. auto res = cli_.Post(
  7387. "/post", 42,
  7388. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7389. return false;
  7390. },
  7391. "text/plain");
  7392. ASSERT_TRUE(!res);
  7393. EXPECT_EQ(Error::Canceled, res.error());
  7394. }
  7395. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7396. cli_.set_compress(true);
  7397. auto res = cli_.Put(
  7398. "/put",
  7399. [](size_t /*offset*/, DataSink &sink) {
  7400. sink.os << "PUT";
  7401. sink.done();
  7402. return true;
  7403. },
  7404. "text/plain");
  7405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7406. EXPECT_EQ(StatusCode::OK_200, res->status);
  7407. EXPECT_EQ("PUT", res->body);
  7408. }
  7409. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7410. cli_.set_compress(true);
  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, PutLargeFileWithGzip) {
  7418. cli_.set_compress(true);
  7419. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7421. EXPECT_EQ(StatusCode::OK_200, res->status);
  7422. EXPECT_EQ(LARGE_DATA, res->body);
  7423. }
  7424. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7425. #ifdef CPPHTTPLIB_SSL_ENABLED
  7426. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7427. Client cli(s.c_str());
  7428. cli.enable_server_certificate_verification(false);
  7429. #else
  7430. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7431. Client cli(s.c_str());
  7432. #endif
  7433. cli.set_compress(true);
  7434. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7436. EXPECT_EQ(StatusCode::OK_200, res->status);
  7437. EXPECT_EQ(LARGE_DATA, res->body);
  7438. // The compressed size should be less than a 10th of the original. May vary
  7439. // depending on the zlib library.
  7440. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7441. static_cast<uint64_t>(10 * 1024 * 1024));
  7442. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7443. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7444. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7445. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7446. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7447. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7448. #endif
  7449. }
  7450. TEST_F(ServerTest, PutContentWithDeflate) {
  7451. cli_.set_compress(false);
  7452. Headers headers;
  7453. headers.emplace("Content-Encoding", "deflate");
  7454. // PUT in deflate format:
  7455. auto res = cli_.Put("/put", headers,
  7456. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7458. EXPECT_EQ(StatusCode::OK_200, res->status);
  7459. EXPECT_EQ("PUT", res->body);
  7460. }
  7461. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7462. Headers headers;
  7463. headers.emplace("Accept-Encoding", "gzip, deflate");
  7464. auto res = cli_.Get("/streamed-chunked", headers);
  7465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7466. EXPECT_EQ(StatusCode::OK_200, res->status);
  7467. EXPECT_EQ(std::string("123456789"), res->body);
  7468. }
  7469. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7470. Headers headers;
  7471. headers.emplace("Accept-Encoding", "gzip, deflate");
  7472. auto res = cli_.Get("/streamed-chunked2", headers);
  7473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7474. EXPECT_EQ(StatusCode::OK_200, res->status);
  7475. EXPECT_EQ(std::string("123456789"), res->body);
  7476. }
  7477. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7478. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7480. EXPECT_EQ(StatusCode::OK_200, res->status);
  7481. }
  7482. TEST(GzipDecompressor, ChunkedDecompression) {
  7483. std::string data;
  7484. for (size_t i = 0; i < 32 * 1024; ++i) {
  7485. data.push_back(static_cast<char>('a' + i % 26));
  7486. }
  7487. std::string compressed_data;
  7488. {
  7489. httplib::detail::gzip_compressor compressor;
  7490. bool result = compressor.compress(
  7491. data.data(), data.size(),
  7492. /*last=*/true,
  7493. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7494. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7495. compressed_data_size);
  7496. return true;
  7497. });
  7498. ASSERT_TRUE(result);
  7499. }
  7500. std::string decompressed_data;
  7501. {
  7502. httplib::detail::gzip_decompressor decompressor;
  7503. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7504. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7505. size_t chunk_size = 130;
  7506. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7507. chunk_begin += chunk_size) {
  7508. size_t current_chunk_size =
  7509. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7510. bool result = decompressor.decompress(
  7511. compressed_data.data() + chunk_begin, current_chunk_size,
  7512. [&](const char *decompressed_data_chunk,
  7513. size_t decompressed_data_chunk_size) {
  7514. decompressed_data.insert(decompressed_data.size(),
  7515. decompressed_data_chunk,
  7516. decompressed_data_chunk_size);
  7517. return true;
  7518. });
  7519. ASSERT_TRUE(result);
  7520. }
  7521. }
  7522. ASSERT_EQ(data, decompressed_data);
  7523. }
  7524. TEST(GzipDecompressor, DeflateDecompression) {
  7525. std::string original_text = "Raw deflate without gzip";
  7526. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7527. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7528. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7529. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7530. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7531. std::string decompressed_data;
  7532. {
  7533. httplib::detail::gzip_decompressor decompressor;
  7534. bool result = decompressor.decompress(
  7535. compressed_data.data(), compressed_data.size(),
  7536. [&](const char *decompressed_data_chunk,
  7537. size_t decompressed_data_chunk_size) {
  7538. decompressed_data.insert(decompressed_data.size(),
  7539. decompressed_data_chunk,
  7540. decompressed_data_chunk_size);
  7541. return true;
  7542. });
  7543. ASSERT_TRUE(result);
  7544. }
  7545. ASSERT_EQ(original_text, decompressed_data);
  7546. }
  7547. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7548. std::string original_text = "Raw deflate without gzip";
  7549. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7550. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7551. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7552. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7553. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7554. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7555. std::string decompressed_data;
  7556. {
  7557. httplib::detail::gzip_decompressor decompressor;
  7558. bool result = decompressor.decompress(
  7559. compressed_data.data(), compressed_data.size(),
  7560. [&](const char *decompressed_data_chunk,
  7561. size_t decompressed_data_chunk_size) {
  7562. decompressed_data.insert(decompressed_data.size(),
  7563. decompressed_data_chunk,
  7564. decompressed_data_chunk_size);
  7565. return true;
  7566. });
  7567. ASSERT_TRUE(result);
  7568. }
  7569. ASSERT_EQ(original_text, decompressed_data);
  7570. }
  7571. #endif
  7572. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7573. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7574. Headers headers;
  7575. headers.emplace("Accept-Encoding", "br");
  7576. auto res = cli_.Get("/streamed-chunked", headers);
  7577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7578. EXPECT_EQ(StatusCode::OK_200, res->status);
  7579. EXPECT_EQ(std::string("123456789"), res->body);
  7580. }
  7581. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7582. Headers headers;
  7583. headers.emplace("Accept-Encoding", "br");
  7584. auto res = cli_.Get("/streamed-chunked2", headers);
  7585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7586. EXPECT_EQ(StatusCode::OK_200, res->status);
  7587. EXPECT_EQ(std::string("123456789"), res->body);
  7588. }
  7589. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7590. cli_.set_compress(true);
  7591. auto res = cli_.Put(
  7592. "/put", 3,
  7593. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7594. sink.os << "PUT";
  7595. return true;
  7596. },
  7597. "text/plain");
  7598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7599. EXPECT_EQ(StatusCode::OK_200, res->status);
  7600. EXPECT_EQ("PUT", res->body);
  7601. }
  7602. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7603. cli_.set_compress(true);
  7604. auto res = cli_.Put(
  7605. "/put",
  7606. [](size_t /*offset*/, DataSink &sink) {
  7607. sink.os << "PUT";
  7608. sink.done();
  7609. return true;
  7610. },
  7611. "text/plain");
  7612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7613. EXPECT_EQ(StatusCode::OK_200, res->status);
  7614. EXPECT_EQ("PUT", res->body);
  7615. }
  7616. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7617. cli_.set_compress(true);
  7618. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7620. EXPECT_EQ(StatusCode::OK_200, res->status);
  7621. EXPECT_EQ(LARGE_DATA, res->body);
  7622. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7623. }
  7624. #endif
  7625. TEST_F(ServerTest, Patch) {
  7626. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7628. EXPECT_EQ(StatusCode::OK_200, res->status);
  7629. EXPECT_EQ("PATCH", res->body);
  7630. }
  7631. TEST_F(ServerTest, Delete) {
  7632. auto res = cli_.Delete("/delete");
  7633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7634. EXPECT_EQ(StatusCode::OK_200, res->status);
  7635. EXPECT_EQ("DELETE", res->body);
  7636. }
  7637. TEST_F(ServerTest, DeleteContentReceiver) {
  7638. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7640. EXPECT_EQ(StatusCode::OK_200, res->status);
  7641. EXPECT_EQ("content", res->body);
  7642. }
  7643. TEST_F(ServerTest, Options) {
  7644. auto res = cli_.Options("*");
  7645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7646. EXPECT_EQ(StatusCode::OK_200, res->status);
  7647. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7648. EXPECT_TRUE(res->body.empty());
  7649. }
  7650. TEST_F(ServerTest, URL) {
  7651. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7653. EXPECT_EQ(StatusCode::OK_200, res->status);
  7654. }
  7655. TEST_F(ServerTest, ArrayParam) {
  7656. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7658. EXPECT_EQ(StatusCode::OK_200, res->status);
  7659. }
  7660. TEST_F(ServerTest, ArrayParamValues) {
  7661. auto res =
  7662. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7664. EXPECT_EQ(StatusCode::OK_200, res->status);
  7665. }
  7666. TEST_F(ServerTest, NoMultipleHeaders) {
  7667. Headers headers = {{"Content-Length", "5"}};
  7668. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7669. "text/plain");
  7670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7671. EXPECT_EQ(StatusCode::OK_200, res->status);
  7672. }
  7673. TEST_F(ServerTest, PostContentReceiver) {
  7674. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7676. ASSERT_EQ(StatusCode::OK_200, res->status);
  7677. ASSERT_EQ("content", res->body);
  7678. }
  7679. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7680. UploadFormDataItems items = {
  7681. {"text1", "text default", "", ""},
  7682. {"text2", "aωb", "", ""},
  7683. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7684. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7685. {"file3", "", "", "application/octet-stream"},
  7686. };
  7687. auto res = cli_.Post("/content_receiver", items);
  7688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7689. EXPECT_EQ(StatusCode::OK_200, res->status);
  7690. }
  7691. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7692. UploadFormDataItems items = {
  7693. {"text1", "text default", "", ""},
  7694. {"text2", "aωb", "", ""},
  7695. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7696. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7697. {"file3", "", "", "application/octet-stream"},
  7698. };
  7699. auto boundary = std::string("+++++");
  7700. std::string body;
  7701. for (const auto &item : items) {
  7702. body += "--" + boundary + "\r\n";
  7703. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7704. if (!item.filename.empty()) {
  7705. body += "; filename=\"" + item.filename + "\"";
  7706. }
  7707. body += "\r\n";
  7708. if (!item.content_type.empty()) {
  7709. body += "Content-Type: " + item.content_type + "\r\n";
  7710. }
  7711. body += "\r\n";
  7712. body += item.content + "\r\n";
  7713. }
  7714. body += "--" + boundary + "--\r\n";
  7715. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7716. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7718. EXPECT_EQ(StatusCode::OK_200, res->status);
  7719. }
  7720. TEST(MultipartFormDataTest, FieldEscaping) {
  7721. Server svr;
  7722. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7723. const ContentReader &content_reader) {
  7724. ASSERT_TRUE(req.is_multipart_form_data());
  7725. std::vector<FormData> received;
  7726. content_reader(
  7727. [&](const FormData &file) {
  7728. received.push_back(file);
  7729. return true;
  7730. },
  7731. [&](const char *data, size_t data_length) {
  7732. received.back().content.append(data, data_length);
  7733. return true;
  7734. });
  7735. // '"', CR and LF in names and filenames are escaped following the
  7736. // WHATWG HTML standard, so each part still parses as a single part
  7737. // with no injected headers. Content types get CR/LF escaped too,
  7738. // while '"' (legal there, e.g. quoted charset) is preserved.
  7739. ASSERT_EQ(4U, received.size());
  7740. EXPECT_EQ("na%22me", received[0].name);
  7741. EXPECT_EQ("quoted name", received[0].content);
  7742. EXPECT_EQ("file", received[1].name);
  7743. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7744. received[1].filename);
  7745. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7746. EXPECT_EQ("injected", received[1].content);
  7747. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7748. EXPECT_EQ("my%22file.txt", received[2].filename);
  7749. EXPECT_EQ("cr lf name", received[2].content);
  7750. EXPECT_EQ("typed", received[3].name);
  7751. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7752. received[3].content_type);
  7753. EXPECT_EQ("typed content", received[3].content);
  7754. });
  7755. auto port = svr.bind_to_any_port("localhost");
  7756. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7757. auto se = detail::scope_exit([&] {
  7758. svr.stop();
  7759. t.join();
  7760. ASSERT_FALSE(svr.is_running());
  7761. });
  7762. svr.wait_until_ready();
  7763. Client cli("localhost", port);
  7764. UploadFormDataItems items = {
  7765. {"na\"me", "quoted name", "", ""},
  7766. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7767. "application/octet-stream"},
  7768. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7769. {"typed", "typed content", "",
  7770. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7771. };
  7772. auto res = cli.Post("/post", items);
  7773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7774. EXPECT_EQ(StatusCode::OK_200, res->status);
  7775. }
  7776. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7777. const UploadFormDataItems items = {
  7778. {"name1", "Content 1", "", ""},
  7779. {"name2", "Content 2", "file2.txt", "text/plain"},
  7780. };
  7781. Server svr;
  7782. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7783. const ContentReader &content_reader) {
  7784. ASSERT_TRUE(req.is_multipart_form_data());
  7785. std::vector<FormData> received;
  7786. content_reader(
  7787. [&](const FormData &file) {
  7788. received.push_back(file);
  7789. return true;
  7790. },
  7791. [&](const char *data, size_t data_length) {
  7792. received.back().content.append(data, data_length);
  7793. return true;
  7794. });
  7795. ASSERT_EQ(2U, received.size());
  7796. EXPECT_EQ("name1", received[0].name);
  7797. EXPECT_EQ("Content 1", received[0].content);
  7798. EXPECT_EQ("name2", received[1].name);
  7799. EXPECT_EQ("Content 2", received[1].content);
  7800. EXPECT_EQ("file2.txt", received[1].filename);
  7801. EXPECT_EQ("text/plain", received[1].content_type);
  7802. });
  7803. auto port = svr.bind_to_any_port("localhost");
  7804. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7805. auto se = detail::scope_exit([&] {
  7806. svr.stop();
  7807. t.join();
  7808. ASSERT_FALSE(svr.is_running());
  7809. });
  7810. svr.wait_until_ready();
  7811. Client cli("localhost", port);
  7812. // Whole-body serialization with a generated boundary
  7813. {
  7814. MultipartFormDataWriter writer;
  7815. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7816. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7817. writer.content_type());
  7818. auto body = writer.serialize(items);
  7819. EXPECT_EQ(body.size(), writer.content_length(items));
  7820. auto res = cli.Post("/post", body, writer.content_type());
  7821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7822. EXPECT_EQ(StatusCode::OK_200, res->status);
  7823. }
  7824. // Per-part framing with a custom boundary via a content provider
  7825. {
  7826. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7827. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7828. MultipartFormDataWriter writer("custom-boundary_123");
  7829. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7830. std::string body;
  7831. for (const auto &item : items) {
  7832. body += writer.item_begin(item);
  7833. body += item.content;
  7834. body += MultipartFormDataWriter::item_end();
  7835. }
  7836. body += writer.finish();
  7837. EXPECT_EQ(body.size(), writer.content_length(items));
  7838. auto res = cli.Post(
  7839. "/post", body.size(),
  7840. [&](size_t offset, size_t length, DataSink &sink) {
  7841. sink.write(body.data() + offset, length);
  7842. return true;
  7843. },
  7844. writer.content_type());
  7845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7846. EXPECT_EQ(StatusCode::OK_200, res->status);
  7847. }
  7848. }
  7849. TEST_F(ServerTest, PostContentReceiverGzip) {
  7850. cli_.set_compress(true);
  7851. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7853. ASSERT_EQ(StatusCode::OK_200, res->status);
  7854. ASSERT_EQ("content", res->body);
  7855. }
  7856. TEST_F(ServerTest, PutContentReceiver) {
  7857. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7859. ASSERT_EQ(StatusCode::OK_200, res->status);
  7860. ASSERT_EQ("content", res->body);
  7861. }
  7862. TEST_F(ServerTest, PatchContentReceiver) {
  7863. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7865. ASSERT_EQ(StatusCode::OK_200, res->status);
  7866. ASSERT_EQ("content", res->body);
  7867. }
  7868. template <typename ClientType>
  7869. void TestWithHeadersAndContentReceiver(
  7870. ClientType &cli,
  7871. std::function<Result(ClientType &, const std::string &, const Headers &,
  7872. const std::string &, const std::string &,
  7873. ContentReceiver, DownloadProgress)>
  7874. request_func) {
  7875. Headers headers;
  7876. headers.emplace("X-Custom-Header", "test-value");
  7877. std::string received_body;
  7878. auto res = request_func(
  7879. cli, "/content_receiver", headers, "content", "application/json",
  7880. [&](const char *data, size_t data_length) {
  7881. received_body.append(data, data_length);
  7882. return true;
  7883. },
  7884. nullptr);
  7885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7886. EXPECT_EQ(StatusCode::OK_200, res->status);
  7887. EXPECT_EQ("content", received_body);
  7888. }
  7889. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7890. #ifdef CPPHTTPLIB_SSL_ENABLED
  7891. using ClientT = SSLClient;
  7892. #else
  7893. using ClientT = Client;
  7894. #endif
  7895. TestWithHeadersAndContentReceiver<ClientT>(
  7896. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7897. const std::string &body, const std::string &content_type,
  7898. ContentReceiver receiver, DownloadProgress progress) {
  7899. return cli.Post(path, headers, body, content_type, receiver, progress);
  7900. });
  7901. }
  7902. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7903. #ifdef CPPHTTPLIB_SSL_ENABLED
  7904. using ClientT = SSLClient;
  7905. #else
  7906. using ClientT = Client;
  7907. #endif
  7908. TestWithHeadersAndContentReceiver<ClientT>(
  7909. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7910. const std::string &body, const std::string &content_type,
  7911. ContentReceiver receiver, DownloadProgress progress) {
  7912. return cli.Put(path, headers, body, content_type, receiver, progress);
  7913. });
  7914. }
  7915. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7916. #ifdef CPPHTTPLIB_SSL_ENABLED
  7917. using ClientT = SSLClient;
  7918. #else
  7919. using ClientT = Client;
  7920. #endif
  7921. TestWithHeadersAndContentReceiver<ClientT>(
  7922. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7923. const std::string &body, const std::string &content_type,
  7924. ContentReceiver receiver, DownloadProgress progress) {
  7925. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7926. });
  7927. }
  7928. template <typename ClientType>
  7929. void TestWithHeadersAndContentReceiverWithProgress(
  7930. ClientType &cli,
  7931. std::function<Result(ClientType &, const std::string &, const Headers &,
  7932. const std::string &, const std::string &,
  7933. ContentReceiver, DownloadProgress)>
  7934. request_func) {
  7935. Headers headers;
  7936. headers.emplace("X-Test-Header", "progress-test");
  7937. std::string received_body;
  7938. auto progress_called = false;
  7939. auto res = request_func(
  7940. cli, "/content_receiver", headers, "content", "text/plain",
  7941. [&](const char *data, size_t data_length) {
  7942. received_body.append(data, data_length);
  7943. return true;
  7944. },
  7945. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7946. progress_called = true;
  7947. return true;
  7948. });
  7949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7950. EXPECT_EQ(StatusCode::OK_200, res->status);
  7951. EXPECT_EQ("content", received_body);
  7952. EXPECT_TRUE(progress_called);
  7953. }
  7954. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7955. #ifdef CPPHTTPLIB_SSL_ENABLED
  7956. using ClientT = SSLClient;
  7957. #else
  7958. using ClientT = Client;
  7959. #endif
  7960. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7961. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7962. const std::string &body, const std::string &content_type,
  7963. ContentReceiver receiver, DownloadProgress progress) {
  7964. return cli.Post(path, headers, body, content_type, receiver, progress);
  7965. });
  7966. }
  7967. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7968. #ifdef CPPHTTPLIB_SSL_ENABLED
  7969. using ClientT = SSLClient;
  7970. #else
  7971. using ClientT = Client;
  7972. #endif
  7973. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7974. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7975. const std::string &body, const std::string &content_type,
  7976. ContentReceiver receiver, DownloadProgress progress) {
  7977. return cli.Put(path, headers, body, content_type, receiver, progress);
  7978. });
  7979. }
  7980. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7981. #ifdef CPPHTTPLIB_SSL_ENABLED
  7982. using ClientT = SSLClient;
  7983. #else
  7984. using ClientT = Client;
  7985. #endif
  7986. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7987. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7988. const std::string &body, const std::string &content_type,
  7989. ContentReceiver receiver, DownloadProgress progress) {
  7990. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7991. });
  7992. }
  7993. template <typename ClientType>
  7994. void TestWithHeadersAndContentReceiverError(
  7995. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7996. const Headers &, const std::string &,
  7997. const std::string &, ContentReceiver)>
  7998. request_func) {
  7999. Headers headers;
  8000. headers.emplace("X-Error-Test", "true");
  8001. std::string received_body;
  8002. auto receiver_failed = false;
  8003. auto res =
  8004. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8005. [&](const char *data, size_t data_length) {
  8006. received_body.append(data, data_length);
  8007. receiver_failed = true;
  8008. return false;
  8009. });
  8010. ASSERT_FALSE(res);
  8011. EXPECT_TRUE(receiver_failed);
  8012. }
  8013. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8014. #ifdef CPPHTTPLIB_SSL_ENABLED
  8015. using ClientT = SSLClient;
  8016. #else
  8017. using ClientT = Client;
  8018. #endif
  8019. TestWithHeadersAndContentReceiverError<ClientT>(
  8020. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8021. const std::string &body, const std::string &content_type,
  8022. ContentReceiver receiver) {
  8023. return cli.Post(path, headers, body, content_type, receiver);
  8024. });
  8025. }
  8026. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8027. #ifdef CPPHTTPLIB_SSL_ENABLED
  8028. using ClientT = SSLClient;
  8029. #else
  8030. using ClientT = Client;
  8031. #endif
  8032. TestWithHeadersAndContentReceiverError<ClientT>(
  8033. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8034. const std::string &body, const std::string &content_type,
  8035. ContentReceiver receiver) {
  8036. return cli.Put(path, headers, body, content_type, receiver);
  8037. });
  8038. }
  8039. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8040. #ifdef CPPHTTPLIB_SSL_ENABLED
  8041. using ClientT = SSLClient;
  8042. #else
  8043. using ClientT = Client;
  8044. #endif
  8045. TestWithHeadersAndContentReceiverError<ClientT>(
  8046. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8047. const std::string &body, const std::string &content_type,
  8048. ContentReceiver receiver) {
  8049. return cli.Patch(path, headers, body, content_type, receiver);
  8050. });
  8051. }
  8052. TEST_F(ServerTest, PostQueryStringAndBody) {
  8053. auto res =
  8054. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8056. ASSERT_EQ(StatusCode::OK_200, res->status);
  8057. }
  8058. TEST_F(ServerTest, HTTP2Magic) {
  8059. Request req;
  8060. req.method = "PRI";
  8061. req.path = "*";
  8062. req.body = "SM";
  8063. auto res = std::make_shared<Response>();
  8064. auto error = Error::Success;
  8065. auto ret = cli_.send(req, *res, error);
  8066. ASSERT_TRUE(ret);
  8067. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8068. }
  8069. TEST_F(ServerTest, KeepAlive) {
  8070. auto res = cli_.Get("/hi");
  8071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8072. EXPECT_EQ(StatusCode::OK_200, res->status);
  8073. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8074. EXPECT_EQ("Hello World!", res->body);
  8075. res = cli_.Get("/hi");
  8076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8077. EXPECT_EQ(StatusCode::OK_200, res->status);
  8078. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8079. EXPECT_EQ("Hello World!", res->body);
  8080. res = cli_.Get("/hi");
  8081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8082. EXPECT_EQ(StatusCode::OK_200, res->status);
  8083. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8084. EXPECT_EQ("Hello World!", res->body);
  8085. res = cli_.Get("/not-exist");
  8086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8087. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8088. res = cli_.Post("/empty", "", "text/plain");
  8089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8090. EXPECT_EQ(StatusCode::OK_200, res->status);
  8091. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8092. EXPECT_EQ("empty", res->body);
  8093. EXPECT_EQ("close", res->get_header_value("Connection"));
  8094. res = cli_.Post(
  8095. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8096. "text/plain");
  8097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8098. EXPECT_EQ(StatusCode::OK_200, res->status);
  8099. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8100. EXPECT_EQ("empty", res->body);
  8101. cli_.set_keep_alive(false);
  8102. res = cli_.Get("/last-request");
  8103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8104. EXPECT_EQ(StatusCode::OK_200, res->status);
  8105. EXPECT_EQ("close", res->get_header_value("Connection"));
  8106. }
  8107. TEST_F(ServerTest, TooManyRedirect) {
  8108. cli_.set_follow_location(true);
  8109. auto res = cli_.Get("/redirect/0");
  8110. ASSERT_TRUE(!res);
  8111. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8112. }
  8113. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8114. Request req;
  8115. req.method = "FOOBAR";
  8116. req.path = "/hi";
  8117. cli_.set_keep_alive(true);
  8118. auto res = cli_.send(req);
  8119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8120. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8121. EXPECT_EQ("close", res->get_header_value("Connection"));
  8122. EXPECT_FALSE(cli_.is_socket_open());
  8123. }
  8124. TEST_F(ServerTest, CustomRouteReadsBody) {
  8125. const std::string xml =
  8126. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8127. Request req;
  8128. req.method = "PROPFIND";
  8129. req.path = "/dav/dir";
  8130. req.set_header("Depth", "1");
  8131. req.body = xml;
  8132. auto res = cli_.send(req);
  8133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8134. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8135. EXPECT_EQ(xml, res->body);
  8136. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8137. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8138. }
  8139. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8140. Request req;
  8141. req.method = "PROPFIND";
  8142. req.path = "/dav/42";
  8143. auto res = cli_.send(req);
  8144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8145. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8146. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8147. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8148. }
  8149. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8150. Request req;
  8151. req.method = "PROPFIND";
  8152. req.path = "/dav-re/123";
  8153. auto res = cli_.send(req);
  8154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8155. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8156. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8157. }
  8158. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8159. Request req;
  8160. req.method = "MKCOL";
  8161. req.path = "/dav-mkcol";
  8162. auto res = cli_.send(req);
  8163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8164. EXPECT_EQ(StatusCode::Created_201, res->status);
  8165. }
  8166. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8167. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8168. Request req;
  8169. req.method = "REPORT";
  8170. req.path = "/dav-report";
  8171. req.body = xml;
  8172. auto res = cli_.send(req);
  8173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8174. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8175. EXPECT_EQ(xml, res->body);
  8176. }
  8177. // A content reader route must fire even when the request carries no body,
  8178. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8179. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8180. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8181. Request req;
  8182. req.method = "REPORT";
  8183. req.path = "/dav-report";
  8184. auto res = cli_.send(req);
  8185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8186. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8187. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8188. }
  8189. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8190. Request req;
  8191. req.method = "PROPFIND";
  8192. req.path = "/not-dav";
  8193. auto res = cli_.send(req);
  8194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8195. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8196. }
  8197. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8198. Request req;
  8199. req.method = "UNLOCK";
  8200. req.path = "/dav/dir";
  8201. cli_.set_keep_alive(true);
  8202. auto res = cli_.send(req);
  8203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8204. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8205. EXPECT_EQ("close", res->get_header_value("Connection"));
  8206. EXPECT_FALSE(cli_.is_socket_open());
  8207. }
  8208. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8209. // The mount point serves this path, but only for GET and HEAD.
  8210. auto get_res = cli_.Get("/dir/index.html");
  8211. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8212. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8213. Request req;
  8214. req.method = "PROPFIND";
  8215. req.path = "/dir/index.html";
  8216. auto res = cli_.send(req);
  8217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8218. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8219. }
  8220. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8221. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8222. cli_.set_keep_alive(true);
  8223. for (auto i = 0; i < 2; i++) {
  8224. Request req;
  8225. req.method = "PROPFIND";
  8226. req.path = "/dav/dir";
  8227. req.body = xml;
  8228. auto res = cli_.send(req);
  8229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8230. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8231. EXPECT_EQ(xml, res->body);
  8232. EXPECT_TRUE(cli_.is_socket_open());
  8233. }
  8234. // A built-in method must still be served on the same connection.
  8235. cli_.set_keep_alive(false);
  8236. auto res = cli_.Get("/hi");
  8237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8238. EXPECT_EQ(StatusCode::OK_200, res->status);
  8239. EXPECT_EQ("close", res->get_header_value("Connection"));
  8240. }
  8241. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8242. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8243. Request req;
  8244. req.method = "PROPFIND";
  8245. req.path = "/dav/dir";
  8246. req.set_header("Expect", "100-continue");
  8247. req.body = xml;
  8248. auto res = cli_.send(req);
  8249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8250. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8251. EXPECT_EQ(xml, res->body);
  8252. }
  8253. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8254. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8255. TEST_F(ServerTest, Gzip) {
  8256. Headers headers;
  8257. headers.emplace("Accept-Encoding", "gzip, deflate");
  8258. auto res = cli_.Get("/compress", headers);
  8259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8260. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8261. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8262. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8263. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8264. "7890123456789012345678901234567890",
  8265. res->body);
  8266. EXPECT_EQ(StatusCode::OK_200, res->status);
  8267. }
  8268. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8269. Headers headers;
  8270. headers.emplace("Accept-Encoding", "gzip, deflate");
  8271. auto res = cli_.Get("/compress-with-charset", headers);
  8272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8273. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8274. EXPECT_EQ("application/json; charset=utf-8",
  8275. res->get_header_value("Content-Type"));
  8276. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8277. "7890123456789012345678901234567890",
  8278. res->body);
  8279. EXPECT_EQ(StatusCode::OK_200, res->status);
  8280. }
  8281. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8282. Headers headers;
  8283. headers.emplace("Accept-Encoding", "");
  8284. auto res = cli_.Get("/compress", headers);
  8285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8286. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8287. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8288. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8289. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8290. "7890123456789012345678901234567890",
  8291. res->body);
  8292. EXPECT_EQ(StatusCode::OK_200, res->status);
  8293. }
  8294. TEST_F(ServerTest, GzipWithContentReceiver) {
  8295. Headers headers;
  8296. headers.emplace("Accept-Encoding", "gzip, deflate");
  8297. std::string body;
  8298. auto res = cli_.Get("/compress", headers,
  8299. [&](const char *data, uint64_t data_length) {
  8300. EXPECT_EQ(100U, data_length);
  8301. body.append(data, data_length);
  8302. return true;
  8303. });
  8304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8305. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8306. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8307. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8308. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8309. "7890123456789012345678901234567890",
  8310. body);
  8311. EXPECT_EQ(StatusCode::OK_200, res->status);
  8312. }
  8313. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8314. Headers headers;
  8315. headers.emplace("Accept-Encoding", "gzip, deflate");
  8316. cli_.set_decompress(false);
  8317. auto res = cli_.Get("/compress", headers);
  8318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8319. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8320. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8321. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8322. EXPECT_EQ(33U, res->body.size());
  8323. EXPECT_EQ(StatusCode::OK_200, res->status);
  8324. }
  8325. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8326. Headers headers;
  8327. headers.emplace("Accept-Encoding", "");
  8328. std::string body;
  8329. auto res = cli_.Get("/compress", headers,
  8330. [&](const char *data, uint64_t data_length) {
  8331. EXPECT_EQ(100U, data_length);
  8332. body.append(data, data_length);
  8333. return true;
  8334. });
  8335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8336. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8337. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8338. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8339. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8340. "7890123456789012345678901234567890",
  8341. body);
  8342. EXPECT_EQ(StatusCode::OK_200, res->status);
  8343. }
  8344. TEST_F(ServerTest, NoGzip) {
  8345. Headers headers;
  8346. headers.emplace("Accept-Encoding", "gzip, deflate");
  8347. auto res = cli_.Get("/nocompress", headers);
  8348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8349. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8350. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8351. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8352. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8353. "7890123456789012345678901234567890",
  8354. res->body);
  8355. EXPECT_EQ(StatusCode::OK_200, res->status);
  8356. }
  8357. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8358. Headers headers;
  8359. headers.emplace("Accept-Encoding", "gzip, deflate");
  8360. std::string body;
  8361. auto res = cli_.Get("/nocompress", headers,
  8362. [&](const char *data, uint64_t data_length) {
  8363. EXPECT_EQ(100U, data_length);
  8364. body.append(data, data_length);
  8365. return true;
  8366. });
  8367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8368. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8369. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8370. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8371. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8372. "7890123456789012345678901234567890",
  8373. body);
  8374. EXPECT_EQ(StatusCode::OK_200, res->status);
  8375. }
  8376. TEST_F(ServerTest, MultipartFormDataGzip) {
  8377. UploadFormDataItems items = {
  8378. {"key1", "test", "", ""},
  8379. {"key2", "--abcdefg123", "", ""},
  8380. };
  8381. cli_.set_compress(true);
  8382. auto res = cli_.Post("/compress-multipart", items);
  8383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8384. EXPECT_EQ(StatusCode::OK_200, res->status);
  8385. }
  8386. #endif
  8387. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8388. // Static file compression is opt-in, so these run their own server rather than
  8389. // flipping it on for the shared ServerTest fixture, which would silently
  8390. // rewrite what every other static file test is asserting.
  8391. class StaticFileCompressionTest : public ::testing::Test {
  8392. protected:
  8393. void TearDown() override {
  8394. if (t_.joinable()) {
  8395. svr_.stop();
  8396. t_.join();
  8397. }
  8398. }
  8399. int start(const std::function<void(Server &)> &configure = nullptr) {
  8400. // Serves the same tree as a directory of build-time compressed assets
  8401. // would be served: the mount point names the coding the files are already
  8402. // stored in. Registered before "/" so it is the one that matches.
  8403. svr_.set_mount_point("/pre-encoded", "./www",
  8404. {{"Content-Encoding", "gzip"}});
  8405. svr_.set_mount_point("/", "./www");
  8406. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8407. res.set_file_content("./www/dir/index.html", "text/html");
  8408. });
  8409. svr_.Get("/pre-encoded-file-content",
  8410. [](const Request & /*req*/, Response &res) {
  8411. res.set_header("Content-Encoding", "gzip");
  8412. res.set_file_content("./www/dir/index.html", "text/html");
  8413. });
  8414. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8415. res.set_content_provider(
  8416. 6, "text/plain",
  8417. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8418. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8419. return true;
  8420. });
  8421. });
  8422. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8423. res.set_content_provider(
  8424. 1000, "text/plain",
  8425. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8426. if (offset < 100) {
  8427. std::string data(100, 'A');
  8428. sink.write(data.data(), data.size());
  8429. return true;
  8430. }
  8431. std::this_thread::sleep_for(std::chrono::seconds(2));
  8432. std::string data(900, 'B');
  8433. sink.write(data.data(), data.size());
  8434. return true;
  8435. });
  8436. });
  8437. if (configure) { configure(svr_); }
  8438. auto port = svr_.bind_to_any_port(HOST);
  8439. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8440. svr_.wait_until_ready();
  8441. return port;
  8442. }
  8443. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8444. // Every file under ./www except 1MB.txt is smaller than the default
  8445. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8446. // it out of the way.
  8447. static void enable_without_floor(Server &svr) {
  8448. svr.set_static_file_compression(true);
  8449. svr.set_static_file_compression_min_length(0);
  8450. }
  8451. Server svr_;
  8452. std::thread t_;
  8453. };
  8454. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8455. auto port = start();
  8456. Client cli(HOST, port);
  8457. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8459. EXPECT_EQ(StatusCode::OK_200, res->status);
  8460. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8461. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8462. EXPECT_EQ(1048576U, res->body.size());
  8463. }
  8464. TEST_F(StaticFileCompressionTest, MountPoint) {
  8465. auto port = start(enable);
  8466. Client cli(HOST, port);
  8467. cli.set_decompress(false);
  8468. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8470. EXPECT_EQ(StatusCode::OK_200, res->status);
  8471. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8472. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8473. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8474. // The response stays self-delimiting: a length, not a chunked body.
  8475. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8476. EXPECT_EQ(std::to_string(res->body.size()),
  8477. res->get_header_value("Content-Length"));
  8478. EXPECT_LT(res->body.size(), 1048576U);
  8479. EXPECT_FALSE(res->body.empty());
  8480. }
  8481. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8482. auto port = start(enable);
  8483. Client cli(HOST, port);
  8484. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8486. EXPECT_EQ(StatusCode::OK_200, res->status);
  8487. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8488. EXPECT_EQ(1048576U, res->body.size());
  8489. }
  8490. TEST_F(StaticFileCompressionTest, FileContent) {
  8491. auto port = start(enable_without_floor);
  8492. Client cli(HOST, port);
  8493. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8495. EXPECT_EQ(StatusCode::OK_200, res->status);
  8496. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8497. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8498. EXPECT_EQ(104U, res->body.size());
  8499. }
  8500. // A handler that serves an already-encoded file names the coding itself. The
  8501. // file-backed path decided its coding from Accept-Encoding and the content
  8502. // type alone, so it compressed the stored bytes a second time and appended a
  8503. // second Content-Encoding field line.
  8504. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8505. auto port = start(enable_without_floor);
  8506. Client cli(HOST, port);
  8507. cli.set_decompress(false);
  8508. auto res = cli.Get("/pre-encoded-file-content",
  8509. Headers{{"Accept-Encoding", "gzip"}});
  8510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8511. EXPECT_EQ(StatusCode::OK_200, res->status);
  8512. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8513. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8514. // Vary belongs to a coding the server chose, and it chose none here.
  8515. EXPECT_FALSE(res->has_header("Vary"));
  8516. // The file travels exactly as it is stored on disk.
  8517. EXPECT_EQ(104U, res->body.size());
  8518. }
  8519. // The 1MB file clears the default floor, so this one runs the configuration a
  8520. // deployment would actually have.
  8521. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8522. auto port = start(enable);
  8523. Client cli(HOST, port);
  8524. cli.set_decompress(false);
  8525. auto res =
  8526. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8528. EXPECT_EQ(StatusCode::OK_200, res->status);
  8529. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8530. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8531. EXPECT_FALSE(res->has_header("Vary"));
  8532. EXPECT_EQ(1048576U, res->body.size());
  8533. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8534. }
  8535. TEST_F(StaticFileCompressionTest, Head) {
  8536. auto port = start(enable);
  8537. Client cli(HOST, port);
  8538. cli.set_decompress(false);
  8539. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8540. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8541. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8543. EXPECT_EQ(StatusCode::OK_200, res->status);
  8544. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8545. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8546. // HEAD still reports the size a GET would return.
  8547. EXPECT_EQ(get->get_header_value("Content-Length"),
  8548. res->get_header_value("Content-Length"));
  8549. EXPECT_TRUE(res->body.empty());
  8550. }
  8551. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8552. auto port = start(enable);
  8553. Client cli(HOST, port);
  8554. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8555. {"Accept-Encoding", "gzip"}});
  8556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8557. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8558. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8559. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8560. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8561. EXPECT_EQ("cd", res->body);
  8562. }
  8563. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8564. auto port = start(enable);
  8565. Client cli(HOST, port);
  8566. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8568. EXPECT_EQ(StatusCode::OK_200, res->status);
  8569. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8570. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8571. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8572. }
  8573. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8574. auto port = start(enable);
  8575. Client cli(HOST, port);
  8576. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8578. EXPECT_EQ(StatusCode::OK_200, res->status);
  8579. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8580. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8581. EXPECT_TRUE(res->body.empty());
  8582. }
  8583. TEST_F(StaticFileCompressionTest, MinLength) {
  8584. auto port = start(enable);
  8585. Client cli(HOST, port);
  8586. // 104 bytes, well under the default floor. Compressing it would add the
  8587. // gzip header and trailer to a body that already fits in one packet.
  8588. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8590. EXPECT_EQ(StatusCode::OK_200, res->status);
  8591. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8592. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8593. }
  8594. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8595. auto port = start([](Server &svr) {
  8596. svr.set_static_file_compression(true);
  8597. svr.set_static_file_compression_min_length(1);
  8598. });
  8599. Client cli(HOST, port);
  8600. cli.set_decompress(false);
  8601. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8603. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8604. // A 9-byte file comes back larger than it went in, because gzip's header and
  8605. // trailer outweigh anything deflate can save. That is the end of the range
  8606. // the floor exists to keep out.
  8607. EXPECT_GT(res->body.size(), 9U);
  8608. }
  8609. TEST_F(StaticFileCompressionTest, MaxLength) {
  8610. auto port = start([](Server &svr) {
  8611. svr.set_static_file_compression(true);
  8612. svr.set_static_file_compression_min_length(0);
  8613. svr.set_static_file_compression_max_length(1024);
  8614. });
  8615. Client cli(HOST, port);
  8616. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8617. // defines `small` as a macro on Windows.
  8618. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8619. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8620. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8621. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8622. // Under it: compressed.
  8623. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8624. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8625. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8626. }
  8627. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8628. auto port = start(enable_without_floor);
  8629. Client cli(HOST, port);
  8630. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8631. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8632. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8633. auto identity_etag = identity->get_header_value("ETag");
  8634. ASSERT_FALSE(identity_etag.empty());
  8635. auto gzipped =
  8636. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8637. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8638. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8639. auto gzip_etag = gzipped->get_header_value("ETag");
  8640. ASSERT_FALSE(gzip_etag.empty());
  8641. // Two representations, two validators.
  8642. EXPECT_NE(identity_etag, gzip_etag);
  8643. // Each one revalidates against the request that would produce it...
  8644. auto fresh =
  8645. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8646. {"If-None-Match", gzip_etag}});
  8647. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8648. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8649. auto fresh_identity =
  8650. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8651. {"If-None-Match", identity_etag}});
  8652. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8653. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8654. // ...and not against the other representation.
  8655. auto crossed =
  8656. cli.Get("/dir/index.html",
  8657. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8658. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8659. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8660. }
  8661. // The opt-in covers responses the server reads off disk itself. A caller's own
  8662. // known-length provider keeps its Content-Length and, more importantly, keeps
  8663. // delivering incrementally: routing it through a compressor would hold every
  8664. // write back until zlib's window filled.
  8665. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8666. auto port = start(enable);
  8667. Client cli(HOST, port);
  8668. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8670. EXPECT_EQ(StatusCode::OK_200, res->status);
  8671. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8672. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8673. EXPECT_EQ("aaabbb", res->body);
  8674. }
  8675. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8676. auto port = start(enable);
  8677. Client cli(HOST, port);
  8678. cli.set_read_timeout(1, 0);
  8679. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8680. Headers{{"Accept-Encoding", "gzip"}});
  8681. ASSERT_TRUE(handle.is_valid());
  8682. // The provider writes 100 bytes and then stalls for longer than the read
  8683. // timeout. Those first bytes have to arrive anyway: run the response through
  8684. // a compressor and zlib holds them until its window fills, so the read would
  8685. // come back empty instead.
  8686. char buf[256];
  8687. auto n = handle.read(buf, sizeof(buf));
  8688. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8689. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8690. }
  8691. #endif
  8692. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8693. TEST_F(ServerTest, Brotli) {
  8694. Headers headers;
  8695. headers.emplace("Accept-Encoding", "br");
  8696. auto res = cli_.Get("/compress", headers);
  8697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8698. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8699. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8700. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8701. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8702. "7890123456789012345678901234567890",
  8703. res->body);
  8704. EXPECT_EQ(StatusCode::OK_200, res->status);
  8705. }
  8706. #endif
  8707. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8708. TEST_F(ServerTest, Zstd) {
  8709. Headers headers;
  8710. headers.emplace("Accept-Encoding", "zstd");
  8711. auto res = cli_.Get("/compress", headers);
  8712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8713. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8714. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8715. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8716. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8717. "7890123456789012345678901234567890",
  8718. res->body);
  8719. EXPECT_EQ(StatusCode::OK_200, res->status);
  8720. }
  8721. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8722. Headers headers;
  8723. headers.emplace("Accept-Encoding", "");
  8724. auto res = cli_.Get("/compress", headers);
  8725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8726. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8727. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8728. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8729. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8730. "7890123456789012345678901234567890",
  8731. res->body);
  8732. EXPECT_EQ(StatusCode::OK_200, res->status);
  8733. }
  8734. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8735. Headers headers;
  8736. headers.emplace("Accept-Encoding", "zstd");
  8737. std::string body;
  8738. auto res = cli_.Get("/compress", headers,
  8739. [&](const char *data, uint64_t data_length) {
  8740. EXPECT_EQ(100U, data_length);
  8741. body.append(data, data_length);
  8742. return true;
  8743. });
  8744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8745. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8746. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8747. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8748. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8749. "7890123456789012345678901234567890",
  8750. body);
  8751. EXPECT_EQ(StatusCode::OK_200, res->status);
  8752. }
  8753. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8754. Headers headers;
  8755. headers.emplace("Accept-Encoding", "zstd");
  8756. cli_.set_decompress(false);
  8757. auto res = cli_.Get("/compress", headers);
  8758. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8759. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8760. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8761. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8763. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8764. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8765. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8766. EXPECT_EQ(StatusCode::OK_200, res->status);
  8767. ASSERT_EQ(26U, res->body.size());
  8768. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8769. 0);
  8770. }
  8771. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8772. Headers headers;
  8773. headers.emplace("Accept-Encoding", "");
  8774. std::string body;
  8775. auto res = cli_.Get("/compress", headers,
  8776. [&](const char *data, uint64_t data_length) {
  8777. EXPECT_EQ(100U, data_length);
  8778. body.append(data, data_length);
  8779. return true;
  8780. });
  8781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8782. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8783. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8784. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8785. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8786. "7890123456789012345678901234567890",
  8787. body);
  8788. EXPECT_EQ(StatusCode::OK_200, res->status);
  8789. }
  8790. TEST_F(ServerTest, NoZstd) {
  8791. Headers headers;
  8792. headers.emplace("Accept-Encoding", "zstd");
  8793. auto res = cli_.Get("/nocompress", headers);
  8794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8795. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8796. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8797. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8798. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8799. "7890123456789012345678901234567890",
  8800. res->body);
  8801. EXPECT_EQ(StatusCode::OK_200, res->status);
  8802. }
  8803. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8804. Headers headers;
  8805. headers.emplace("Accept-Encoding", "zstd");
  8806. std::string body;
  8807. auto res = cli_.Get("/nocompress", headers,
  8808. [&](const char *data, uint64_t data_length) {
  8809. EXPECT_EQ(100U, data_length);
  8810. body.append(data, data_length);
  8811. return true;
  8812. });
  8813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8814. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8815. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8816. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8817. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8818. "7890123456789012345678901234567890",
  8819. body);
  8820. EXPECT_EQ(StatusCode::OK_200, res->status);
  8821. }
  8822. // TODO: How to enable zstd ??
  8823. TEST_F(ServerTest, MultipartFormDataZstd) {
  8824. UploadFormDataItems items = {
  8825. {"key1", "test", "", ""},
  8826. {"key2", "--abcdefg123", "", ""},
  8827. };
  8828. Headers headers;
  8829. headers.emplace("Accept-Encoding", "zstd");
  8830. cli_.set_compress(true);
  8831. auto res = cli_.Post("/compress-multipart", headers, items);
  8832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8833. EXPECT_EQ(StatusCode::OK_200, res->status);
  8834. }
  8835. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8836. Headers headers;
  8837. headers.emplace("Accept-Encoding", "zstd");
  8838. cli_.set_compress(true);
  8839. auto res = cli_.Put(
  8840. "/put", headers, 3,
  8841. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8842. sink.os << "PUT";
  8843. return true;
  8844. },
  8845. "text/plain");
  8846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8847. EXPECT_EQ(StatusCode::OK_200, res->status);
  8848. EXPECT_EQ("PUT", res->body);
  8849. }
  8850. // Pre-compression logging tests
  8851. TEST_F(ServerTest, PreCompressionLogging) {
  8852. // Test data for compression (matches the actual /compress endpoint content)
  8853. const std::string test_content =
  8854. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8855. "3456789012345678901234567890";
  8856. // Variables to capture logging data
  8857. std::string pre_compression_body;
  8858. std::string pre_compression_content_type;
  8859. std::string pre_compression_content_encoding;
  8860. std::string post_compression_body;
  8861. std::string post_compression_content_type;
  8862. std::string post_compression_content_encoding;
  8863. // Set up pre-compression logger
  8864. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8865. const Response &res) {
  8866. pre_compression_body = res.body;
  8867. pre_compression_content_type = res.get_header_value("Content-Type");
  8868. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8869. });
  8870. // Set up post-compression logger
  8871. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8872. post_compression_body = res.body;
  8873. post_compression_content_type = res.get_header_value("Content-Type");
  8874. post_compression_content_encoding =
  8875. res.get_header_value("Content-Encoding");
  8876. });
  8877. // Test with gzip compression
  8878. Headers headers;
  8879. headers.emplace("Accept-Encoding", "gzip");
  8880. auto res = cli_.Get("/compress", headers);
  8881. // Verify response was compressed
  8882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8883. EXPECT_EQ(StatusCode::OK_200, res->status);
  8884. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8885. // Verify pre-compression logger captured uncompressed content
  8886. EXPECT_EQ(test_content, pre_compression_body);
  8887. EXPECT_EQ("text/plain", pre_compression_content_type);
  8888. EXPECT_TRUE(pre_compression_content_encoding
  8889. .empty()); // No encoding header before compression
  8890. // Verify post-compression logger captured compressed content
  8891. EXPECT_NE(test_content,
  8892. post_compression_body); // Should be different after compression
  8893. EXPECT_EQ("text/plain", post_compression_content_type);
  8894. EXPECT_EQ("gzip", post_compression_content_encoding);
  8895. // Verify compressed content is smaller
  8896. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8897. }
  8898. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8899. const std::string test_content =
  8900. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8901. "3456789012345678901234567890";
  8902. std::string pre_compression_body;
  8903. std::string post_compression_body;
  8904. svr_.set_pre_compression_logger(
  8905. [&](const Request & /*req*/, const Response &res) {
  8906. pre_compression_body = res.body;
  8907. });
  8908. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8909. post_compression_body = res.body;
  8910. });
  8911. Headers headers;
  8912. headers.emplace("Accept-Encoding", "br");
  8913. auto res = cli_.Get("/compress", headers);
  8914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8915. EXPECT_EQ(StatusCode::OK_200, res->status);
  8916. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8917. // Verify pre-compression content is uncompressed
  8918. EXPECT_EQ(test_content, pre_compression_body);
  8919. // Verify post-compression content is compressed
  8920. EXPECT_NE(test_content, post_compression_body);
  8921. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8922. }
  8923. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8924. const std::string test_content =
  8925. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8926. "3456789012345678901234567890";
  8927. std::string pre_compression_body;
  8928. std::string post_compression_body;
  8929. svr_.set_pre_compression_logger(
  8930. [&](const Request & /*req*/, const Response &res) {
  8931. pre_compression_body = res.body;
  8932. });
  8933. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8934. post_compression_body = res.body;
  8935. });
  8936. // Request without compression (use /nocompress endpoint)
  8937. Headers headers;
  8938. auto res = cli_.Get("/nocompress", headers);
  8939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8940. EXPECT_EQ(StatusCode::OK_200, res->status);
  8941. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8942. // Pre-compression logger should not be called when no compression is applied
  8943. EXPECT_TRUE(
  8944. pre_compression_body.empty()); // Pre-compression logger not called
  8945. EXPECT_EQ(
  8946. test_content,
  8947. post_compression_body); // Post-compression logger captures final content
  8948. }
  8949. TEST_F(ServerTest, LoggerSeesContentLength) {
  8950. size_t logged_content_length = 0;
  8951. std::string logged_content_length_header;
  8952. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8953. logged_content_length = res.content_length_;
  8954. logged_content_length_header = res.get_header_value("Content-Length");
  8955. });
  8956. auto res = cli_.Get("/nocompress");
  8957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8958. EXPECT_EQ(StatusCode::OK_200, res->status);
  8959. EXPECT_EQ(res->body.size(), logged_content_length);
  8960. EXPECT_EQ(std::to_string(logged_content_length),
  8961. logged_content_length_header);
  8962. }
  8963. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8964. const std::string test_content =
  8965. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8966. "3456789012345678901234567890";
  8967. std::string pre_compression_body;
  8968. bool pre_logger_called = false;
  8969. // Set only pre-compression logger
  8970. svr_.set_pre_compression_logger(
  8971. [&](const Request & /*req*/, const Response &res) {
  8972. pre_compression_body = res.body;
  8973. pre_logger_called = true;
  8974. });
  8975. Headers headers;
  8976. headers.emplace("Accept-Encoding", "gzip");
  8977. auto res = cli_.Get("/compress", headers);
  8978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8979. EXPECT_EQ(StatusCode::OK_200, res->status);
  8980. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8981. // Verify pre-compression logger was called
  8982. EXPECT_TRUE(pre_logger_called);
  8983. EXPECT_EQ(test_content, pre_compression_body);
  8984. }
  8985. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8986. {
  8987. // Test with Expect: 100-continue header - success case
  8988. // Server returns 100 Continue, client sends body, server returns 200 OK
  8989. Request req;
  8990. req.method = "POST";
  8991. req.path = "/post-large";
  8992. req.set_header("Expect", "100-continue");
  8993. req.body = LARGE_DATA;
  8994. Response res;
  8995. auto error = Error::Success;
  8996. cli_.set_keep_alive(true);
  8997. auto ret = cli_.send(req, res, error);
  8998. EXPECT_TRUE(ret);
  8999. EXPECT_EQ(StatusCode::OK_200, res.status);
  9000. EXPECT_EQ(LARGE_DATA, res.body);
  9001. }
  9002. {
  9003. // Test with Expect: 100-continue header - error case
  9004. // Client should not send the body when server returns an error
  9005. Request req;
  9006. req.method = "POST";
  9007. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9008. req.set_header("Expect", "100-continue");
  9009. req.body = LARGE_DATA;
  9010. Response res;
  9011. auto error = Error::Success;
  9012. auto start = std::chrono::high_resolution_clock::now();
  9013. cli_.set_keep_alive(true);
  9014. auto ret = cli_.send(req, res, error);
  9015. auto end = std::chrono::high_resolution_clock::now();
  9016. auto elapsed =
  9017. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9018. .count();
  9019. // With Expect: 100-continue, request completes successfully but with error
  9020. EXPECT_TRUE(ret);
  9021. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9022. EXPECT_EQ("close", res.get_header_value("Connection"));
  9023. EXPECT_FALSE(cli_.is_socket_open());
  9024. EXPECT_LE(elapsed, 2000);
  9025. }
  9026. {
  9027. // Send an extra GET request to ensure error recovery without hanging
  9028. Request req;
  9029. req.method = "GET";
  9030. req.path = "/hi";
  9031. auto start = std::chrono::high_resolution_clock::now();
  9032. auto res = cli_.send(req);
  9033. auto end = std::chrono::high_resolution_clock::now();
  9034. auto elapsed =
  9035. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9036. .count();
  9037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9038. EXPECT_EQ(StatusCode::OK_200, res->status);
  9039. EXPECT_EQ("Hello World!", res->body);
  9040. EXPECT_LE(elapsed, 500);
  9041. }
  9042. }
  9043. TEST(ZstdDecompressor, ChunkedDecompression) {
  9044. std::string data;
  9045. for (size_t i = 0; i < 32 * 1024; ++i) {
  9046. data.push_back(static_cast<char>('a' + i % 26));
  9047. }
  9048. std::string compressed_data;
  9049. {
  9050. httplib::detail::zstd_compressor compressor;
  9051. bool result = compressor.compress(
  9052. data.data(), data.size(),
  9053. /*last=*/true,
  9054. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9055. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9056. compressed_data_size);
  9057. return true;
  9058. });
  9059. ASSERT_TRUE(result);
  9060. }
  9061. std::string decompressed_data;
  9062. {
  9063. httplib::detail::zstd_decompressor decompressor;
  9064. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9065. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9066. size_t chunk_size = 130;
  9067. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9068. chunk_begin += chunk_size) {
  9069. size_t current_chunk_size =
  9070. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9071. bool result = decompressor.decompress(
  9072. compressed_data.data() + chunk_begin, current_chunk_size,
  9073. [&](const char *decompressed_data_chunk,
  9074. size_t decompressed_data_chunk_size) {
  9075. decompressed_data.insert(decompressed_data.size(),
  9076. decompressed_data_chunk,
  9077. decompressed_data_chunk_size);
  9078. return true;
  9079. });
  9080. ASSERT_TRUE(result);
  9081. }
  9082. }
  9083. ASSERT_EQ(data, decompressed_data);
  9084. }
  9085. TEST(ZstdDecompressor, Decompress) {
  9086. std::string original_text = "Compressed with ZSTD";
  9087. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9088. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9089. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9090. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9091. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9092. std::string decompressed_data;
  9093. {
  9094. httplib::detail::zstd_decompressor decompressor;
  9095. bool result = decompressor.decompress(
  9096. compressed_data.data(), compressed_data.size(),
  9097. [&](const char *decompressed_data_chunk,
  9098. size_t decompressed_data_chunk_size) {
  9099. decompressed_data.insert(decompressed_data.size(),
  9100. decompressed_data_chunk,
  9101. decompressed_data_chunk_size);
  9102. return true;
  9103. });
  9104. ASSERT_TRUE(result);
  9105. }
  9106. ASSERT_EQ(original_text, decompressed_data);
  9107. }
  9108. #endif
  9109. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9110. // separate chunks so that the server sees each part in its own read(). Used to
  9111. // place a read boundary at a specific offset of a request body.
  9112. static bool send_request_in_parts(time_t read_timeout_sec,
  9113. const std::vector<std::string> &parts,
  9114. std::string *resp = nullptr,
  9115. int port = PORT) {
  9116. auto error = Error::Success;
  9117. auto client_sock = detail::create_client_socket(
  9118. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9119. /*connection_timeout_sec=*/5, 0,
  9120. /*read_timeout_sec=*/5, 0,
  9121. /*write_timeout_sec=*/5, 0, std::string(), error);
  9122. if (client_sock == INVALID_SOCKET) { return false; }
  9123. auto ret = detail::process_client_socket(
  9124. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9125. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9126. for (size_t i = 0; i < parts.size(); i++) {
  9127. const auto &part = parts[i];
  9128. if (part.size() !=
  9129. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9130. return false;
  9131. }
  9132. if (i + 1 < parts.size()) {
  9133. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9134. }
  9135. }
  9136. char buf[512];
  9137. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9138. while (line_reader.getline()) {
  9139. if (resp) { *resp += line_reader.ptr(); }
  9140. }
  9141. return true;
  9142. });
  9143. detail::close_socket(client_sock);
  9144. return ret;
  9145. }
  9146. // Sends a raw request to a server listening at HOST:PORT.
  9147. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9148. std::string *resp = nullptr, int port = PORT) {
  9149. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9150. }
  9151. #ifdef CPPHTTPLIB_SSL_ENABLED
  9152. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9153. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9154. ASSERT_TRUE(svr.is_valid());
  9155. svr.set_read_timeout(1, 0);
  9156. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9157. auto se = detail::scope_exit([&] {
  9158. svr.stop();
  9159. t.join();
  9160. ASSERT_FALSE(svr.is_running());
  9161. });
  9162. svr.wait_until_ready();
  9163. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9164. // keeps each wait well within the read timeout. The server gives up a
  9165. // second in, so the bytes sent after that fail.
  9166. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9167. parts.resize(26, std::string(1, '\0'));
  9168. EXPECT_FALSE(send_request_in_parts(5, parts));
  9169. }
  9170. #endif
  9171. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9172. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9173. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9174. const std::vector<std::string> &parts,
  9175. std::string *resp = nullptr,
  9176. int port = PORT) {
  9177. auto error = Error::Success;
  9178. auto sock = detail::create_client_socket(
  9179. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9180. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9181. /*write_timeout_sec=*/5, 0, std::string(), error);
  9182. if (sock == INVALID_SOCKET) { return false; }
  9183. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9184. auto ctx = SSL_CTX_new(TLS_client_method());
  9185. auto ssl = SSL_new(ctx);
  9186. auto ssl_se = detail::scope_exit([&] {
  9187. SSL_free(ssl);
  9188. SSL_CTX_free(ctx);
  9189. });
  9190. SSL_set_fd(ssl, static_cast<int>(sock));
  9191. if (SSL_connect(ssl) != 1) { return false; }
  9192. for (size_t i = 0; i < parts.size(); i++) {
  9193. const auto &part = parts[i];
  9194. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9195. static_cast<int>(part.size())) {
  9196. return false;
  9197. }
  9198. if (i + 1 < parts.size()) {
  9199. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9200. }
  9201. }
  9202. char buf[512];
  9203. int n;
  9204. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9205. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9206. }
  9207. return true;
  9208. }
  9209. #endif
  9210. // The request line, then a header value a byte at a time.
  9211. static std::vector<std::string> slow_request_head_parts() {
  9212. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9213. parts.resize(26, "a");
  9214. parts.emplace_back("\r\n\r\n");
  9215. return parts;
  9216. }
  9217. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9218. // within the one-second read timeout. The server gives up a second in, before
  9219. // the head is complete.
  9220. static void
  9221. expect_slow_request_head_dropped(Server &svr,
  9222. const std::function<std::string()> &send) {
  9223. std::atomic<bool> handled(false);
  9224. svr.Get("/", [&](const Request &, Response &res) {
  9225. handled = true;
  9226. res.set_content("ok", "text/plain");
  9227. });
  9228. svr.set_read_timeout(1, 0);
  9229. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9230. auto se = detail::scope_exit([&] {
  9231. svr.stop();
  9232. t.join();
  9233. ASSERT_FALSE(svr.is_running());
  9234. });
  9235. svr.wait_until_ready();
  9236. auto resp = send();
  9237. EXPECT_FALSE(handled);
  9238. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9239. }
  9240. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9241. Server svr;
  9242. expect_slow_request_head_dropped(svr, [] {
  9243. std::string resp;
  9244. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9245. return resp;
  9246. });
  9247. }
  9248. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9249. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9250. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9251. ASSERT_TRUE(svr.is_valid());
  9252. expect_slow_request_head_dropped(svr, [] {
  9253. std::string resp;
  9254. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9255. return resp;
  9256. });
  9257. }
  9258. #endif
  9259. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9260. Server svr;
  9261. std::string header_value;
  9262. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9263. header_value = req.get_header_value("foo");
  9264. res.set_content("ok", "text/plain");
  9265. });
  9266. thread t = thread([&] { svr.listen(HOST, PORT); });
  9267. auto se = detail::scope_exit([&] {
  9268. svr.stop();
  9269. t.join();
  9270. ASSERT_FALSE(svr.is_running());
  9271. });
  9272. svr.wait_until_ready();
  9273. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9274. // like characters are not treated the same - use vertical tab and escape.
  9275. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9276. "foo: \t \v bar \x1B\t \r\n"
  9277. "Connection: close\r\n"
  9278. "\r\n";
  9279. std::string res;
  9280. ASSERT_TRUE(send_request(5, req, &res));
  9281. EXPECT_EQ(header_value, "");
  9282. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9283. }
  9284. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9285. Server svr;
  9286. std::string received;
  9287. svr.Get("/order", [&](const Request &req, Response &res) {
  9288. received = entries_to_string(req.headers);
  9289. res.set_content("ok", "text/plain");
  9290. });
  9291. auto port = svr.bind_to_any_port(HOST);
  9292. thread t = thread([&] { svr.listen_after_bind(); });
  9293. auto se = detail::scope_exit([&] {
  9294. svr.stop();
  9295. t.join();
  9296. ASSERT_FALSE(svr.is_running());
  9297. });
  9298. svr.wait_until_ready();
  9299. const std::string req = "GET /order HTTP/1.1\r\n"
  9300. "Host: localhost\r\n"
  9301. "X-First: 1\r\n"
  9302. "X-Dup: a\r\n"
  9303. "X-Second: 2\r\n"
  9304. "X-Dup: b\r\n"
  9305. "Connection: close\r\n"
  9306. "\r\n";
  9307. std::string res;
  9308. ASSERT_TRUE(send_request(5, req, &res, port));
  9309. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9310. EXPECT_EQ(
  9311. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9312. received);
  9313. }
  9314. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9315. Server svr;
  9316. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9317. res.set_header("Set-Cookie", "first=1");
  9318. res.set_header("X-Between", "y");
  9319. res.set_header("Set-Cookie", "second=2");
  9320. res.set_content("ok", "text/plain");
  9321. });
  9322. auto port = svr.bind_to_any_port(HOST);
  9323. thread t = thread([&] { svr.listen_after_bind(); });
  9324. auto se = detail::scope_exit([&] {
  9325. svr.stop();
  9326. t.join();
  9327. ASSERT_FALSE(svr.is_running());
  9328. });
  9329. svr.wait_until_ready();
  9330. Client cli(HOST, port);
  9331. auto res = cli.Get("/cookies");
  9332. ASSERT_TRUE(res);
  9333. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9334. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9335. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9336. }
  9337. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9338. Server svr;
  9339. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9340. auto i = new int(0);
  9341. res.set_header("Trailer", "X-Safe, X-Reflected");
  9342. res.set_chunked_content_provider(
  9343. "text/plain",
  9344. [i](size_t /*offset*/, DataSink &sink) {
  9345. if (*i == 0) {
  9346. sink.os << "body";
  9347. } else {
  9348. Headers trailer;
  9349. // A valid trailer that must survive.
  9350. trailer.emplace("X-Safe", "safe");
  9351. // Attacker-controlled value carrying CR/LF (response splitting).
  9352. trailer.emplace("X-Reflected",
  9353. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9354. // Attacker-controlled name carrying CR/LF.
  9355. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9356. sink.done_with_trailer(trailer);
  9357. }
  9358. (*i)++;
  9359. return true;
  9360. },
  9361. [i](bool /*success*/) { delete i; });
  9362. });
  9363. thread t = thread([&] { svr.listen(HOST, PORT); });
  9364. auto se = detail::scope_exit([&] {
  9365. svr.stop();
  9366. t.join();
  9367. ASSERT_FALSE(svr.is_running());
  9368. });
  9369. svr.wait_until_ready();
  9370. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9371. "Host: " + HOST +
  9372. "\r\n"
  9373. "Connection: close\r\n"
  9374. "\r\n";
  9375. std::string res;
  9376. ASSERT_TRUE(send_request(5, req, &res));
  9377. // The injected fields must not appear anywhere in the raw response.
  9378. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9379. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9380. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9381. // Invalid trailers are dropped entirely, matching set_header().
  9382. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9383. // The valid trailer still passes through.
  9384. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9385. }
  9386. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9387. Server svr;
  9388. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9389. // res.headers is a public field an application can populate directly,
  9390. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9391. // A valid header that must survive.
  9392. res.headers.emplace("X-Safe", "safe");
  9393. // Attacker-controlled value carrying CR/LF (response splitting).
  9394. res.headers.emplace("X-Reflected",
  9395. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9396. // Attacker-controlled name carrying CR/LF.
  9397. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9398. res.set_content("body", "text/plain");
  9399. });
  9400. thread t = thread([&] { svr.listen(HOST, PORT); });
  9401. auto se = detail::scope_exit([&] {
  9402. svr.stop();
  9403. t.join();
  9404. ASSERT_FALSE(svr.is_running());
  9405. });
  9406. svr.wait_until_ready();
  9407. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9408. "Host: " + HOST +
  9409. "\r\n"
  9410. "Connection: close\r\n"
  9411. "\r\n";
  9412. std::string res;
  9413. ASSERT_TRUE(send_request(5, req, &res));
  9414. // The injected fields must not appear anywhere in the raw response.
  9415. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9416. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9417. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9418. // Invalid headers are dropped entirely, matching set_header().
  9419. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9420. // The valid header still passes through.
  9421. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9422. }
  9423. // Forward declaration: in split builds split.py strips `inline` and moves the
  9424. // definition into httplib.cc, so detail::write_request_line is not visible from
  9425. // the public httplib.h. Re-declaring it here lets the tests link against the
  9426. // symbol in both header-only and split builds.
  9427. namespace httplib {
  9428. namespace detail {
  9429. ssize_t write_request_line(Stream &strm, const std::string &method,
  9430. const std::string &path);
  9431. } // namespace detail
  9432. } // namespace httplib
  9433. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9434. // A well-formed target is written verbatim.
  9435. {
  9436. detail::BufferStream strm;
  9437. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9438. EXPECT_GT(n, 0);
  9439. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9440. }
  9441. // A target carrying CR/LF, SP or other control octets must be rejected
  9442. // before anything reaches the wire, otherwise it splits the request line and
  9443. // injects a header or a whole request.
  9444. const std::string evil_targets[] = {
  9445. "/a\r\nInjected: pwned",
  9446. "/a\rInjected",
  9447. "/a\nInjected",
  9448. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9449. "/a b",
  9450. "/a\tb",
  9451. "/a\x7f",
  9452. };
  9453. for (const auto &evil : evil_targets) {
  9454. detail::BufferStream strm;
  9455. auto n = detail::write_request_line(strm, "GET", evil);
  9456. EXPECT_LT(n, 0);
  9457. EXPECT_TRUE(strm.get_buffer().empty());
  9458. }
  9459. }
  9460. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9461. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9462. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9463. // target reaches write_request. The client must fail cleanly with
  9464. // Error::Write instead of putting a request-line-less, header-injecting
  9465. // request on the wire.
  9466. Server svr;
  9467. svr.Get("/a", [](const Request &, Response &res) {
  9468. res.set_content("ok", "text/plain");
  9469. });
  9470. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9471. auto se = detail::scope_exit([&] {
  9472. svr.stop();
  9473. thread.join();
  9474. ASSERT_FALSE(svr.is_running());
  9475. });
  9476. svr.wait_until_ready();
  9477. {
  9478. Client cli(HOST, PORT);
  9479. cli.set_path_encode(false);
  9480. // The request is rejected before anything is written, so the connection
  9481. // stays silent and the subsequent response read would otherwise block for
  9482. // the full default read timeout. Shorten it -- the assertion is on the
  9483. // error, not the timeout.
  9484. cli.set_read_timeout(1, 0);
  9485. auto res = cli.Get("/a\r\nInjected: pwned");
  9486. EXPECT_FALSE(res);
  9487. EXPECT_EQ(Error::Write, res.error());
  9488. }
  9489. }
  9490. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9491. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9492. // including extension methods.
  9493. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9494. for (const auto &method : good_methods) {
  9495. detail::BufferStream strm;
  9496. auto n = detail::write_request_line(strm, method, "/");
  9497. EXPECT_GT(n, 0);
  9498. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9499. }
  9500. // A method carrying CR/LF would split the request line and smuggle a whole
  9501. // request ahead of the real one. A space or an empty method corrupts the
  9502. // request line. All must be rejected before anything reaches the wire.
  9503. const std::string evil_methods[] = {
  9504. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9505. "GET\r\nInjected: pwned",
  9506. "GET\r",
  9507. "GET\n",
  9508. "GE T",
  9509. "",
  9510. };
  9511. for (const auto &evil : evil_methods) {
  9512. detail::BufferStream strm;
  9513. auto n = detail::write_request_line(strm, evil, "/");
  9514. EXPECT_LT(n, 0);
  9515. EXPECT_TRUE(strm.get_buffer().empty());
  9516. }
  9517. }
  9518. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9519. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9520. // through Client::send must fail with Error::Write and no request, neither
  9521. // the smuggled one nor the real one, may reach the server.
  9522. Server svr;
  9523. std::atomic<int> request_count(0);
  9524. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9525. request_count++;
  9526. res.status = StatusCode::OK_200;
  9527. return Server::HandlerResponse::Handled;
  9528. });
  9529. auto port = svr.bind_to_any_port(HOST);
  9530. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9531. auto se = detail::scope_exit([&] {
  9532. svr.stop();
  9533. thread.join();
  9534. ASSERT_FALSE(svr.is_running());
  9535. });
  9536. svr.wait_until_ready();
  9537. {
  9538. Client cli(HOST, port);
  9539. const std::string evil_methods[] = {
  9540. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9541. "GE T",
  9542. "",
  9543. };
  9544. for (const auto &evil : evil_methods) {
  9545. Request req;
  9546. req.method = evil;
  9547. req.path = "/";
  9548. auto res = cli.send(req);
  9549. EXPECT_FALSE(res);
  9550. EXPECT_EQ(Error::Write, res.error());
  9551. }
  9552. auto handle =
  9553. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9554. EXPECT_FALSE(handle.is_valid());
  9555. EXPECT_EQ(Error::Write, handle.error);
  9556. // A valid request on the same client still goes through.
  9557. auto res = cli.Get("/");
  9558. ASSERT_TRUE(res);
  9559. EXPECT_EQ(StatusCode::OK_200, res->status);
  9560. }
  9561. EXPECT_EQ(1, request_count.load());
  9562. }
  9563. // Sends a raw request and verifies that there isn't a crash or exception.
  9564. static void test_raw_request(const std::string &req,
  9565. std::string *out = nullptr) {
  9566. Server svr;
  9567. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9568. res.set_content("ok", "text/plain");
  9569. });
  9570. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9571. res.set_content("ok", "text/plain");
  9572. });
  9573. svr.Get("/header_field_value_check",
  9574. [&](const Request & /*req*/, Response &res) {
  9575. res.set_content("ok", "text/plain");
  9576. });
  9577. svr.CustomRoute("PROPFIND", "/dav",
  9578. [&](const Request & /*req*/, Response &res) {
  9579. res.status = StatusCode::MultiStatus_207;
  9580. });
  9581. // Server read timeout must be longer than the client read timeout for the
  9582. // bug to reproduce, probably to force the server to process a request
  9583. // without a trailing blank line.
  9584. const time_t client_read_timeout_sec = 1;
  9585. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9586. bool listen_thread_ok = false;
  9587. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9588. auto se = detail::scope_exit([&] {
  9589. svr.stop();
  9590. t.join();
  9591. ASSERT_FALSE(svr.is_running());
  9592. EXPECT_TRUE(listen_thread_ok);
  9593. });
  9594. svr.wait_until_ready();
  9595. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9596. }
  9597. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9598. // A certain header line causes an exception if the header property is parsed
  9599. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9600. test_raw_request(
  9601. "GET /hi HTTP/1.1\r\n"
  9602. " : "
  9603. " "
  9604. " ");
  9605. }
  9606. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9607. // A certain header line causes an exception if the header property *name* is
  9608. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9609. // greedy matcher and requires backtracking when there are a lot of ":"
  9610. // characters.
  9611. // This occurs with libc++ but not libstdc++.
  9612. test_raw_request(
  9613. "GET /hi HTTP/1.1\r\n"
  9614. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9615. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9616. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9617. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9618. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9619. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9620. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9621. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9622. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9623. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9624. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9625. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9626. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9627. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9628. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9629. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9630. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9631. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9632. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9633. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9634. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9635. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9636. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9637. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9638. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9639. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9640. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9641. "&&&%%%");
  9642. }
  9643. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9644. // Make sure this doesn't crash the server.
  9645. // In a previous version of the header line regex, the "\r" rendered the line
  9646. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9647. // a new position where the leading white space ended and the field value
  9648. // began.
  9649. // The crash occurs with libc++ but not libstdc++.
  9650. test_raw_request("GET /hi HTTP/1.1\r\n"
  9651. "a:" +
  9652. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9653. "\r\n"
  9654. "\r\n");
  9655. }
  9656. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9657. const char *rejected[] = {
  9658. // RFC 9112 §3: one SP between the parts, and nothing else
  9659. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9660. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9661. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9662. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9663. // A request-target has no fragment
  9664. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9665. // An HTTP/1.1 request needs a Host
  9666. "GET /hi HTTP/1.1\r\n\r\n",
  9667. };
  9668. for (auto request : rejected) {
  9669. std::string out;
  9670. test_raw_request(request, &out);
  9671. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9672. }
  9673. std::string out;
  9674. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9675. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9676. }
  9677. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9678. // RFC 9112 §6.1
  9679. const char *requests[] = {
  9680. "PUT /put_hi HTTP/1.1\r\n"
  9681. "Host: localhost\r\n"
  9682. "Content-Length: 0\r\n"
  9683. "Transfer-Encoding: chunked\r\n"
  9684. "\r\n"
  9685. "0\r\n\r\n",
  9686. "PUT /put_hi HTTP/1.0\r\n"
  9687. "Connection: keep-alive\r\n"
  9688. "Transfer-Encoding: chunked\r\n"
  9689. "\r\n"
  9690. "0\r\n\r\n",
  9691. };
  9692. for (auto request : requests) {
  9693. std::string out;
  9694. test_raw_request(request, &out);
  9695. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9696. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9697. }
  9698. }
  9699. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9700. std::string out;
  9701. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9702. "Content-Type: text/plain\r\n"
  9703. "Transfer-Encoding: chunked\r\n"
  9704. "\r\n"
  9705. "nothex\r\n",
  9706. &out);
  9707. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9708. }
  9709. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9710. std::string out;
  9711. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9712. "Content-Type: text/plain\r\n"
  9713. "Transfer-Encoding: chunked\r\n"
  9714. "\r\n"
  9715. "3\r\n"
  9716. "xyz\r\n"
  9717. "NaN\r\n",
  9718. &out);
  9719. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9720. }
  9721. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9722. std::string out;
  9723. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9724. "Content-Type: text/plain\r\n"
  9725. "Transfer-Encoding: chunked\r\n"
  9726. "\r\n"
  9727. // Length is too large for 64 bits.
  9728. "1ffffffffffffffff\r\n"
  9729. "xyz\r\n",
  9730. &out);
  9731. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9732. }
  9733. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9734. test_raw_request("GET /hi HTTP/1.1\r\n"
  9735. "Content-Type: text/plain\r\n\r");
  9736. }
  9737. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9738. std::string out;
  9739. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9740. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9741. }
  9742. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9743. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9744. std::string out;
  9745. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9746. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9747. }
  9748. }
  9749. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9750. std::string out;
  9751. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9752. "Host: localhost\r\n"
  9753. "Connection: close\r\n\r\n",
  9754. &out);
  9755. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9756. }
  9757. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9758. Server svr;
  9759. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9760. EXPECT_TRUE(!req.remote_addr.empty());
  9761. });
  9762. thread t = thread([&] { svr.listen(HOST, PORT); });
  9763. auto se = detail::scope_exit([&] {
  9764. svr.stop();
  9765. t.join();
  9766. ASSERT_FALSE(svr.is_running());
  9767. });
  9768. svr.wait_until_ready();
  9769. // Send an invalid request line to trigger Bad Request
  9770. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9771. std::string out;
  9772. ASSERT_TRUE(send_request(5, bad_req, &out));
  9773. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9774. }
  9775. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9776. // answered right away rather than blocking on a read that waits for EOF.
  9777. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9778. std::string out;
  9779. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9780. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9781. }
  9782. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9783. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9784. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9785. for (const auto *method : methods) {
  9786. Server svr;
  9787. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9788. EXPECT_FALSE(svr.is_valid()) << method;
  9789. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9790. }
  9791. }
  9792. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9793. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9794. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9795. for (const auto *method : methods) {
  9796. Server svr;
  9797. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9798. EXPECT_FALSE(svr.is_valid()) << method;
  9799. }
  9800. }
  9801. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9802. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9803. "COPY", "MOVE", "LOCK",
  9804. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9805. Server svr;
  9806. for (const auto *method : methods) {
  9807. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9808. }
  9809. EXPECT_TRUE(svr.is_valid());
  9810. }
  9811. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9812. Server svr;
  9813. svr.CustomRoute("POST", "/x",
  9814. [](const Request &, Response &, const ContentReader &) {});
  9815. EXPECT_FALSE(svr.is_valid());
  9816. }
  9817. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9818. Server svr;
  9819. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9820. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9821. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9822. EXPECT_FALSE(svr.is_valid());
  9823. }
  9824. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9825. Server svr;
  9826. auto captured = Error::Success;
  9827. svr.set_error_logger(
  9828. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9829. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9830. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9831. }
  9832. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9833. std::string out;
  9834. std::string request(
  9835. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9836. test_raw_request(request, &out);
  9837. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9838. }
  9839. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9840. std::string out;
  9841. std::string request(
  9842. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9843. test_raw_request(request, &out);
  9844. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9845. }
  9846. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9847. std::string out;
  9848. std::string request(
  9849. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9850. test_raw_request(request, &out);
  9851. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9852. }
  9853. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9854. std::string out;
  9855. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9856. "Host: localhost\r\n"
  9857. "Test: \r\n\r\n",
  9858. &out);
  9859. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9860. }
  9861. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9862. Server svr;
  9863. std::string x_custom;
  9864. std::string cookie;
  9865. std::string xff;
  9866. std::string x_unicode;
  9867. std::string x_iis;
  9868. svr.Get("/check", [&](const Request &req, Response &res) {
  9869. x_custom = req.get_header_value("X-Custom");
  9870. cookie = req.get_header_value("Cookie");
  9871. xff = req.get_header_value("X-Forwarded-For");
  9872. x_unicode = req.get_header_value("X-Unicode");
  9873. x_iis = req.get_header_value("X-IIS");
  9874. res.set_content("ok", "text/plain");
  9875. });
  9876. thread t = thread([&] { svr.listen(HOST, PORT); });
  9877. auto se = detail::scope_exit([&] {
  9878. svr.stop();
  9879. t.join();
  9880. ASSERT_FALSE(svr.is_running());
  9881. });
  9882. svr.wait_until_ready();
  9883. const std::string req = "GET /check HTTP/1.1\r\n"
  9884. "Host: localhost\r\n"
  9885. "X-Custom: a%0D%0AInjected: b\r\n"
  9886. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9887. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9888. "X-Unicode: %E3%81%82\r\n"
  9889. "X-IIS: %u00E9\r\n"
  9890. "Connection: close\r\n"
  9891. "\r\n";
  9892. std::string res;
  9893. ASSERT_TRUE(send_request(5, req, &res));
  9894. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9895. // Every value must be returned verbatim (wire form), with no decoding.
  9896. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9897. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9898. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9899. EXPECT_EQ("%E3%81%82", x_unicode);
  9900. EXPECT_EQ("%u00E9", x_iis);
  9901. }
  9902. // Applications that previously relied on automatic percent-decoding can
  9903. // reproduce the old behavior by explicitly calling decode_path_component()
  9904. // or, for RFC 3986 conformance, decode_uri_component().
  9905. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9906. Server svr;
  9907. std::string decoded;
  9908. svr.Get("/check", [&](const Request &req, Response &res) {
  9909. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9910. res.set_content("ok", "text/plain");
  9911. });
  9912. thread t = thread([&] { svr.listen(HOST, PORT); });
  9913. auto se = detail::scope_exit([&] {
  9914. svr.stop();
  9915. t.join();
  9916. ASSERT_FALSE(svr.is_running());
  9917. });
  9918. svr.wait_until_ready();
  9919. const std::string req = "GET /check HTTP/1.1\r\n"
  9920. "Host: localhost\r\n"
  9921. "X-Custom: hello%20world\r\n"
  9922. "Connection: close\r\n"
  9923. "\r\n";
  9924. std::string res;
  9925. ASSERT_TRUE(send_request(5, req, &res));
  9926. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9927. EXPECT_EQ("hello world", decoded);
  9928. }
  9929. // Regression test for #2033. Browsers send Referer values that include
  9930. // percent-encoded characters such as %0A inside the URL. Decoding the
  9931. // header value would either trip the post-decode CR/LF/NUL guard (the
  9932. // original bug, returning 400) or, after that guard was relaxed, silently
  9933. // store a literal LF — both unacceptable. The wire form must round-trip.
  9934. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9935. Server svr;
  9936. std::string referer;
  9937. svr.Get("/check", [&](const Request &req, Response &res) {
  9938. referer = req.get_header_value("Referer");
  9939. res.set_content("ok", "text/plain");
  9940. });
  9941. thread t = thread([&] { svr.listen(HOST, PORT); });
  9942. auto se = detail::scope_exit([&] {
  9943. svr.stop();
  9944. t.join();
  9945. ASSERT_FALSE(svr.is_running());
  9946. });
  9947. svr.wait_until_ready();
  9948. const std::string req = "GET /check HTTP/1.1\r\n"
  9949. "Host: localhost\r\n"
  9950. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9951. "Connection: close\r\n"
  9952. "\r\n";
  9953. std::string res;
  9954. ASSERT_TRUE(send_request(5, req, &res));
  9955. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9956. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9957. }
  9958. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9959. Server svr;
  9960. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9961. res.set_header("Cache-Control", "no-cache");
  9962. res.set_chunked_content_provider(
  9963. "text/event-stream", [](size_t offset, DataSink &sink) {
  9964. std::string s = "data:";
  9965. s += std::to_string(offset);
  9966. s += "\n\n";
  9967. auto ret = sink.write(s.data(), s.size());
  9968. EXPECT_TRUE(ret);
  9969. std::this_thread::sleep_for(std::chrono::seconds(1));
  9970. return true;
  9971. });
  9972. });
  9973. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9974. svr.wait_until_ready();
  9975. Client client(HOST, PORT);
  9976. const Headers headers = {{"Accept", "text/event-stream"}};
  9977. auto get_thread = std::thread([&client, &headers]() {
  9978. auto res = client.Get(
  9979. "/events", headers,
  9980. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9981. });
  9982. auto se = detail::scope_exit([&] {
  9983. svr.stop();
  9984. get_thread.join();
  9985. listen_thread.join();
  9986. ASSERT_FALSE(svr.is_running());
  9987. });
  9988. // Give GET time to get a few messages.
  9989. std::this_thread::sleep_for(std::chrono::seconds(2));
  9990. }
  9991. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9992. httplib::Server svr;
  9993. svr.Post("/hi",
  9994. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9995. res.status = StatusCode::OK_200;
  9996. });
  9997. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9998. svr.wait_until_ready();
  9999. Client cli(HOST, PORT);
  10000. auto res = cli.Post("/hi", "data", "text/plain");
  10001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10002. EXPECT_EQ(StatusCode::OK_200, res->status);
  10003. svr.stop();
  10004. thread.join();
  10005. ASSERT_FALSE(svr.is_running());
  10006. res = cli.Post("/hi", "data", "text/plain");
  10007. ASSERT_FALSE(res);
  10008. }
  10009. TEST(ServerStopTest, ListenFailure) {
  10010. Server svr;
  10011. auto t = thread([&]() {
  10012. auto ret = svr.listen("????", PORT);
  10013. EXPECT_FALSE(ret);
  10014. });
  10015. svr.wait_until_ready();
  10016. svr.stop();
  10017. t.join();
  10018. }
  10019. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10020. TEST(ServerStopTest, Decommision) {
  10021. Server svr;
  10022. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10023. for (int i = 0; i < 4; i++) {
  10024. auto is_even = !(i % 2);
  10025. std::thread t{[&] {
  10026. try {
  10027. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10028. if (is_even) {
  10029. throw std::runtime_error("Some thing that happens to go wrong.");
  10030. }
  10031. svr.listen(HOST, PORT);
  10032. } catch (...) { svr.decommission(); }
  10033. }};
  10034. svr.wait_until_ready();
  10035. // Server is up
  10036. {
  10037. Client cli(HOST, PORT);
  10038. auto res = cli.Get("/hi");
  10039. if (is_even) {
  10040. EXPECT_FALSE(res);
  10041. } else {
  10042. EXPECT_TRUE(res);
  10043. EXPECT_EQ("hi...", res->body);
  10044. }
  10045. }
  10046. svr.stop();
  10047. t.join();
  10048. // Server is down...
  10049. {
  10050. Client cli(HOST, PORT);
  10051. auto res = cli.Get("/hi");
  10052. EXPECT_FALSE(res);
  10053. }
  10054. }
  10055. }
  10056. #endif
  10057. // Helper function for string body upload progress tests
  10058. template <typename SetupHandler, typename ClientCall>
  10059. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10060. ClientCall &&client_call,
  10061. const string &body) {
  10062. Server svr;
  10063. setup_handler(svr);
  10064. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10065. auto se = detail::scope_exit([&] {
  10066. svr.stop();
  10067. t.join();
  10068. });
  10069. svr.wait_until_ready();
  10070. Client cli(HOST, PORT);
  10071. vector<uint64_t> progress_values;
  10072. bool progress_called = false;
  10073. auto res =
  10074. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10075. progress_values.push_back(current);
  10076. progress_called = true;
  10077. return true;
  10078. });
  10079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10080. EXPECT_EQ(200, res->status);
  10081. EXPECT_TRUE(progress_called);
  10082. }
  10083. TEST(UploadProgressTest, PostStringBodyBasic) {
  10084. TestStringBodyUploadProgress(
  10085. [](Server &svr) {
  10086. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10087. res.set_content("received", "text/plain");
  10088. });
  10089. },
  10090. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10091. return cli.Post("/test", body, "text/plain", progress_callback);
  10092. },
  10093. "test data for upload progress");
  10094. }
  10095. TEST(UploadProgressTest, PutStringBodyBasic) {
  10096. TestStringBodyUploadProgress(
  10097. [](Server &svr) {
  10098. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10099. res.set_content("put received", "text/plain");
  10100. });
  10101. },
  10102. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10103. return cli.Put("/test", body, "text/plain", progress_callback);
  10104. },
  10105. "put test data for upload progress");
  10106. }
  10107. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10108. TestStringBodyUploadProgress(
  10109. [](Server &svr) {
  10110. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10111. res.set_content("patch received", "text/plain");
  10112. });
  10113. },
  10114. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10115. return cli.Patch("/test", body, "text/plain", progress_callback);
  10116. },
  10117. "patch test data for upload progress");
  10118. }
  10119. // Helper function for content provider upload progress tests
  10120. template <typename SetupHandler, typename ClientCall>
  10121. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10122. ClientCall &&client_call) {
  10123. Server svr;
  10124. setup_handler(svr);
  10125. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10126. auto se = detail::scope_exit([&] {
  10127. svr.stop();
  10128. t.join();
  10129. });
  10130. svr.wait_until_ready();
  10131. Client cli(HOST, PORT);
  10132. vector<uint64_t> progress_values;
  10133. auto res =
  10134. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10135. progress_values.push_back(current);
  10136. return true;
  10137. });
  10138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10139. EXPECT_EQ(200, res->status);
  10140. EXPECT_FALSE(progress_values.empty());
  10141. }
  10142. TEST(UploadProgressTest, PostContentProviderProgress) {
  10143. TestContentProviderUploadProgress(
  10144. [](Server &svr) {
  10145. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10146. res.set_content("provider received", "text/plain");
  10147. });
  10148. },
  10149. [](Client &cli, UploadProgress progress_callback) {
  10150. return cli.Post(
  10151. "/test", 9,
  10152. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10153. sink.os << "test data";
  10154. return true;
  10155. },
  10156. "text/plain", progress_callback);
  10157. });
  10158. }
  10159. // Helper function for multipart upload progress tests
  10160. template <typename SetupHandler, typename ClientCall>
  10161. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10162. ClientCall &&client_call,
  10163. const string &endpoint) {
  10164. Server svr;
  10165. setup_handler(svr);
  10166. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10167. auto se = detail::scope_exit([&] {
  10168. svr.stop();
  10169. t.join();
  10170. });
  10171. svr.wait_until_ready();
  10172. Client cli(HOST, PORT);
  10173. vector<uint64_t> progress_values;
  10174. UploadFormDataItems items = {
  10175. {"field1", "value1", "", ""},
  10176. {"field2", "longer value for progress tracking test", "", ""},
  10177. {"file1", "file content data for upload progress", "test.txt",
  10178. "text/plain"}};
  10179. auto res = client_call(cli, endpoint, items,
  10180. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10181. progress_values.push_back(current);
  10182. return true;
  10183. });
  10184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10185. EXPECT_EQ(200, res->status);
  10186. EXPECT_FALSE(progress_values.empty());
  10187. }
  10188. TEST(UploadProgressTest, PostMultipartProgress) {
  10189. TestMultipartUploadProgress(
  10190. [](Server &svr) {
  10191. svr.Post("/multipart", [](const Request &req, Response &res) {
  10192. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10193. res.set_content("multipart received", "text/plain");
  10194. });
  10195. },
  10196. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10197. UploadProgress progress_callback) {
  10198. return cli.Post(endpoint, items, progress_callback);
  10199. },
  10200. "/multipart");
  10201. }
  10202. // Helper function for basic download progress tests
  10203. template <typename SetupHandler, typename ClientCall>
  10204. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10205. ClientCall &&client_call, const string &endpoint,
  10206. size_t expected_content_size) {
  10207. Server svr;
  10208. setup_handler(svr);
  10209. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10210. auto se = detail::scope_exit([&] {
  10211. svr.stop();
  10212. t.join();
  10213. });
  10214. svr.wait_until_ready();
  10215. Client cli(HOST, PORT);
  10216. vector<uint64_t> progress_values;
  10217. auto res = client_call(cli, endpoint,
  10218. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10219. progress_values.push_back(current);
  10220. return true;
  10221. });
  10222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10223. EXPECT_EQ(200, res->status);
  10224. EXPECT_FALSE(progress_values.empty());
  10225. EXPECT_EQ(expected_content_size, res->body.size());
  10226. }
  10227. TEST(DownloadProgressTest, GetBasic) {
  10228. TestBasicDownloadProgress(
  10229. [](Server &svr) {
  10230. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10231. string content(1000, 'D');
  10232. res.set_content(content, "text/plain");
  10233. });
  10234. },
  10235. [](Client &cli, const string &endpoint,
  10236. DownloadProgress progress_callback) {
  10237. return cli.Get(endpoint, progress_callback);
  10238. },
  10239. "/download", 1000u);
  10240. }
  10241. // Helper function for content receiver download progress tests
  10242. template <typename SetupHandler, typename ClientCall>
  10243. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10244. ClientCall &&client_call,
  10245. const string &endpoint,
  10246. size_t expected_content_size) {
  10247. Server svr;
  10248. setup_handler(svr);
  10249. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10250. auto se = detail::scope_exit([&] {
  10251. svr.stop();
  10252. t.join();
  10253. });
  10254. svr.wait_until_ready();
  10255. Client cli(HOST, PORT);
  10256. vector<uint64_t> progress_values;
  10257. string received_body;
  10258. auto res = client_call(
  10259. cli, endpoint,
  10260. [&](const char *data, size_t data_length) -> bool {
  10261. received_body.append(data, data_length);
  10262. return true;
  10263. },
  10264. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10265. progress_values.push_back(current);
  10266. return true;
  10267. });
  10268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10269. EXPECT_EQ(200, res->status);
  10270. EXPECT_FALSE(progress_values.empty());
  10271. EXPECT_EQ(expected_content_size, received_body.size());
  10272. EXPECT_TRUE(res->body.empty());
  10273. }
  10274. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10275. TestContentReceiverDownloadProgress(
  10276. [](Server &svr) {
  10277. svr.Get("/download-receiver",
  10278. [](const Request & /*req*/, Response &res) {
  10279. string content(2000, 'R');
  10280. res.set_content(content, "text/plain");
  10281. });
  10282. },
  10283. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10284. DownloadProgress progress_callback) {
  10285. return cli.Get(endpoint, content_receiver, progress_callback);
  10286. },
  10287. "/download-receiver", 2000u);
  10288. }
  10289. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10290. // A provider reaching a pass with nothing to hand over - an empty buffer
  10291. // popped off a queue, say - must not be taken to mean the body is finished.
  10292. // It used to end the loop with the terminating chunk unwritten while the
  10293. // server still considered the response complete, so the peer waited for an
  10294. // end that never arrived.
  10295. Server svr;
  10296. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10297. auto step = std::make_shared<int>(0);
  10298. res.set_chunked_content_provider("text/plain",
  10299. [step](size_t /*offset*/, DataSink &sink) {
  10300. switch ((*step)++) {
  10301. case 0: sink.write("", 0); break;
  10302. case 1: sink.write("hello", 5); break;
  10303. default: sink.done(); break;
  10304. }
  10305. return true;
  10306. });
  10307. });
  10308. auto port = svr.bind_to_any_port(HOST);
  10309. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10310. auto listen_se = detail::scope_exit([&] {
  10311. svr.stop();
  10312. listen_thread.join();
  10313. ASSERT_FALSE(svr.is_running());
  10314. });
  10315. svr.wait_until_ready();
  10316. Client cli(HOST, port);
  10317. // Without the fix the body is never terminated, so bound the wait rather
  10318. // than letting the test hang on the default read timeout.
  10319. cli.set_read_timeout(5, 0);
  10320. auto res = cli.Get("/stream");
  10321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10322. EXPECT_EQ(StatusCode::OK_200, res->status);
  10323. EXPECT_EQ("hello", res->body);
  10324. }
  10325. TEST(StreamingTest, NoContentLengthStreaming) {
  10326. Server svr;
  10327. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10328. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10329. if (offset < 6) {
  10330. sink.os << (offset < 3 ? "a" : "b");
  10331. } else {
  10332. sink.done();
  10333. }
  10334. return true;
  10335. });
  10336. });
  10337. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10338. auto listen_se = detail::scope_exit([&] {
  10339. svr.stop();
  10340. listen_thread.join();
  10341. ASSERT_FALSE(svr.is_running());
  10342. });
  10343. svr.wait_until_ready();
  10344. Client client(HOST, PORT);
  10345. auto get_thread = std::thread([&client]() {
  10346. std::string s;
  10347. auto res =
  10348. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10349. s += std::string(data, len);
  10350. return true;
  10351. });
  10352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10353. EXPECT_EQ(StatusCode::OK_200, res->status);
  10354. EXPECT_EQ("aaabbb", s);
  10355. });
  10356. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10357. // Give GET time to get a few messages.
  10358. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10359. }
  10360. TEST(MountTest, Unmount) {
  10361. Server svr;
  10362. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10363. auto se = detail::scope_exit([&] {
  10364. svr.stop();
  10365. listen_thread.join();
  10366. ASSERT_FALSE(svr.is_running());
  10367. });
  10368. svr.wait_until_ready();
  10369. Client cli("localhost", PORT);
  10370. svr.set_mount_point("/mount2", "./www2");
  10371. auto res = cli.Get("/");
  10372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10373. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10374. res = cli.Get("/mount2/dir/test.html");
  10375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10376. EXPECT_EQ(StatusCode::OK_200, res->status);
  10377. svr.set_mount_point("/", "./www");
  10378. res = cli.Get("/dir/");
  10379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10380. EXPECT_EQ(StatusCode::OK_200, res->status);
  10381. svr.remove_mount_point("/");
  10382. res = cli.Get("/dir/");
  10383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10384. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10385. svr.remove_mount_point("/mount2");
  10386. res = cli.Get("/mount2/dir/test.html");
  10387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10388. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10389. }
  10390. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10391. Server svr;
  10392. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10393. svr.Get("/api/hello", [](const Request &, Response &res) {
  10394. res.set_content("api", "text/plain");
  10395. });
  10396. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10397. auto se = detail::scope_exit([&] {
  10398. svr.stop();
  10399. listen_thread.join();
  10400. ASSERT_FALSE(svr.is_running());
  10401. });
  10402. svr.wait_until_ready();
  10403. Client cli(HOST, PORT);
  10404. auto res = cli.Get("/dir/test.html");
  10405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10406. EXPECT_EQ(StatusCode::OK_200, res->status);
  10407. res = cli.Get("/api/hello");
  10408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10409. EXPECT_EQ(StatusCode::OK_200, res->status);
  10410. EXPECT_EQ("api", res->body);
  10411. }
  10412. TEST(MountTest, PathSegmentBoundary) {
  10413. Server svr;
  10414. svr.set_mount_point("/mount2", "./www2");
  10415. svr.set_mount_point("/", "./www");
  10416. auto port = svr.bind_to_any_port(HOST);
  10417. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10418. auto se = detail::scope_exit([&] {
  10419. svr.stop();
  10420. listen_thread.join();
  10421. ASSERT_FALSE(svr.is_running());
  10422. });
  10423. svr.wait_until_ready();
  10424. Client cli(HOST, port);
  10425. auto res = cli.Get("/mount2/dir/test.html");
  10426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10427. EXPECT_EQ(StatusCode::OK_200, res->status);
  10428. // "/mount2" must not match part-way through a path segment.
  10429. res = cli.Get("/mount2dir/test.html");
  10430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10431. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10432. // A mount point ending in '/' keeps matching every path below it.
  10433. res = cli.Get("/dir/test.html");
  10434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10435. EXPECT_EQ(StatusCode::OK_200, res->status);
  10436. }
  10437. TEST(MountTest, Redicect) {
  10438. Server svr;
  10439. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10440. auto se = detail::scope_exit([&] {
  10441. svr.stop();
  10442. listen_thread.join();
  10443. ASSERT_FALSE(svr.is_running());
  10444. });
  10445. svr.set_mount_point("/", "./www");
  10446. svr.wait_until_ready();
  10447. Client cli("localhost", PORT);
  10448. auto res = cli.Get("/dir/");
  10449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10450. EXPECT_EQ(StatusCode::OK_200, res->status);
  10451. res = cli.Get("/dir");
  10452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10453. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10454. res = cli.Get("/file");
  10455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10456. EXPECT_EQ(StatusCode::OK_200, res->status);
  10457. res = cli.Get("/file/");
  10458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10459. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10460. cli.set_follow_location(true);
  10461. res = cli.Get("/dir");
  10462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10463. EXPECT_EQ(StatusCode::OK_200, res->status);
  10464. }
  10465. TEST(MountTest, MultibytesPathName) {
  10466. Server svr;
  10467. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10468. auto se = detail::scope_exit([&] {
  10469. svr.stop();
  10470. listen_thread.join();
  10471. ASSERT_FALSE(svr.is_running());
  10472. });
  10473. svr.set_mount_point("/", "./www");
  10474. svr.wait_until_ready();
  10475. Client cli("localhost", PORT);
  10476. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10478. EXPECT_EQ(StatusCode::OK_200, res->status);
  10479. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10480. }
  10481. #ifdef _WIN32
  10482. // Issue #2435: mmap::open() must succeed even when another handle holds
  10483. // the file open for writing (e.g. an active log file).
  10484. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10485. const char *path = "mmap_concurrent_writer_test.txt";
  10486. const char *content = "hello";
  10487. {
  10488. std::ofstream f(path, std::ios::binary);
  10489. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10490. }
  10491. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10492. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10493. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10494. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10495. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10496. detail::mmap m(path);
  10497. ASSERT_TRUE(m.is_open());
  10498. EXPECT_EQ(strlen(content), m.size());
  10499. char buf[8];
  10500. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10501. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10502. }
  10503. #endif
  10504. #ifndef _WIN32
  10505. // A directory or a device has no size to serve.
  10506. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10507. const char *path = "./mmap_not_regular_test_dir";
  10508. ASSERT_EQ(0, ::mkdir(path, 0755));
  10509. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10510. for (auto p : {path, "/dev/null"}) {
  10511. detail::mmap m(p);
  10512. EXPECT_FALSE(m.is_open()) << p;
  10513. EXPECT_EQ(0U, m.size()) << p;
  10514. }
  10515. Server svr;
  10516. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10517. res.set_file_content("/dev/null");
  10518. });
  10519. auto port = svr.bind_to_any_port(HOST);
  10520. thread t = thread([&] { svr.listen_after_bind(); });
  10521. auto se = detail::scope_exit([&] {
  10522. svr.stop();
  10523. t.join();
  10524. });
  10525. svr.wait_until_ready();
  10526. auto res = Client(HOST, port).Get("/null");
  10527. ASSERT_TRUE(res);
  10528. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10529. }
  10530. #endif
  10531. #ifdef __linux__
  10532. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10533. TEST(MmapTest, FileIsNotMapped) {
  10534. const char *path = "mmap_not_mapped_test.txt";
  10535. {
  10536. std::ofstream f(path, std::ios::binary);
  10537. f << "hello";
  10538. }
  10539. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10540. detail::mmap m(path);
  10541. ASSERT_TRUE(m.is_open());
  10542. std::ifstream maps("/proc/self/maps");
  10543. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10544. std::istreambuf_iterator<char>());
  10545. EXPECT_EQ(std::string::npos, mappings.find(path));
  10546. }
  10547. #endif
  10548. TEST(KeepAliveTest, ReadTimeout) {
  10549. Server svr;
  10550. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10551. std::this_thread::sleep_for(std::chrono::seconds(2));
  10552. res.set_content("a", "text/plain");
  10553. });
  10554. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10555. res.set_content("b", "text/plain");
  10556. });
  10557. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10558. auto se = detail::scope_exit([&] {
  10559. svr.stop();
  10560. listen_thread.join();
  10561. ASSERT_FALSE(svr.is_running());
  10562. });
  10563. svr.wait_until_ready();
  10564. Client cli("localhost", PORT);
  10565. cli.set_keep_alive(true);
  10566. cli.set_read_timeout(std::chrono::seconds(1));
  10567. auto resa = cli.Get("/a");
  10568. ASSERT_FALSE(resa);
  10569. EXPECT_EQ(Error::Read, resa.error());
  10570. auto resb = cli.Get("/b");
  10571. ASSERT_TRUE(resb);
  10572. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10573. EXPECT_EQ("b", resb->body);
  10574. }
  10575. TEST(KeepAliveTest, MaxCount) {
  10576. size_t keep_alive_max_count = 3;
  10577. Server svr;
  10578. svr.set_keep_alive_max_count(keep_alive_max_count);
  10579. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10580. res.set_content("Hello World!", "text/plain");
  10581. });
  10582. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10583. auto se = detail::scope_exit([&] {
  10584. svr.stop();
  10585. listen_thread.join();
  10586. ASSERT_FALSE(svr.is_running());
  10587. });
  10588. svr.wait_until_ready();
  10589. Client cli(HOST, PORT);
  10590. cli.set_keep_alive(true);
  10591. for (size_t i = 0; i < 5; i++) {
  10592. auto result = cli.Get("/hi");
  10593. ASSERT_TRUE(result);
  10594. EXPECT_EQ(StatusCode::OK_200, result->status);
  10595. if (i == keep_alive_max_count - 1) {
  10596. EXPECT_EQ("close", result->get_header_value("Connection"));
  10597. } else {
  10598. EXPECT_FALSE(result->has_header("Connection"));
  10599. }
  10600. }
  10601. }
  10602. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10603. // can pull the next one into the server's buffer. The server must serve it
  10604. // without waiting for the socket to become readable again. The keep-alive
  10605. // timeout outlasts the client's read timeout, so a request left waiting for it
  10606. // shows up as a missing response.
  10607. static void serve_pipelining_routes(Server &svr,
  10608. const std::function<void(int)> &client) {
  10609. svr.set_keep_alive_timeout(5);
  10610. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10611. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10612. });
  10613. svr.Post("/echo", [](const Request &req, Response &res) {
  10614. res.set_content("echo " + req.body, "text/plain");
  10615. });
  10616. auto port = svr.bind_to_any_port(HOST);
  10617. thread t = thread([&] { svr.listen_after_bind(); });
  10618. auto se = detail::scope_exit([&] {
  10619. svr.stop();
  10620. t.join();
  10621. });
  10622. svr.wait_until_ready();
  10623. client(port);
  10624. }
  10625. static std::string
  10626. send_pipelined_requests(const std::vector<std::string> &parts) {
  10627. Server svr;
  10628. std::string res;
  10629. serve_pipelining_routes(svr, [&](int port) {
  10630. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10631. });
  10632. return res;
  10633. }
  10634. static void expect_in_order(const std::string &res,
  10635. const std::vector<std::string> &bodies) {
  10636. size_t pos = 0;
  10637. for (const auto &body : bodies) {
  10638. pos = res.find(body, pos);
  10639. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10640. pos += body.size();
  10641. }
  10642. }
  10643. TEST(KeepAliveTest, PipelinedRequests) {
  10644. auto res = send_pipelined_requests(
  10645. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10646. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10647. "Content-Length: 4\r\n\r\nbody"
  10648. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10649. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10650. }
  10651. // The second request starts in the server's buffer and ends on the socket.
  10652. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10653. auto res =
  10654. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10655. "GET /hi/2 HTTP/1.1\r\nHo",
  10656. "st: localhost\r\nConnection: close\r\n\r\n"});
  10657. expect_in_order(res, {"hi 1", "hi 2"});
  10658. }
  10659. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10660. // CRLF after a body does not turn into a 400 for the next request.
  10661. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10662. auto res = send_pipelined_requests(
  10663. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10664. "Content-Length: 4\r\n\r\nbody\r\n"
  10665. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10666. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10667. expect_in_order(res, {"echo body", "hi 2"});
  10668. }
  10669. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10670. // must not be served as the next request.
  10671. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10672. auto res = send_pipelined_requests(
  10673. {"INVALID REQUEST LINE\r\n\r\n"
  10674. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10675. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10676. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10677. }
  10678. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10679. // Over TLS, the next request is held by the TLS library as already decrypted
  10680. // data rather than on the socket.
  10681. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10682. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10683. std::string res;
  10684. serve_pipelining_routes(svr, [&](int port) {
  10685. // One part, so all three requests arrive in one TLS record
  10686. EXPECT_TRUE(send_ssl_request_in_parts(
  10687. 2,
  10688. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10689. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10690. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10691. &res, port));
  10692. });
  10693. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10694. }
  10695. #endif
  10696. TEST(KeepAliveTest, Issue1041) {
  10697. Server svr;
  10698. svr.set_keep_alive_timeout(3);
  10699. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10700. res.set_content("Hello World!", "text/plain");
  10701. });
  10702. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10703. auto se = detail::scope_exit([&] {
  10704. svr.stop();
  10705. listen_thread.join();
  10706. ASSERT_FALSE(svr.is_running());
  10707. });
  10708. svr.wait_until_ready();
  10709. Client cli(HOST, PORT);
  10710. cli.set_keep_alive(true);
  10711. auto result = cli.Get("/hi");
  10712. ASSERT_TRUE(result);
  10713. EXPECT_EQ(StatusCode::OK_200, result->status);
  10714. std::this_thread::sleep_for(std::chrono::seconds(5));
  10715. result = cli.Get("/hi");
  10716. ASSERT_TRUE(result);
  10717. EXPECT_EQ(StatusCode::OK_200, result->status);
  10718. }
  10719. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10720. Server svr;
  10721. svr.set_keep_alive_max_count(0);
  10722. std::set<int> remote_ports;
  10723. svr.Get("/hi", [&](const Request &req, Response &res) {
  10724. remote_ports.insert(req.remote_port);
  10725. res.set_content("hi", "text/plain");
  10726. });
  10727. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10728. auto se = detail::scope_exit([&] {
  10729. svr.stop();
  10730. listen_thread.join();
  10731. ASSERT_FALSE(svr.is_running());
  10732. });
  10733. svr.wait_until_ready();
  10734. Client cli(HOST, PORT);
  10735. cli.set_keep_alive(true);
  10736. for (int i = 0; i < 3; i++) {
  10737. auto res = cli.Get("/hi");
  10738. ASSERT_TRUE(res);
  10739. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  10740. }
  10741. // All three over one connection
  10742. EXPECT_EQ(1u, remote_ports.size());
  10743. }
  10744. TEST(KeepAliveTest, Issue1959) {
  10745. Server svr;
  10746. svr.set_keep_alive_timeout(5);
  10747. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10748. res.set_content("a", "text/plain");
  10749. });
  10750. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10751. auto se = detail::scope_exit([&] {
  10752. if (!svr.is_running()) return;
  10753. svr.stop();
  10754. listen_thread.join();
  10755. ASSERT_FALSE(svr.is_running());
  10756. });
  10757. svr.wait_until_ready();
  10758. Client cli("localhost", PORT);
  10759. cli.set_keep_alive(true);
  10760. using namespace std::chrono;
  10761. auto start = steady_clock::now();
  10762. cli.Get("/a");
  10763. svr.stop();
  10764. listen_thread.join();
  10765. auto end = steady_clock::now();
  10766. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10767. EXPECT_LT(elapsed, 5000);
  10768. }
  10769. #ifdef CPPHTTPLIB_SSL_ENABLED
  10770. TEST(KeepAliveTest, SSLClientReconnection) {
  10771. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10772. ASSERT_TRUE(svr.is_valid());
  10773. svr.set_keep_alive_timeout(1);
  10774. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10775. res.set_content("Hello World!", "text/plain");
  10776. });
  10777. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10778. auto se = detail::scope_exit([&] {
  10779. svr.stop();
  10780. listen_thread.join();
  10781. ASSERT_FALSE(svr.is_running());
  10782. });
  10783. svr.wait_until_ready();
  10784. SSLClient cli(HOST, PORT);
  10785. cli.enable_server_certificate_verification(false);
  10786. cli.set_keep_alive(true);
  10787. auto result = cli.Get("/hi");
  10788. ASSERT_TRUE(result);
  10789. EXPECT_EQ(StatusCode::OK_200, result->status);
  10790. result = cli.Get("/hi");
  10791. ASSERT_TRUE(result);
  10792. EXPECT_EQ(StatusCode::OK_200, result->status);
  10793. std::this_thread::sleep_for(std::chrono::seconds(2));
  10794. // Recoonect
  10795. result = cli.Get("/hi");
  10796. ASSERT_TRUE(result);
  10797. EXPECT_EQ(StatusCode::OK_200, result->status);
  10798. result = cli.Get("/hi");
  10799. ASSERT_TRUE(result);
  10800. EXPECT_EQ(StatusCode::OK_200, result->status);
  10801. }
  10802. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10803. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10804. ASSERT_TRUE(svr.is_valid());
  10805. svr.set_keep_alive_timeout(1);
  10806. std::string content = "reconnect";
  10807. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10808. res.set_content("Hello World!", "text/plain");
  10809. });
  10810. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10811. auto se = detail::scope_exit([&] {
  10812. svr.stop();
  10813. listen_thread.join();
  10814. ASSERT_FALSE(svr.is_running());
  10815. });
  10816. svr.wait_until_ready();
  10817. SSLClient cli(HOST, PORT);
  10818. cli.enable_server_certificate_verification(false);
  10819. cli.set_keep_alive(true);
  10820. auto result = cli.Post(
  10821. "/hi", content.size(),
  10822. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10823. sink.write(content.c_str(), content.size());
  10824. return true;
  10825. },
  10826. "text/plain");
  10827. ASSERT_TRUE(result);
  10828. EXPECT_EQ(200, result->status);
  10829. std::this_thread::sleep_for(std::chrono::seconds(2));
  10830. // Recoonect
  10831. result = cli.Post(
  10832. "/hi", content.size(),
  10833. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10834. sink.write(content.c_str(), content.size());
  10835. return true;
  10836. },
  10837. "text/plain");
  10838. ASSERT_TRUE(result);
  10839. EXPECT_EQ(200, result->status);
  10840. result = cli.Post(
  10841. "/hi", content.size(),
  10842. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10843. sink.write(content.c_str(), content.size());
  10844. return true;
  10845. },
  10846. "text/plain");
  10847. ASSERT_TRUE(result);
  10848. EXPECT_EQ(200, result->status);
  10849. }
  10850. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10851. using namespace httplib::tls;
  10852. {
  10853. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10854. ASSERT_TRUE(svr.is_valid());
  10855. svr.Get("/sni", [&](const Request &req, Response &res) {
  10856. std::string expected = req.sni();
  10857. EXPECT_EQ(expected, req.get_param_value("expected"));
  10858. res.set_content("ok", "text/plain");
  10859. });
  10860. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10861. auto se = detail::scope_exit([&] {
  10862. svr.stop();
  10863. listen_thread.join();
  10864. ASSERT_FALSE(svr.is_running());
  10865. });
  10866. svr.wait_until_ready();
  10867. {
  10868. SSLClient cli("localhost", PORT);
  10869. cli.enable_server_certificate_verification(false);
  10870. auto res = cli.Get("/sni?expected=localhost");
  10871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10872. }
  10873. {
  10874. SSLClient cli("::1", PORT);
  10875. cli.enable_server_certificate_verification(false);
  10876. auto res = cli.Get("/sni?expected=");
  10877. // NOTE: This may fail if the server is listening on IPv4 only
  10878. // (e.g., when localhost resolves to 127.0.0.1 only)
  10879. if (res) {
  10880. EXPECT_EQ(StatusCode::OK_200, res->status);
  10881. } else {
  10882. EXPECT_EQ(Error::Connection, res.error());
  10883. }
  10884. }
  10885. }
  10886. }
  10887. #endif
  10888. TEST(ClientProblemDetectionTest, ContentProvider) {
  10889. Server svr;
  10890. size_t content_length = 1024 * 1024;
  10891. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10892. res.set_content_provider(
  10893. content_length, "text/plain",
  10894. [&](size_t offset, size_t length, DataSink &sink) {
  10895. auto out_len = std::min(length, static_cast<size_t>(1024));
  10896. std::string out(out_len, '@');
  10897. sink.write(out.data(), out_len);
  10898. return offset < 4096;
  10899. },
  10900. [](bool success) { ASSERT_FALSE(success); });
  10901. });
  10902. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10903. res.set_content_provider(
  10904. 0, "text/plain",
  10905. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10906. EXPECT_TRUE(false);
  10907. return true;
  10908. },
  10909. [](bool success) { ASSERT_FALSE(success); });
  10910. });
  10911. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10912. auto se = detail::scope_exit([&] {
  10913. svr.stop();
  10914. listen_thread.join();
  10915. ASSERT_FALSE(svr.is_running());
  10916. });
  10917. svr.wait_until_ready();
  10918. Client cli("localhost", PORT);
  10919. {
  10920. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10921. size_t /*data_length*/) { return false; });
  10922. ASSERT_FALSE(res);
  10923. }
  10924. {
  10925. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10926. size_t /*data_length*/) { return false; });
  10927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10928. }
  10929. }
  10930. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10931. // A provider that reports success without writing anything and without
  10932. // calling done() used to be handed the same offset and length again on every
  10933. // pass, so it spun for as long as the peer stayed connected.
  10934. Server svr;
  10935. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10936. res.set_content("ok", "text/plain");
  10937. });
  10938. auto port = svr.bind_to_any_port(HOST);
  10939. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10940. auto se = detail::scope_exit([&] {
  10941. svr.stop();
  10942. listen_thread.join();
  10943. ASSERT_FALSE(svr.is_running());
  10944. });
  10945. svr.wait_until_ready();
  10946. std::atomic<int> call_count{0};
  10947. Client cli(HOST, port);
  10948. auto res = cli.Post(
  10949. "/", 1024,
  10950. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10951. // Give up after enough passes to show the spin, so that losing the
  10952. // check below fails this test instead of hanging it.
  10953. return ++call_count < 100;
  10954. },
  10955. "text/plain");
  10956. ASSERT_FALSE(res);
  10957. EXPECT_EQ(Error::Write, res.error());
  10958. EXPECT_EQ(1, call_count.load());
  10959. }
  10960. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10961. // A writer only has to assign `write`. The other three used to be left as
  10962. // empty std::functions, so a provider calling one threw
  10963. // std::bad_function_call out of the thread running it and took the whole
  10964. // process down.
  10965. DataSink sink;
  10966. std::string written;
  10967. sink.write = [&](const char *data, size_t data_len) {
  10968. written.append(data, data_len);
  10969. return true;
  10970. };
  10971. EXPECT_TRUE(sink.is_writable());
  10972. sink.done();
  10973. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10974. EXPECT_TRUE(written.empty());
  10975. }
  10976. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10977. // A sink that cannot carry trailers still has to finish.
  10978. DataSink sink;
  10979. auto done_count = 0;
  10980. sink.done = [&]() { done_count++; };
  10981. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10982. EXPECT_EQ(1, done_count);
  10983. }
  10984. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10985. Server svr;
  10986. const std::string body(4096, 'x');
  10987. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10988. res.set_content_provider(body.size(), "text/plain",
  10989. [&](size_t offset, size_t length, DataSink &sink) {
  10990. sink.write(body.data() + offset, length);
  10991. sink.done();
  10992. return true;
  10993. });
  10994. });
  10995. auto port = svr.bind_to_any_port(HOST);
  10996. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10997. auto se = detail::scope_exit([&] {
  10998. svr.stop();
  10999. listen_thread.join();
  11000. ASSERT_FALSE(svr.is_running());
  11001. });
  11002. svr.wait_until_ready();
  11003. Client cli(HOST, port);
  11004. auto res = cli.Get("/");
  11005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11006. EXPECT_EQ(StatusCode::OK_200, res->status);
  11007. EXPECT_EQ(body, res->body);
  11008. }
  11009. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11010. Server svr;
  11011. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11012. res.set_content_provider(
  11013. 1024, "text/plain",
  11014. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11015. sink.write("hello", 5);
  11016. sink.done(); // short of the 1024 bytes the response promised
  11017. return true;
  11018. });
  11019. });
  11020. auto port = svr.bind_to_any_port(HOST);
  11021. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11022. auto se = detail::scope_exit([&] {
  11023. svr.stop();
  11024. listen_thread.join();
  11025. ASSERT_FALSE(svr.is_running());
  11026. });
  11027. svr.wait_until_ready();
  11028. Client cli(HOST, port);
  11029. cli.set_read_timeout(5, 0);
  11030. // The response is short of its Content-Length, so the client cannot read a
  11031. // complete body. What matters is that this returns at all: a no-op done()
  11032. // would leave the writer looping over a provider that never makes progress.
  11033. auto res = cli.Get("/");
  11034. EXPECT_FALSE(res);
  11035. }
  11036. // Read as the next response by a peer that sees it after a framed body.
  11037. static const std::string smuggled_response =
  11038. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11039. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11040. Server svr;
  11041. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11042. res.set_content_provider(
  11043. 5, "text/plain",
  11044. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11045. auto data = "AAAAA" + smuggled_response;
  11046. sink.write(data.data(), data.size());
  11047. return true;
  11048. });
  11049. });
  11050. thread t = thread([&] { svr.listen(HOST, PORT); });
  11051. auto se = detail::scope_exit([&] {
  11052. svr.stop();
  11053. t.join();
  11054. ASSERT_FALSE(svr.is_running());
  11055. });
  11056. svr.wait_until_ready();
  11057. std::string resp;
  11058. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11059. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11060. resp.clear();
  11061. ASSERT_TRUE(send_request(
  11062. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11063. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11064. }
  11065. TEST(NoContentTest, BodyIsNotSent) {
  11066. Server svr;
  11067. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11068. res.status = StatusCode::NoContent_204;
  11069. res.set_content(smuggled_response, "text/plain");
  11070. });
  11071. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11072. res.status = StatusCode::NotModified_304;
  11073. res.set_chunked_content_provider(
  11074. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11075. sink.write(smuggled_response.data(), smuggled_response.size());
  11076. sink.done();
  11077. return true;
  11078. });
  11079. });
  11080. thread t = thread([&] { svr.listen(HOST, PORT); });
  11081. auto se = detail::scope_exit([&] {
  11082. svr.stop();
  11083. t.join();
  11084. ASSERT_FALSE(svr.is_running());
  11085. });
  11086. svr.wait_until_ready();
  11087. for (auto path : {"/204", "/304"}) {
  11088. std::string resp;
  11089. ASSERT_TRUE(send_request(
  11090. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11091. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11092. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11093. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11094. }
  11095. }
  11096. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11097. Server svr;
  11098. std::atomic<bool> smuggled(false);
  11099. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11100. res.set_content("ok", "text/plain");
  11101. });
  11102. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11103. smuggled = true;
  11104. });
  11105. auto port = svr.bind_to_any_port(HOST);
  11106. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11107. auto se = detail::scope_exit([&] {
  11108. svr.stop();
  11109. listen_thread.join();
  11110. ASSERT_FALSE(svr.is_running());
  11111. });
  11112. svr.wait_until_ready();
  11113. // What follows the body would be read as the next request.
  11114. Client cli(HOST, port);
  11115. auto res = cli.Post(
  11116. "/", 5,
  11117. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11118. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11119. sink.write(data.data(), data.size());
  11120. return true;
  11121. },
  11122. "text/plain");
  11123. ASSERT_FALSE(res);
  11124. EXPECT_EQ(Error::Write, res.error());
  11125. EXPECT_FALSE(smuggled);
  11126. }
  11127. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11128. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11129. // The compressed path builds the whole body before connecting, so this
  11130. // fails client-side and never reaches a server.
  11131. Client cli(HOST, PORT);
  11132. cli.set_compress(true);
  11133. auto res = cli.Post(
  11134. "/", 1024,
  11135. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11136. sink.write("hello", 5);
  11137. sink.done(); // short of the 1024 bytes the request announced
  11138. return true;
  11139. },
  11140. "text/plain");
  11141. ASSERT_FALSE(res);
  11142. EXPECT_EQ(Error::Write, res.error());
  11143. }
  11144. #endif
  11145. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11146. Server svr;
  11147. svr.set_error_handler([](Request const &, Response &res) -> void {
  11148. res.set_chunked_content_provider(
  11149. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11150. sink.os << "hello";
  11151. sink.os << "world";
  11152. sink.done();
  11153. return true;
  11154. });
  11155. });
  11156. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11157. auto se = detail::scope_exit([&] {
  11158. svr.stop();
  11159. listen_thread.join();
  11160. ASSERT_FALSE(svr.is_running());
  11161. });
  11162. svr.wait_until_ready();
  11163. Client cli("localhost", PORT);
  11164. auto res = cli.Get("/");
  11165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11166. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11167. EXPECT_EQ("helloworld", res->body);
  11168. }
  11169. // A body set after a content provider must replace it, not be sent through it.
  11170. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11171. Server svr;
  11172. svr.set_mount_point("/", "./www");
  11173. svr.set_file_request_handler([](const Request &req, Response &res) {
  11174. if (req.path == "/dir/test.html") {
  11175. res.status = StatusCode::Forbidden_403;
  11176. res.set_content(std::string(5000, 'D'), "text/plain");
  11177. } else if (req.path == "/file") {
  11178. res.status = StatusCode::Forbidden_403;
  11179. res.body = "Denied";
  11180. }
  11181. });
  11182. auto port = svr.bind_to_any_port(HOST);
  11183. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11184. auto se = detail::scope_exit([&] {
  11185. svr.stop();
  11186. t.join();
  11187. ASSERT_FALSE(svr.is_running());
  11188. });
  11189. svr.wait_until_ready();
  11190. Client cli(HOST, port);
  11191. {
  11192. auto res = cli.Get("/dir/test.html");
  11193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11194. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11195. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11196. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11197. }
  11198. {
  11199. auto res = cli.Get("/file");
  11200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11201. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11202. EXPECT_EQ("Denied", res->body);
  11203. }
  11204. {
  11205. auto res = cli.Get("/dir/index.html");
  11206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11207. EXPECT_EQ(StatusCode::OK_200, res->status);
  11208. EXPECT_EQ(0U, res->body.find("<html>"));
  11209. }
  11210. }
  11211. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11212. Server svr;
  11213. std::vector<bool> released;
  11214. std::mutex released_mutex;
  11215. auto releaser = [&](bool success) {
  11216. std::lock_guard<std::mutex> guard(released_mutex);
  11217. released.push_back(success);
  11218. };
  11219. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11220. return sink.write(&"hello"[offset], length);
  11221. };
  11222. svr.Get("/sized", [&](const Request &, Response &res) {
  11223. res.status = StatusCode::NotFound_404;
  11224. res.set_content_provider(5, "text/plain", provider, releaser);
  11225. });
  11226. svr.Get("/chunked", [&](const Request &, Response &res) {
  11227. res.status = StatusCode::ServiceUnavailable_503;
  11228. res.set_chunked_content_provider(
  11229. "text/plain",
  11230. [](size_t, DataSink &sink) {
  11231. sink.os << "chunk";
  11232. sink.done();
  11233. return true;
  11234. },
  11235. releaser);
  11236. });
  11237. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11238. res.set_content_provider(5, "text/plain", provider, releaser);
  11239. throw std::runtime_error("after the provider");
  11240. });
  11241. svr.set_error_handler([](const Request &req, Response &res) {
  11242. // Leave the exception handler's content to it.
  11243. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11244. res.set_content(std::string(1000, 'E'), "text/html");
  11245. return Server::HandlerResponse::Handled;
  11246. });
  11247. svr.set_exception_handler(
  11248. [](const Request &, Response &res, std::exception_ptr) {
  11249. res.status = StatusCode::InternalServerError_500;
  11250. res.set_content(std::string(1000, 'X'), "text/html");
  11251. });
  11252. auto port = svr.bind_to_any_port(HOST);
  11253. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11254. auto se = detail::scope_exit([&] {
  11255. svr.stop();
  11256. t.join();
  11257. ASSERT_FALSE(svr.is_running());
  11258. });
  11259. svr.wait_until_ready();
  11260. Client cli(HOST, port);
  11261. {
  11262. auto res = cli.Get("/sized");
  11263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11264. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11265. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11266. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11267. }
  11268. {
  11269. auto res = cli.Get("/chunked");
  11270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11271. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11272. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11273. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11274. }
  11275. {
  11276. auto res = cli.Get("/throw");
  11277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11278. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11279. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11280. }
  11281. std::lock_guard<std::mutex> guard(released_mutex);
  11282. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11283. }
  11284. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11285. Server svr;
  11286. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11287. return sink.write(&"abc"[offset], length);
  11288. };
  11289. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11290. res.set_file_content("./www/dir/test.html");
  11291. res.set_content("body", "text/plain");
  11292. });
  11293. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11294. res.set_content(std::string(100, 'B'), "text/plain");
  11295. res.set_file_content("./www/dir/test.html");
  11296. });
  11297. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11298. res.set_content(std::string(100, 'B'), "text/plain");
  11299. res.set_content_provider(3, "text/plain", abc);
  11300. });
  11301. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11302. res.set_content_provider(3, "text/plain", abc);
  11303. res.set_content(std::string(100, 'B'), "text/plain");
  11304. });
  11305. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11306. res.set_content_provider(3, "text/plain", abc);
  11307. res.body = "direct";
  11308. });
  11309. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11310. res.set_file_content("./www/dir/test.html");
  11311. res.body = "direct";
  11312. });
  11313. auto port = svr.bind_to_any_port(HOST);
  11314. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11315. auto se = detail::scope_exit([&] {
  11316. svr.stop();
  11317. t.join();
  11318. ASSERT_FALSE(svr.is_running());
  11319. });
  11320. svr.wait_until_ready();
  11321. Client cli(HOST, port);
  11322. auto expect_body = [&](const char *path, const std::string &body) {
  11323. // Uncompressed, so Content-Length can be compared with the body.
  11324. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11325. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11326. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11327. EXPECT_EQ(body, res->body) << path;
  11328. EXPECT_EQ(std::to_string(body.size()),
  11329. res->get_header_value("Content-Length"))
  11330. << path;
  11331. };
  11332. expect_body("/file-then-body", "body");
  11333. expect_body("/body-then-file", "test.html");
  11334. expect_body("/body-then-provider", "abc");
  11335. expect_body("/provider-then-body", std::string(100, 'B'));
  11336. expect_body("/provider-then-direct-body", "direct");
  11337. expect_body("/file-then-direct-body", "direct");
  11338. // Ranges are checked against the body, not the dropped provider.
  11339. {
  11340. auto res = cli.Get("/provider-then-direct-body",
  11341. Headers{{make_range_header({{1, 2}})}});
  11342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11343. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11344. EXPECT_EQ("ir", res->body);
  11345. }
  11346. {
  11347. auto res = cli.Get("/file-then-direct-body",
  11348. Headers{{make_range_header({{7, 8}})}});
  11349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11350. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11351. }
  11352. }
  11353. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11354. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11355. const char *path = "./truncated_while_served.txt";
  11356. const size_t size = 32 * 1024 * 1024;
  11357. {
  11358. std::ofstream f(path, std::ios::binary);
  11359. f << std::string(size, 'x');
  11360. }
  11361. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11362. // Over TLS, where the bytes are encrypted in this process rather than
  11363. // copied by send().
  11364. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11365. svr.Get("/file", [&](const Request &, Response &res) {
  11366. res.set_file_content(path, "text/plain");
  11367. });
  11368. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11369. auto se = detail::scope_exit([&] {
  11370. svr.stop();
  11371. thread.join();
  11372. ASSERT_FALSE(svr.is_running());
  11373. });
  11374. svr.wait_until_ready();
  11375. // The file shrinks once the first bytes are in, as a rewrite in place
  11376. // would, and reading the mapping past its new end used to raise SIGBUS.
  11377. SSLClient cli(HOST, PORT);
  11378. cli.enable_server_certificate_verification(false);
  11379. size_t received = 0;
  11380. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11381. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11382. received += len;
  11383. return true;
  11384. });
  11385. EXPECT_FALSE(res);
  11386. EXPECT_LT(received, size);
  11387. }
  11388. #endif
  11389. // Forward declaration (see the base64_encode note).
  11390. namespace httplib {
  11391. namespace detail {
  11392. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11393. const std::string &content_type,
  11394. EncodingType encoding);
  11395. } // namespace detail
  11396. } // namespace httplib
  11397. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11398. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11399. ASSERT_TRUE(mm->is_open());
  11400. Response res;
  11401. detail::set_file_content_provider(res, mm, "text/html",
  11402. detail::EncodingType::None);
  11403. std::string out;
  11404. DataSink sink;
  11405. sink.write = [&](const char *d, size_t l) {
  11406. out.append(d, l);
  11407. return true;
  11408. };
  11409. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11410. EXPECT_EQ("test.html", out);
  11411. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11412. EXPECT_EQ("test.html", out);
  11413. }
  11414. TEST(LongPollingTest, ClientCloseDetection) {
  11415. Server svr;
  11416. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11417. res.set_chunked_content_provider(
  11418. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11419. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11420. sink.os << "hello";
  11421. auto count = 10;
  11422. while (count > 0 && sink.is_writable()) {
  11423. this_thread::sleep_for(chrono::milliseconds(10));
  11424. count--;
  11425. }
  11426. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11427. return true;
  11428. });
  11429. });
  11430. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11431. auto se = detail::scope_exit([&] {
  11432. svr.stop();
  11433. listen_thread.join();
  11434. ASSERT_FALSE(svr.is_running());
  11435. });
  11436. svr.wait_until_ready();
  11437. Client cli("localhost", PORT);
  11438. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11439. EXPECT_EQ("hello", string(data, data_length));
  11440. return false; // close the socket immediately.
  11441. });
  11442. ASSERT_FALSE(res);
  11443. }
  11444. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11445. Server svr;
  11446. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11447. res.set_chunked_content_provider(
  11448. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11449. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11450. sink.os << "hello";
  11451. EXPECT_TRUE(sink.os.good());
  11452. // Wait for the client to close the connection
  11453. auto count = 10;
  11454. while (count > 0 && sink.is_writable()) {
  11455. this_thread::sleep_for(chrono::milliseconds(10));
  11456. count--;
  11457. }
  11458. // After client disconnect, write repeatedly until the socket
  11459. // write actually fails (small writes may be absorbed by the
  11460. // kernel buffer)
  11461. std::string chunk(1024, 'x');
  11462. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11463. sink.os << chunk;
  11464. }
  11465. EXPECT_TRUE(sink.os.fail());
  11466. return true;
  11467. });
  11468. });
  11469. auto port = svr.bind_to_any_port("localhost");
  11470. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11471. auto se = detail::scope_exit([&] {
  11472. svr.stop();
  11473. listen_thread.join();
  11474. ASSERT_FALSE(svr.is_running());
  11475. });
  11476. svr.wait_until_ready();
  11477. Client cli("localhost", port);
  11478. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11479. EXPECT_EQ("hello", string(data, data_length));
  11480. return false; // close the socket immediately.
  11481. });
  11482. ASSERT_FALSE(res);
  11483. }
  11484. TEST(GetWithParametersTest, GetWithParameters) {
  11485. Server svr;
  11486. svr.Get("/", [&](const Request &req, Response &) {
  11487. EXPECT_EQ("world", req.get_param_value("hello"));
  11488. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11489. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11490. });
  11491. svr.Get("/params", [&](const Request &req, Response &) {
  11492. EXPECT_EQ("world", req.get_param_value("hello"));
  11493. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11494. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11495. });
  11496. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11497. EXPECT_EQ("resource-id", req.matches[1]);
  11498. EXPECT_EQ("foo", req.get_param_value("param1"));
  11499. EXPECT_EQ("bar", req.get_param_value("param2"));
  11500. });
  11501. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11502. EXPECT_EQ("user-id", req.path_params.at("id"));
  11503. EXPECT_EQ("foo", req.get_param_value("param1"));
  11504. EXPECT_EQ("bar", req.get_param_value("param2"));
  11505. });
  11506. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11507. auto se = detail::scope_exit([&] {
  11508. svr.stop();
  11509. listen_thread.join();
  11510. ASSERT_FALSE(svr.is_running());
  11511. });
  11512. svr.wait_until_ready();
  11513. {
  11514. Client cli(HOST, PORT);
  11515. Params params;
  11516. params.emplace("hello", "world");
  11517. params.emplace("hello2", "world2");
  11518. params.emplace("hello3", "world3");
  11519. auto res = cli.Get("/", params, Headers{});
  11520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11521. EXPECT_EQ(StatusCode::OK_200, res->status);
  11522. }
  11523. {
  11524. Client cli(HOST, PORT);
  11525. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11527. EXPECT_EQ(StatusCode::OK_200, res->status);
  11528. }
  11529. {
  11530. Client cli(HOST, PORT);
  11531. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11533. EXPECT_EQ(StatusCode::OK_200, res->status);
  11534. }
  11535. {
  11536. Client cli(HOST, PORT);
  11537. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11539. EXPECT_EQ(StatusCode::OK_200, res->status);
  11540. }
  11541. }
  11542. TEST(GetWithParametersTest, GetWithParameters2) {
  11543. Server svr;
  11544. svr.Get("/", [&](const Request &req, Response &res) {
  11545. auto text = req.get_param_value("hello");
  11546. res.set_content(text, "text/plain");
  11547. });
  11548. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11549. auto se = detail::scope_exit([&] {
  11550. svr.stop();
  11551. listen_thread.join();
  11552. ASSERT_FALSE(svr.is_running());
  11553. });
  11554. svr.wait_until_ready();
  11555. Client cli("localhost", PORT);
  11556. Params params;
  11557. params.emplace("hello", "world");
  11558. std::string body;
  11559. auto res = cli.Get("/", params, Headers{},
  11560. [&](const char *data, size_t data_length) {
  11561. body.append(data, data_length);
  11562. return true;
  11563. });
  11564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11565. EXPECT_EQ(StatusCode::OK_200, res->status);
  11566. EXPECT_EQ("world", body);
  11567. }
  11568. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11569. Server svr;
  11570. svr.Get("/search", [&](const Request &req, Response &res) {
  11571. auto q = req.get_param_value("q");
  11572. res.set_content(q, "text/plain");
  11573. });
  11574. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11575. auto se = detail::scope_exit([&] {
  11576. svr.stop();
  11577. listen_thread.join();
  11578. ASSERT_FALSE(svr.is_running());
  11579. });
  11580. svr.wait_until_ready();
  11581. Client cli("localhost", PORT);
  11582. // Verify that Get(path, params) works without requiring Headers argument
  11583. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11585. EXPECT_EQ(StatusCode::OK_200, res->status);
  11586. EXPECT_EQ("cpp-httplib", res->body);
  11587. }
  11588. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11589. auto host = "httpbingo.org";
  11590. auto path = std::string{"/range/32"};
  11591. #ifdef CPPHTTPLIB_SSL_ENABLED
  11592. SSLClient cli(host);
  11593. #else
  11594. Client cli(host);
  11595. #endif
  11596. cli.set_default_headers({make_range_header({{1, 10}})});
  11597. cli.set_connection_timeout(5);
  11598. {
  11599. auto res = cli.Get(path);
  11600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11601. EXPECT_EQ("bcdefghijk", res->body);
  11602. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11603. }
  11604. {
  11605. auto res = cli.Get(path);
  11606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11607. EXPECT_EQ("bcdefghijk", res->body);
  11608. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11609. }
  11610. }
  11611. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11612. Server svr;
  11613. svr.set_default_headers({{"Hello", "World"}});
  11614. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11615. res.set_content("ok", "text/plain");
  11616. });
  11617. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11618. auto se = detail::scope_exit([&] {
  11619. svr.stop();
  11620. listen_thread.join();
  11621. ASSERT_FALSE(svr.is_running());
  11622. });
  11623. svr.wait_until_ready();
  11624. Client cli("localhost", PORT);
  11625. auto res = cli.Get("/");
  11626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11627. EXPECT_EQ(StatusCode::OK_200, res->status);
  11628. EXPECT_EQ("ok", res->body);
  11629. EXPECT_EQ("World", res->get_header_value("Hello"));
  11630. }
  11631. #ifdef CPPHTTPLIB_SSL_ENABLED
  11632. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11633. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11634. ASSERT_TRUE(svr.is_valid());
  11635. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11636. std::this_thread::sleep_for(std::chrono::seconds(2));
  11637. res.set_content("a", "text/plain");
  11638. });
  11639. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11640. res.set_content("b", "text/plain");
  11641. });
  11642. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11643. auto se = detail::scope_exit([&] {
  11644. svr.stop();
  11645. listen_thread.join();
  11646. ASSERT_FALSE(svr.is_running());
  11647. });
  11648. svr.wait_until_ready();
  11649. SSLClient cli("localhost", PORT);
  11650. cli.enable_server_certificate_verification(false);
  11651. cli.set_keep_alive(true);
  11652. cli.set_read_timeout(std::chrono::seconds(1));
  11653. auto resa = cli.Get("/a");
  11654. ASSERT_TRUE(!resa);
  11655. EXPECT_EQ(Error::Read, resa.error());
  11656. auto resb = cli.Get("/b");
  11657. ASSERT_TRUE(resb);
  11658. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11659. EXPECT_EQ("b", resb->body);
  11660. }
  11661. // Closing an idle keep-alive connection sends close_notify and returns. The
  11662. // server must not wait for the client's close_notify: an idle client never
  11663. // sends one, so the worker would be held until the read timeout expires, and
  11664. // stop() would wait for it.
  11665. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11666. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11667. ASSERT_TRUE(svr.is_valid());
  11668. svr.set_keep_alive_timeout(1);
  11669. svr.set_read_timeout(10, 0);
  11670. svr.Get("/", [](const Request &, Response &res) {
  11671. res.set_content("ok", "text/plain");
  11672. });
  11673. auto port = svr.bind_to_any_port(HOST);
  11674. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11675. auto se = detail::scope_exit([&] {
  11676. if (listen_thread.joinable()) {
  11677. svr.stop();
  11678. listen_thread.join();
  11679. }
  11680. });
  11681. svr.wait_until_ready();
  11682. SSLClient cli(HOST, port);
  11683. cli.enable_server_certificate_verification(false);
  11684. cli.set_keep_alive(true);
  11685. auto res = cli.Get("/");
  11686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11687. EXPECT_EQ(StatusCode::OK_200, res->status);
  11688. // Stay idle past the keep-alive timeout so the server closes the connection.
  11689. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11690. auto start = std::chrono::steady_clock::now();
  11691. svr.stop();
  11692. listen_thread.join();
  11693. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11694. std::chrono::steady_clock::now() - start)
  11695. .count();
  11696. EXPECT_LT(elapsed, 3000);
  11697. }
  11698. #endif
  11699. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11700. protected:
  11701. ServerTestWithAI_PASSIVE()
  11702. : cli_(HOST, PORT)
  11703. #ifdef CPPHTTPLIB_SSL_ENABLED
  11704. ,
  11705. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11706. #endif
  11707. {
  11708. #ifdef CPPHTTPLIB_SSL_ENABLED
  11709. cli_.enable_server_certificate_verification(false);
  11710. #endif
  11711. }
  11712. virtual void SetUp() {
  11713. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11714. res.set_content("Hello World!", "text/plain");
  11715. });
  11716. t_ = thread(
  11717. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11718. svr_.wait_until_ready();
  11719. }
  11720. virtual void TearDown() {
  11721. svr_.stop();
  11722. t_.join();
  11723. }
  11724. #ifdef CPPHTTPLIB_SSL_ENABLED
  11725. SSLClient cli_;
  11726. SSLServer svr_;
  11727. #else
  11728. Client cli_;
  11729. Server svr_;
  11730. #endif
  11731. thread t_;
  11732. };
  11733. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11734. auto res = cli_.Get("/hi");
  11735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11736. EXPECT_EQ(StatusCode::OK_200, res->status);
  11737. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11738. EXPECT_EQ("Hello World!", res->body);
  11739. }
  11740. class ServerUpDownTest : public ::testing::Test {
  11741. protected:
  11742. ServerUpDownTest() : cli_(HOST, PORT) {}
  11743. virtual void SetUp() {
  11744. t_ = thread([&]() {
  11745. svr_.bind_to_any_port(HOST);
  11746. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11747. ASSERT_TRUE(svr_.listen_after_bind());
  11748. });
  11749. svr_.wait_until_ready();
  11750. }
  11751. virtual void TearDown() {
  11752. svr_.stop();
  11753. t_.join();
  11754. }
  11755. Client cli_;
  11756. Server svr_;
  11757. thread t_;
  11758. };
  11759. TEST_F(ServerUpDownTest, QuickStartStop) {
  11760. // Should not crash, especially when run with
  11761. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11762. }
  11763. class PayloadMaxLengthTest : public ::testing::Test {
  11764. protected:
  11765. PayloadMaxLengthTest()
  11766. : cli_(HOST, PORT)
  11767. #ifdef CPPHTTPLIB_SSL_ENABLED
  11768. ,
  11769. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11770. #endif
  11771. {
  11772. #ifdef CPPHTTPLIB_SSL_ENABLED
  11773. cli_.enable_server_certificate_verification(false);
  11774. #endif
  11775. }
  11776. virtual void SetUp() {
  11777. svr_.set_payload_max_length(8);
  11778. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11779. res.set_content("test", "text/plain");
  11780. });
  11781. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11782. svr_.wait_until_ready();
  11783. }
  11784. virtual void TearDown() {
  11785. svr_.stop();
  11786. t_.join();
  11787. }
  11788. #ifdef CPPHTTPLIB_SSL_ENABLED
  11789. SSLClient cli_;
  11790. SSLServer svr_;
  11791. #else
  11792. Client cli_;
  11793. Server svr_;
  11794. #endif
  11795. thread t_;
  11796. };
  11797. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11798. auto res = cli_.Post("/test", "123456789", "text/plain");
  11799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11800. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11801. res = cli_.Post("/test", "12345678", "text/plain");
  11802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11803. EXPECT_EQ(StatusCode::OK_200, res->status);
  11804. }
  11805. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11806. // Test chunked encoding with payload exceeding the 8-byte limit
  11807. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11808. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11810. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11811. }
  11812. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11813. // Test chunked encoding with payload within the 8-byte limit
  11814. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11815. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11817. EXPECT_EQ(StatusCode::OK_200, res->status);
  11818. }
  11819. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11820. // Test using send_request to send chunked data exceeding payload limit
  11821. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11822. "Host: " +
  11823. std::string(HOST) + ":" + std::to_string(PORT) +
  11824. "\r\n"
  11825. "Transfer-Encoding: chunked\r\n"
  11826. "Connection: close\r\n"
  11827. "\r\n"
  11828. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11829. "0123456789\r\n"
  11830. "0\r\n" // End chunk
  11831. "\r\n";
  11832. std::string response;
  11833. bool result = send_request(1, chunked_request, &response);
  11834. if (!result) {
  11835. // If send_request fails, it might be because the server closed the
  11836. // connection due to payload limit enforcement, which is acceptable
  11837. SUCCEED()
  11838. << "Server rejected oversized chunked request (connection closed)";
  11839. } else {
  11840. // If we got a response, check if it's an error response or connection was
  11841. // closed early Short response length indicates connection was closed due to
  11842. // payload limit
  11843. if (response.length() <= 10) {
  11844. SUCCEED() << "Server closed connection for oversized chunked request";
  11845. } else {
  11846. // Check for error status codes
  11847. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11848. response.find("Payload Too Large") != std::string::npos ||
  11849. response.find("400") != std::string::npos);
  11850. }
  11851. }
  11852. }
  11853. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11854. // Test request without Content-Length header exceeding payload limit
  11855. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11856. "Host: " +
  11857. std::string(HOST) + ":" +
  11858. std::to_string(PORT) +
  11859. "\r\n"
  11860. "Connection: close\r\n"
  11861. "\r\n";
  11862. // Add payload exceeding the 8-byte limit
  11863. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11864. request_without_content_length += large_payload;
  11865. std::string response;
  11866. bool result = send_request(1, request_without_content_length, &response);
  11867. if (!result) {
  11868. // If send_request fails, server likely closed connection due to payload
  11869. // limit
  11870. SUCCEED() << "Server rejected oversized request without Content-Length "
  11871. "(connection closed)";
  11872. } else {
  11873. // Check if server responded with error or closed connection early
  11874. if (response.length() <= 10) {
  11875. SUCCEED() << "Server closed connection for oversized request without "
  11876. "Content-Length";
  11877. } else {
  11878. // Check for error status codes
  11879. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11880. response.find("Payload Too Large") != std::string::npos ||
  11881. response.find("400") != std::string::npos);
  11882. }
  11883. }
  11884. }
  11885. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11886. // Test request without Content-Length header within payload limit
  11887. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11888. "Host: " +
  11889. std::string(HOST) + ":" +
  11890. std::to_string(PORT) +
  11891. "\r\n"
  11892. "Connection: close\r\n"
  11893. "\r\n";
  11894. // Add payload within the 8-byte limit
  11895. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11896. request_without_content_length += small_payload;
  11897. std::string response;
  11898. bool result = send_request(1, request_without_content_length, &response);
  11899. // For requests without Content-Length, the server may have different behavior
  11900. // The key is that it should not reject due to payload limit for small
  11901. // payloads
  11902. if (result) {
  11903. // Check for any HTTP response (success or error, but not connection closed)
  11904. if (response.length() > 10) {
  11905. SUCCEED()
  11906. << "Server processed request without Content-Length within limit";
  11907. } else {
  11908. // Short response might indicate connection closed, which is acceptable
  11909. SUCCEED() << "Server closed connection for request without "
  11910. "Content-Length (acceptable behavior)";
  11911. }
  11912. } else {
  11913. // Connection failure might be due to protocol requirements
  11914. SUCCEED() << "Connection issue with request without Content-Length "
  11915. "(environment-specific)";
  11916. }
  11917. }
  11918. class LargePayloadMaxLengthTest : public ::testing::Test {
  11919. protected:
  11920. LargePayloadMaxLengthTest()
  11921. : cli_(HOST, PORT)
  11922. #ifdef CPPHTTPLIB_SSL_ENABLED
  11923. ,
  11924. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11925. #endif
  11926. {
  11927. #ifdef CPPHTTPLIB_SSL_ENABLED
  11928. cli_.enable_server_certificate_verification(false);
  11929. #endif
  11930. }
  11931. virtual void SetUp() {
  11932. // Set 10MB payload limit
  11933. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11934. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11935. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11936. res.set_content("Large payload test", "text/plain");
  11937. });
  11938. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11939. svr_.wait_until_ready();
  11940. }
  11941. virtual void TearDown() {
  11942. svr_.stop();
  11943. t_.join();
  11944. }
  11945. #ifdef CPPHTTPLIB_SSL_ENABLED
  11946. SSLClient cli_;
  11947. SSLServer svr_;
  11948. #else
  11949. Client cli_;
  11950. Server svr_;
  11951. #endif
  11952. thread t_;
  11953. };
  11954. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11955. // Test chunked encoding with payload within 10MB limit
  11956. std::string medium_payload(5 * 1024 * 1024,
  11957. 'A'); // 5MB payload, within 10MB limit
  11958. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11960. EXPECT_EQ(StatusCode::OK_200, res->status);
  11961. }
  11962. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11963. // Test chunked encoding with payload exceeding 10MB limit
  11964. std::string large_payload(12 * 1024 * 1024,
  11965. 'B'); // 12MB payload, exceeds 10MB limit
  11966. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11967. // Server may either return 413 or close the connection
  11968. if (res) {
  11969. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11970. } else {
  11971. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11972. }
  11973. }
  11974. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11975. // Test request without Content-Length header within 10MB limit
  11976. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11977. "Host: " +
  11978. std::string(HOST) + ":" +
  11979. std::to_string(PORT) +
  11980. "\r\n"
  11981. "Connection: close\r\n"
  11982. "\r\n";
  11983. // Add 1MB payload (within 10MB limit)
  11984. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11985. request_without_content_length += medium_payload;
  11986. std::string response;
  11987. bool result = send_request(5, request_without_content_length, &response);
  11988. if (result) {
  11989. // Should get a proper HTTP response for payloads within limit
  11990. if (response.length() > 10) {
  11991. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11992. "10MB limit";
  11993. } else {
  11994. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11995. "Content-Length)";
  11996. }
  11997. } else {
  11998. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11999. }
  12000. }
  12001. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  12002. // Test request without Content-Length header exceeding 10MB limit
  12003. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12004. "Host: " +
  12005. std::string(HOST) + ":" +
  12006. std::to_string(PORT) +
  12007. "\r\n"
  12008. "Connection: close\r\n"
  12009. "\r\n";
  12010. // Add 12MB payload (exceeds 10MB limit)
  12011. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  12012. request_without_content_length += large_payload;
  12013. std::string response;
  12014. bool result = send_request(10, request_without_content_length, &response);
  12015. if (!result) {
  12016. // Server should close connection due to payload limit
  12017. SUCCEED() << "Server rejected 12MB request without Content-Length "
  12018. "(connection closed)";
  12019. } else {
  12020. // Check for error response
  12021. if (response.length() <= 10) {
  12022. SUCCEED()
  12023. << "Server closed connection for 12MB request exceeding 10MB limit";
  12024. } else {
  12025. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12026. response.find("Payload Too Large") != std::string::npos ||
  12027. response.find("400") != std::string::npos);
  12028. }
  12029. }
  12030. }
  12031. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12032. Server svr;
  12033. svr.Get("/", [](const Request &, Response &res) {
  12034. // Claims far more than it sends, then drops the connection.
  12035. res.set_content_provider(size_t(1) << 41, "text/plain",
  12036. [](size_t, size_t, DataSink &sink) {
  12037. sink.write("abc", 3);
  12038. return false;
  12039. });
  12040. });
  12041. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12042. auto se = detail::scope_exit([&] {
  12043. svr.stop();
  12044. thread.join();
  12045. ASSERT_FALSE(svr.is_running());
  12046. });
  12047. svr.wait_until_ready();
  12048. Client cli(HOST, PORT);
  12049. cli.set_payload_max_length(0);
  12050. EXPECT_FALSE(cli.Get("/"));
  12051. }
  12052. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12053. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12054. // path.
  12055. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12056. Server svr;
  12057. const size_t LIMIT = 64 * 1024; // 64KB
  12058. svr.set_payload_max_length(LIMIT);
  12059. size_t total = 0;
  12060. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12061. const ContentReader &content_reader) {
  12062. content_reader([&](const char * /*data*/, size_t len) {
  12063. total += len;
  12064. return true;
  12065. });
  12066. res.status = 200;
  12067. res.set_content("stream_ok", "text/plain");
  12068. });
  12069. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12070. auto se = detail::scope_exit([&] {
  12071. svr.stop();
  12072. thread.join();
  12073. ASSERT_FALSE(svr.is_running());
  12074. });
  12075. svr.wait_until_ready();
  12076. // Prepare 256KB raw data and gzip-compress it
  12077. std::string raw(256 * 1024, 'A');
  12078. std::string gz;
  12079. {
  12080. z_stream zs{};
  12081. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12082. Z_DEFAULT_STRATEGY);
  12083. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12084. zs.avail_in = static_cast<uInt>(raw.size());
  12085. char outbuf[4096];
  12086. int ret;
  12087. do {
  12088. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12089. zs.avail_out = sizeof(outbuf);
  12090. ret = deflate(&zs, Z_FINISH);
  12091. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12092. } while (ret != Z_STREAM_END);
  12093. deflateEnd(&zs);
  12094. }
  12095. Client cli(HOST, PORT);
  12096. cli.set_connection_timeout(std::chrono::seconds(5));
  12097. Headers headers = {{"Content-Encoding", "gzip"}};
  12098. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12099. "application/octet-stream");
  12100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12101. // Server must reject oversized decompressed payloads with 413.
  12102. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12103. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12104. EXPECT_LE(total, LIMIT);
  12105. }
  12106. #ifndef CPPHTTPLIB_SSL_ENABLED
  12107. // For a request with neither Content-Length nor Transfer-Encoding, the
  12108. // non-SSL raw-socket fallback in read_content_core() used to hand the
  12109. // compressed wire bytes straight to the ContentReader without ever routing
  12110. // them through the decompressor, so payload_max_length_ only bounded the
  12111. // compressed size on the wire, not the decompressed size.
  12112. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  12113. Server svr;
  12114. const size_t LIMIT = 64 * 1024; // 64KB
  12115. svr.set_payload_max_length(LIMIT);
  12116. size_t total = 0;
  12117. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12118. const ContentReader &content_reader) {
  12119. content_reader([&](const char * /*data*/, size_t len) {
  12120. total += len;
  12121. return true;
  12122. });
  12123. res.status = 200;
  12124. res.set_content("stream_ok", "text/plain");
  12125. });
  12126. auto port = svr.bind_to_any_port(HOST);
  12127. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12128. auto se = detail::scope_exit([&] {
  12129. svr.stop();
  12130. thread.join();
  12131. ASSERT_FALSE(svr.is_running());
  12132. });
  12133. svr.wait_until_ready();
  12134. // Prepare 256KB raw data and gzip-compress it, same payload as the
  12135. // StreamingGzipDecompression test above.
  12136. std::string raw(256 * 1024, 'A');
  12137. std::string gz;
  12138. {
  12139. httplib::detail::gzip_compressor compressor;
  12140. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  12141. [&](const char *chunk, size_t len) {
  12142. gz.append(chunk, len);
  12143. return true;
  12144. });
  12145. ASSERT_TRUE(result);
  12146. }
  12147. // Send the gzip body over raw TCP with neither Content-Length nor
  12148. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  12149. // kicks in.
  12150. std::string req = "POST /stream HTTP/1.1\r\n"
  12151. "Host: " +
  12152. std::string(HOST) + ":" + std::to_string(port) +
  12153. "\r\n"
  12154. "Content-Encoding: gzip\r\n"
  12155. "Connection: close\r\n"
  12156. "\r\n" +
  12157. gz;
  12158. std::string response;
  12159. ASSERT_TRUE(send_request(5, req, &response, port));
  12160. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12161. EXPECT_LE(total, LIMIT);
  12162. }
  12163. #endif
  12164. #endif
  12165. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12166. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12167. // the payload must be passed through untouched instead of being rejected.
  12168. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12169. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12170. Server svr;
  12171. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12172. res.set_content(body, "image/jpeg");
  12173. res.set_header("Content-Encoding", "UTF-8");
  12174. });
  12175. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12176. res.set_content(body, "image/jpeg");
  12177. res.set_header("Content-Encoding", "identity");
  12178. });
  12179. svr.Post("/echo", [](const Request &req, Response &res) {
  12180. res.set_content(req.body, "image/jpeg");
  12181. });
  12182. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12183. auto se = detail::scope_exit([&] {
  12184. svr.stop();
  12185. t.join();
  12186. ASSERT_FALSE(svr.is_running());
  12187. });
  12188. svr.wait_until_ready();
  12189. Client cli(HOST, PORT);
  12190. {
  12191. auto res = cli.Get("/image");
  12192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12193. EXPECT_EQ(StatusCode::OK_200, res->status);
  12194. EXPECT_EQ(body, res->body);
  12195. }
  12196. {
  12197. auto res = cli.Get("/identity");
  12198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12199. EXPECT_EQ(StatusCode::OK_200, res->status);
  12200. EXPECT_EQ(body, res->body);
  12201. }
  12202. {
  12203. // The same applies to a request body reaching the server.
  12204. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12205. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12207. EXPECT_EQ(StatusCode::OK_200, res->status);
  12208. EXPECT_EQ(body, res->body);
  12209. }
  12210. }
  12211. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12212. // gzip-encoded response even when the build has no zlib support.
  12213. static const char GZIPPED_HELLO_WORLD[] = {
  12214. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12215. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12216. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12217. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12218. // A content coding is a whole token, not something the field value merely
  12219. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12220. // as "fibre" look like Brotli, and turned a multi-coding value like
  12221. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12222. // it was never meant to see.
  12223. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12224. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12225. Server svr;
  12226. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12227. res.set_content(body, "image/jpeg");
  12228. res.set_header("Content-Encoding", "fibre");
  12229. });
  12230. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12231. res.set_content(body, "image/jpeg");
  12232. res.set_header("Content-Encoding", "gzip, br");
  12233. });
  12234. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12235. res.set_content(body, "image/jpeg");
  12236. res.set_header("Content-Encoding", "x-zstd-ish");
  12237. });
  12238. auto port = svr.bind_to_any_port(HOST);
  12239. thread t = thread([&]() { svr.listen_after_bind(); });
  12240. auto se = detail::scope_exit([&] {
  12241. svr.stop();
  12242. t.join();
  12243. ASSERT_FALSE(svr.is_running());
  12244. });
  12245. svr.wait_until_ready();
  12246. Client cli(HOST, port);
  12247. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12248. auto res = cli.Get(path);
  12249. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12250. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12251. // Not a coding we recognize, so the payload comes back untouched
  12252. EXPECT_EQ(body, res->body) << path;
  12253. }
  12254. }
  12255. // A content coding cpp-httplib recognizes but was not built with must be
  12256. // reported as such. Handing the still-compressed payload back to the caller
  12257. // would silently corrupt it.
  12258. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12259. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12260. Server svr;
  12261. // "image/jpeg" keeps the server from applying a content coding of its own,
  12262. // so the hand-crafted Content-Encoding below survives.
  12263. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12264. res.set_content(gzipped, "image/jpeg");
  12265. res.set_header("Content-Encoding", "gzip");
  12266. });
  12267. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12268. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12269. res.set_content(gzipped, "image/jpeg");
  12270. res.set_header("Content-Encoding", "GZIP");
  12271. });
  12272. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12273. auto se = detail::scope_exit([&] {
  12274. svr.stop();
  12275. t.join();
  12276. ASSERT_FALSE(svr.is_running());
  12277. });
  12278. svr.wait_until_ready();
  12279. Client cli(HOST, PORT);
  12280. {
  12281. auto res = cli.Get("/gzipped");
  12282. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12284. EXPECT_EQ("Hello World!", res->body);
  12285. #else
  12286. ASSERT_FALSE(res);
  12287. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12288. #endif
  12289. }
  12290. {
  12291. // open_stream() must behave the same way.
  12292. auto handle = cli.open_stream("GET", "/gzipped");
  12293. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12294. ASSERT_TRUE(handle.is_valid());
  12295. std::string received;
  12296. char buf[256];
  12297. ssize_t n;
  12298. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12299. received.append(buf, static_cast<size_t>(n));
  12300. }
  12301. EXPECT_EQ("Hello World!", received);
  12302. #else
  12303. EXPECT_FALSE(handle.is_valid());
  12304. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12305. #endif
  12306. }
  12307. {
  12308. // A differently-cased coding must not be mistaken for an unknown one, or
  12309. // the body would be handed back still compressed.
  12310. auto res = cli.Get("/gzipped-uppercase");
  12311. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12313. EXPECT_EQ("Hello World!", res->body);
  12314. #else
  12315. ASSERT_FALSE(res);
  12316. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12317. #endif
  12318. }
  12319. }
  12320. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12321. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12322. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12323. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12324. // body a second time and appending a second Content-Encoding field line, so
  12325. // clients that decode one coding per listed value handed back raw gzip bytes.
  12326. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12327. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12328. Server svr;
  12329. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12330. // keeps the server from applying a coding of its own.
  12331. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12332. res.set_content(gzipped, "text/plain");
  12333. res.set_header("Content-Encoding", "gzip");
  12334. });
  12335. auto port = svr.bind_to_any_port(HOST);
  12336. thread t = thread([&]() { svr.listen_after_bind(); });
  12337. auto se = detail::scope_exit([&] {
  12338. svr.stop();
  12339. t.join();
  12340. ASSERT_FALSE(svr.is_running());
  12341. });
  12342. svr.wait_until_ready();
  12343. Client cli(HOST, port);
  12344. Headers headers = {{"Accept-Encoding", "gzip"}};
  12345. auto res = cli.Get("/pre-gzipped", headers);
  12346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12347. EXPECT_EQ(StatusCode::OK_200, res->status);
  12348. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12349. EXPECT_EQ("Hello World!", res->body);
  12350. }
  12351. // A chunked provider settles its coding where the headers are written and
  12352. // reuses it at write time. Both ends of that have to hold: a handler's own
  12353. // Content-Encoding suppresses the coding, and a response without one is still
  12354. // compressed as it always was.
  12355. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12356. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12357. const std::string plain = "Hello World! Hello World! Hello World!";
  12358. Server svr;
  12359. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12360. res.set_header("Content-Encoding", "gzip");
  12361. res.set_chunked_content_provider(
  12362. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12363. sink.write(gzipped.data(), gzipped.size());
  12364. sink.done();
  12365. return true;
  12366. });
  12367. });
  12368. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12369. res.set_chunked_content_provider(
  12370. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12371. sink.write(plain.data(), plain.size());
  12372. sink.done();
  12373. return true;
  12374. });
  12375. });
  12376. auto port = svr.bind_to_any_port(HOST);
  12377. thread t = thread([&]() { svr.listen_after_bind(); });
  12378. auto se = detail::scope_exit([&] {
  12379. svr.stop();
  12380. t.join();
  12381. ASSERT_FALSE(svr.is_running());
  12382. });
  12383. svr.wait_until_ready();
  12384. Client cli(HOST, port);
  12385. Headers headers = {{"Accept-Encoding", "gzip"}};
  12386. {
  12387. auto res = cli.Get("/pre-gzipped", headers);
  12388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12389. EXPECT_EQ(StatusCode::OK_200, res->status);
  12390. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12391. EXPECT_EQ("Hello World!", res->body);
  12392. }
  12393. {
  12394. auto res = cli.Get("/negotiated", headers);
  12395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12396. EXPECT_EQ(StatusCode::OK_200, res->status);
  12397. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12398. EXPECT_EQ(plain, res->body);
  12399. }
  12400. }
  12401. #endif
  12402. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12403. // the same message as the comma-joined one, so both have to be read the same
  12404. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12405. // single gzip coding, and a body the sender says was encoded twice was handed
  12406. // back after one pass, still compressed but presented as decoded.
  12407. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12408. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12409. Server svr;
  12410. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12411. res.set_content(body, "image/jpeg");
  12412. res.headers.emplace("Content-Encoding", "gzip");
  12413. res.headers.emplace("Content-Encoding", "gzip");
  12414. });
  12415. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12416. res.set_content(body, "image/jpeg");
  12417. res.set_header("Content-Encoding", "gzip, gzip");
  12418. });
  12419. auto port = svr.bind_to_any_port(HOST);
  12420. thread t = thread([&]() { svr.listen_after_bind(); });
  12421. auto se = detail::scope_exit([&] {
  12422. svr.stop();
  12423. t.join();
  12424. ASSERT_FALSE(svr.is_running());
  12425. });
  12426. svr.wait_until_ready();
  12427. Client cli(HOST, port);
  12428. // Two codings is not something cpp-httplib decodes, so both representations
  12429. // take the pass-through path rather than one of them being gunzipped once.
  12430. for (const char *path : {"/split", "/joined"}) {
  12431. auto res = cli.Get(path);
  12432. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12433. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12434. EXPECT_EQ(body, res->body) << path;
  12435. }
  12436. }
  12437. // Regression test for DoS vulnerability: a malicious server sending a response
  12438. // without Content-Length header must not cause unbounded memory consumption on
  12439. // the client side. The client should stop reading after a reasonable limit,
  12440. // similar to the server-side set_payload_max_length protection.
  12441. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12442. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12443. #ifndef _WIN32
  12444. signal(SIGPIPE, SIG_IGN);
  12445. #endif
  12446. auto server_thread = std::thread([] {
  12447. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12448. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12449. default_socket_options(srv);
  12450. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12451. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12452. sockaddr_in addr{};
  12453. addr.sin_family = AF_INET;
  12454. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12455. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12456. int opt = 1;
  12457. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12458. #ifdef _WIN32
  12459. reinterpret_cast<const char *>(&opt),
  12460. #else
  12461. &opt,
  12462. #endif
  12463. sizeof(opt));
  12464. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12465. ::listen(srv, 1);
  12466. sockaddr_in cli_addr{};
  12467. socklen_t cli_len = sizeof(cli_addr);
  12468. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12469. if (cli != INVALID_SOCKET) {
  12470. char buf[4096];
  12471. ::recv(cli, buf, sizeof(buf), 0);
  12472. // Malicious response: no Content-Length, no chunked encoding
  12473. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12474. "Connection: close\r\n"
  12475. "\r\n";
  12476. ::send(cli,
  12477. #ifdef _WIN32
  12478. static_cast<const char *>(response_header.c_str()),
  12479. static_cast<int>(response_header.size()),
  12480. #else
  12481. response_header.c_str(), response_header.size(),
  12482. #endif
  12483. 0);
  12484. // Send 10MB of data
  12485. std::string chunk(64 * 1024, 'A');
  12486. size_t total_sent = 0;
  12487. while (total_sent < MALICIOUS_DATA_SIZE) {
  12488. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12489. auto sent = ::send(cli,
  12490. #ifdef _WIN32
  12491. static_cast<const char *>(chunk.c_str()),
  12492. static_cast<int>(to_send),
  12493. #else
  12494. chunk.c_str(), to_send,
  12495. #endif
  12496. 0);
  12497. if (sent <= 0) break;
  12498. total_sent += static_cast<size_t>(sent);
  12499. }
  12500. detail::close_socket(cli);
  12501. }
  12502. detail::close_socket(srv);
  12503. });
  12504. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12505. size_t total_read = 0;
  12506. {
  12507. Client cli("127.0.0.1", PORT + 2);
  12508. cli.set_read_timeout(5, 0);
  12509. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12510. auto stream = cli.open_stream("GET", "/malicious");
  12511. ASSERT_TRUE(stream.is_valid());
  12512. char buffer[64 * 1024];
  12513. ssize_t n;
  12514. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12515. total_read += static_cast<size_t>(n);
  12516. }
  12517. } // StreamHandle and Client destroyed here, closing the socket
  12518. server_thread.join();
  12519. // With set_payload_max_length, the client must stop reading before consuming
  12520. // all 10MB. The read loop should be cut off at or near the configured limit.
  12521. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12522. << "Client read " << total_read << " bytes, exceeding the configured "
  12523. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12524. }
  12525. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12526. // the entire response body without truncation.
  12527. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12528. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12529. #ifndef _WIN32
  12530. signal(SIGPIPE, SIG_IGN);
  12531. #endif
  12532. auto server_thread = std::thread([] {
  12533. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12534. default_socket_options(srv);
  12535. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12536. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12537. sockaddr_in addr{};
  12538. addr.sin_family = AF_INET;
  12539. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12540. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12541. int opt = 1;
  12542. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12543. #ifdef _WIN32
  12544. reinterpret_cast<const char *>(&opt),
  12545. #else
  12546. &opt,
  12547. #endif
  12548. sizeof(opt));
  12549. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12550. ::listen(srv, 1);
  12551. sockaddr_in cli_addr{};
  12552. socklen_t cli_len = sizeof(cli_addr);
  12553. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12554. if (cli != INVALID_SOCKET) {
  12555. char buf[4096];
  12556. ::recv(cli, buf, sizeof(buf), 0);
  12557. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12558. "Connection: close\r\n"
  12559. "\r\n";
  12560. ::send(cli,
  12561. #ifdef _WIN32
  12562. static_cast<const char *>(response_header.c_str()),
  12563. static_cast<int>(response_header.size()),
  12564. #else
  12565. response_header.c_str(), response_header.size(),
  12566. #endif
  12567. 0);
  12568. std::string chunk(64 * 1024, 'A');
  12569. size_t total_sent = 0;
  12570. while (total_sent < DATA_SIZE) {
  12571. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12572. auto sent = ::send(cli,
  12573. #ifdef _WIN32
  12574. static_cast<const char *>(chunk.c_str()),
  12575. static_cast<int>(to_send),
  12576. #else
  12577. chunk.c_str(), to_send,
  12578. #endif
  12579. 0);
  12580. if (sent <= 0) break;
  12581. total_sent += static_cast<size_t>(sent);
  12582. }
  12583. #ifdef _WIN32
  12584. ::shutdown(cli, SD_SEND);
  12585. #else
  12586. ::shutdown(cli, SHUT_WR);
  12587. #endif
  12588. // Drain until the client closes its end, ensuring all data is delivered
  12589. char drain[1024];
  12590. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12591. detail::close_socket(cli);
  12592. }
  12593. detail::close_socket(srv);
  12594. });
  12595. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12596. size_t total_read = 0;
  12597. {
  12598. Client cli("127.0.0.1", PORT + 2);
  12599. cli.set_read_timeout(5, 0);
  12600. cli.set_payload_max_length(0); // 0 means no limit
  12601. auto stream = cli.open_stream("GET", "/data");
  12602. ASSERT_TRUE(stream.is_valid());
  12603. char buffer[64 * 1024];
  12604. ssize_t n;
  12605. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12606. total_read += static_cast<size_t>(n);
  12607. }
  12608. }
  12609. server_thread.join();
  12610. EXPECT_EQ(total_read, DATA_SIZE)
  12611. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12612. << " bytes without truncation, but only read " << total_read << " bytes.";
  12613. }
  12614. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12615. // enormous Content-Length must not cause the client to pre-allocate a huge
  12616. // response body buffer. The reservation is capped at payload_max_length_, and
  12617. // the read itself fails when the body exceeds the limit.
  12618. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12619. #ifndef _WIN32
  12620. signal(SIGPIPE, SIG_IGN);
  12621. #endif
  12622. auto server_thread = std::thread([] {
  12623. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12624. default_socket_options(srv);
  12625. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12626. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12627. sockaddr_in addr{};
  12628. addr.sin_family = AF_INET;
  12629. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12630. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12631. int opt = 1;
  12632. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12633. #ifdef _WIN32
  12634. reinterpret_cast<const char *>(&opt),
  12635. #else
  12636. &opt,
  12637. #endif
  12638. sizeof(opt));
  12639. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12640. ::listen(srv, 1);
  12641. sockaddr_in cli_addr{};
  12642. socklen_t cli_len = sizeof(cli_addr);
  12643. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12644. if (cli != INVALID_SOCKET) {
  12645. char buf[4096];
  12646. ::recv(cli, buf, sizeof(buf), 0);
  12647. // Malicious response: claim a 20GB body but send only a tiny payload.
  12648. std::string response = "HTTP/1.1 200 OK\r\n"
  12649. "Content-Length: 20000000000\r\n"
  12650. "\r\n"
  12651. "abc";
  12652. ::send(cli,
  12653. #ifdef _WIN32
  12654. static_cast<const char *>(response.c_str()),
  12655. static_cast<int>(response.size()),
  12656. #else
  12657. response.c_str(), response.size(),
  12658. #endif
  12659. 0);
  12660. detail::close_socket(cli);
  12661. }
  12662. detail::close_socket(srv);
  12663. });
  12664. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12665. {
  12666. Client cli("127.0.0.1", PORT + 2);
  12667. cli.set_read_timeout(5, 0);
  12668. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12669. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12670. // (server claims more bytes than payload_max_length permits), but it must
  12671. // not exhaust memory before getting there.
  12672. auto res = cli.Get("/malicious");
  12673. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12674. }
  12675. server_thread.join();
  12676. }
  12677. // Verify that content_receiver bypasses the default payload_max_length,
  12678. // allowing streaming downloads larger than 100MB without requiring an explicit
  12679. // set_payload_max_length call.
  12680. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12681. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12682. #ifndef _WIN32
  12683. signal(SIGPIPE, SIG_IGN);
  12684. #endif
  12685. auto server_thread = std::thread([] {
  12686. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12687. default_socket_options(srv);
  12688. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12689. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12690. sockaddr_in addr{};
  12691. addr.sin_family = AF_INET;
  12692. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12693. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12694. int opt = 1;
  12695. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12696. #ifdef _WIN32
  12697. reinterpret_cast<const char *>(&opt),
  12698. #else
  12699. &opt,
  12700. #endif
  12701. sizeof(opt));
  12702. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12703. ::listen(srv, 1);
  12704. sockaddr_in cli_addr{};
  12705. socklen_t cli_len = sizeof(cli_addr);
  12706. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12707. if (cli != INVALID_SOCKET) {
  12708. char buf[4096];
  12709. ::recv(cli, buf, sizeof(buf), 0);
  12710. // Response with Content-Length larger than default 100MB limit
  12711. auto content_length = std::to_string(DATA_SIZE);
  12712. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12713. "Content-Length: " +
  12714. content_length +
  12715. "\r\n"
  12716. "Connection: close\r\n"
  12717. "\r\n";
  12718. ::send(cli,
  12719. #ifdef _WIN32
  12720. static_cast<const char *>(response_header.c_str()),
  12721. static_cast<int>(response_header.size()),
  12722. #else
  12723. response_header.c_str(), response_header.size(),
  12724. #endif
  12725. 0);
  12726. std::string chunk(64 * 1024, 'A');
  12727. size_t total_sent = 0;
  12728. while (total_sent < DATA_SIZE) {
  12729. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12730. auto sent = ::send(cli,
  12731. #ifdef _WIN32
  12732. static_cast<const char *>(chunk.c_str()),
  12733. static_cast<int>(to_send),
  12734. #else
  12735. chunk.c_str(), to_send,
  12736. #endif
  12737. 0);
  12738. if (sent <= 0) break;
  12739. total_sent += static_cast<size_t>(sent);
  12740. }
  12741. detail::close_socket(cli);
  12742. }
  12743. detail::close_socket(srv);
  12744. });
  12745. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12746. size_t total_received = 0;
  12747. {
  12748. Client cli("127.0.0.1", PORT + 2);
  12749. cli.set_read_timeout(10, 0);
  12750. // Do NOT call set_payload_max_length — use the default 100MB limit
  12751. auto res =
  12752. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12753. total_received += data_length;
  12754. return true;
  12755. });
  12756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12757. EXPECT_EQ(StatusCode::OK_200, res->status);
  12758. }
  12759. server_thread.join();
  12760. EXPECT_EQ(total_received, DATA_SIZE)
  12761. << "With content_receiver, the client should read all " << DATA_SIZE
  12762. << " bytes despite the default 100MB payload_max_length, but only read "
  12763. << total_received << " bytes.";
  12764. }
  12765. // Verify that an explicit set_payload_max_length smaller than the response is
  12766. // enforced even when a content_receiver is used.
  12767. TEST(ClientVulnerabilityTest,
  12768. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12769. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12770. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12771. #ifndef _WIN32
  12772. signal(SIGPIPE, SIG_IGN);
  12773. #endif
  12774. auto server_thread = std::thread([] {
  12775. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12776. default_socket_options(srv);
  12777. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12778. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12779. sockaddr_in addr{};
  12780. addr.sin_family = AF_INET;
  12781. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12782. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12783. int opt = 1;
  12784. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12785. #ifdef _WIN32
  12786. reinterpret_cast<const char *>(&opt),
  12787. #else
  12788. &opt,
  12789. #endif
  12790. sizeof(opt));
  12791. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12792. ::listen(srv, 1);
  12793. sockaddr_in cli_addr{};
  12794. socklen_t cli_len = sizeof(cli_addr);
  12795. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12796. if (cli != INVALID_SOCKET) {
  12797. char buf[4096];
  12798. ::recv(cli, buf, sizeof(buf), 0);
  12799. auto content_length = std::to_string(DATA_SIZE);
  12800. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12801. "Content-Length: " +
  12802. content_length +
  12803. "\r\n"
  12804. "Connection: close\r\n"
  12805. "\r\n";
  12806. ::send(cli,
  12807. #ifdef _WIN32
  12808. static_cast<const char *>(response_header.c_str()),
  12809. static_cast<int>(response_header.size()),
  12810. #else
  12811. response_header.c_str(), response_header.size(),
  12812. #endif
  12813. 0);
  12814. std::string chunk(64 * 1024, 'A');
  12815. size_t total_sent = 0;
  12816. while (total_sent < DATA_SIZE) {
  12817. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12818. auto sent = ::send(cli,
  12819. #ifdef _WIN32
  12820. static_cast<const char *>(chunk.c_str()),
  12821. static_cast<int>(to_send),
  12822. #else
  12823. chunk.c_str(), to_send,
  12824. #endif
  12825. 0);
  12826. if (sent <= 0) break;
  12827. total_sent += static_cast<size_t>(sent);
  12828. }
  12829. detail::close_socket(cli);
  12830. }
  12831. detail::close_socket(srv);
  12832. });
  12833. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12834. size_t total_received = 0;
  12835. {
  12836. Client cli("127.0.0.1", PORT + 2);
  12837. cli.set_read_timeout(10, 0);
  12838. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12839. auto res =
  12840. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12841. total_received += data_length;
  12842. return true;
  12843. });
  12844. // Should fail because 200MB exceeds the explicit 150MB limit
  12845. EXPECT_FALSE(res);
  12846. }
  12847. server_thread.join();
  12848. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12849. << "Client with content_receiver should respect the explicit "
  12850. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12851. << total_received << " bytes.";
  12852. }
  12853. // Verify that an explicit set_payload_max_length larger than the response
  12854. // allows the content_receiver to read all data successfully.
  12855. TEST(ClientVulnerabilityTest,
  12856. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12857. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12858. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12859. #ifndef _WIN32
  12860. signal(SIGPIPE, SIG_IGN);
  12861. #endif
  12862. auto server_thread = std::thread([] {
  12863. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12864. default_socket_options(srv);
  12865. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12866. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12867. sockaddr_in addr{};
  12868. addr.sin_family = AF_INET;
  12869. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12870. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12871. int opt = 1;
  12872. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12873. #ifdef _WIN32
  12874. reinterpret_cast<const char *>(&opt),
  12875. #else
  12876. &opt,
  12877. #endif
  12878. sizeof(opt));
  12879. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12880. ::listen(srv, 1);
  12881. sockaddr_in cli_addr{};
  12882. socklen_t cli_len = sizeof(cli_addr);
  12883. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12884. if (cli != INVALID_SOCKET) {
  12885. char buf[4096];
  12886. ::recv(cli, buf, sizeof(buf), 0);
  12887. auto content_length = std::to_string(DATA_SIZE);
  12888. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12889. "Content-Length: " +
  12890. content_length +
  12891. "\r\n"
  12892. "Connection: close\r\n"
  12893. "\r\n";
  12894. ::send(cli,
  12895. #ifdef _WIN32
  12896. static_cast<const char *>(response_header.c_str()),
  12897. static_cast<int>(response_header.size()),
  12898. #else
  12899. response_header.c_str(), response_header.size(),
  12900. #endif
  12901. 0);
  12902. std::string chunk(64 * 1024, 'A');
  12903. size_t total_sent = 0;
  12904. while (total_sent < DATA_SIZE) {
  12905. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12906. auto sent = ::send(cli,
  12907. #ifdef _WIN32
  12908. static_cast<const char *>(chunk.c_str()),
  12909. static_cast<int>(to_send),
  12910. #else
  12911. chunk.c_str(), to_send,
  12912. #endif
  12913. 0);
  12914. if (sent <= 0) break;
  12915. total_sent += static_cast<size_t>(sent);
  12916. }
  12917. #ifdef _WIN32
  12918. ::shutdown(cli, SD_SEND);
  12919. #else
  12920. ::shutdown(cli, SHUT_WR);
  12921. #endif
  12922. char drain[1024];
  12923. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12924. detail::close_socket(cli);
  12925. }
  12926. detail::close_socket(srv);
  12927. });
  12928. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12929. size_t total_received = 0;
  12930. {
  12931. Client cli("127.0.0.1", PORT + 2);
  12932. cli.set_read_timeout(10, 0);
  12933. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12934. auto res =
  12935. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12936. total_received += data_length;
  12937. return true;
  12938. });
  12939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12940. EXPECT_EQ(StatusCode::OK_200, res->status);
  12941. }
  12942. server_thread.join();
  12943. EXPECT_EQ(total_received, DATA_SIZE)
  12944. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12945. << " bytes (larger than " << DATA_SIZE
  12946. << " bytes response), content_receiver should read all data, but only "
  12947. "read "
  12948. << total_received << " bytes.";
  12949. }
  12950. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12951. // Regression test for "zip bomb" attack on the client side: a malicious server
  12952. // sends a small gzip-compressed response that decompresses to a huge payload.
  12953. // The client must enforce payload_max_length on the decompressed size.
  12954. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12955. constexpr size_t DECOMPRESSED_SIZE =
  12956. 10 * 1024 * 1024; // 10MB after decompression
  12957. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12958. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12959. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12960. std::string compressed;
  12961. {
  12962. httplib::detail::gzip_compressor compressor;
  12963. bool ok =
  12964. compressor.compress(uncompressed.data(), uncompressed.size(),
  12965. /*last=*/true, [&](const char *buf, size_t len) {
  12966. compressed.append(buf, len);
  12967. return true;
  12968. });
  12969. ASSERT_TRUE(ok);
  12970. }
  12971. // Sanity: compressed data should be much smaller than the decompressed size
  12972. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12973. #ifndef _WIN32
  12974. signal(SIGPIPE, SIG_IGN);
  12975. #endif
  12976. // Set up the listening socket in the main thread so the server is guaranteed
  12977. // to be ready before the client connects (eliminates race condition).
  12978. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12979. default_socket_options(srv);
  12980. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12981. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12982. sockaddr_in addr{};
  12983. addr.sin_family = AF_INET;
  12984. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12985. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12986. int opt = 1;
  12987. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12988. #ifdef _WIN32
  12989. reinterpret_cast<const char *>(&opt),
  12990. #else
  12991. &opt,
  12992. #endif
  12993. sizeof(opt));
  12994. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12995. ASSERT_EQ(0, ::listen(srv, 1));
  12996. auto server_thread = std::thread([&compressed, srv] {
  12997. sockaddr_in cli_addr{};
  12998. socklen_t cli_len = sizeof(cli_addr);
  12999. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13000. if (cli != INVALID_SOCKET) {
  13001. // Read the full HTTP request (until \r\n\r\n)
  13002. char buf[4096];
  13003. size_t total = 0;
  13004. while (total < sizeof(buf)) {
  13005. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13006. if (n <= 0) break;
  13007. total += static_cast<size_t>(n);
  13008. // Check for end of headers
  13009. if (total >= 4) {
  13010. std::string req(buf, total);
  13011. if (req.find("\r\n\r\n") != std::string::npos) break;
  13012. }
  13013. }
  13014. // Malicious response: gzip-compressed body, no Content-Length
  13015. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13016. "Content-Encoding: gzip\r\n"
  13017. "Connection: close\r\n"
  13018. "\r\n";
  13019. ::send(cli,
  13020. #ifdef _WIN32
  13021. static_cast<const char *>(response_header.c_str()),
  13022. static_cast<int>(response_header.size()),
  13023. #else
  13024. response_header.c_str(), response_header.size(),
  13025. #endif
  13026. 0);
  13027. // Send the compressed payload (small on the wire, huge when decompressed)
  13028. size_t total_sent = 0;
  13029. while (total_sent < compressed.size()) {
  13030. auto to_send = std::min(compressed.size() - total_sent,
  13031. static_cast<size_t>(64 * 1024));
  13032. auto sent =
  13033. ::send(cli,
  13034. #ifdef _WIN32
  13035. static_cast<const char *>(compressed.c_str() + total_sent),
  13036. static_cast<int>(to_send),
  13037. #else
  13038. compressed.c_str() + total_sent, to_send,
  13039. #endif
  13040. 0);
  13041. if (sent <= 0) break;
  13042. total_sent += static_cast<size_t>(sent);
  13043. }
  13044. detail::close_socket(cli);
  13045. }
  13046. });
  13047. auto se = detail::scope_exit([&] {
  13048. detail::close_socket(srv);
  13049. server_thread.join();
  13050. });
  13051. size_t total_decompressed = 0;
  13052. {
  13053. Client cli("127.0.0.1", PORT + 3);
  13054. cli.set_read_timeout(5, 0);
  13055. cli.set_decompress(true);
  13056. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13057. auto stream = cli.open_stream("GET", "/zipbomb");
  13058. ASSERT_TRUE(stream.is_valid());
  13059. char buffer[64 * 1024];
  13060. ssize_t n;
  13061. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13062. total_decompressed += static_cast<size_t>(n);
  13063. }
  13064. }
  13065. // The decompressed size must be capped by payload_max_length. Without
  13066. // protection, the client would decompress the full 10MB from a tiny
  13067. // compressed payload, enabling a zip bomb DoS attack.
  13068. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13069. << "Client decompressed " << total_decompressed
  13070. << " bytes from a gzip response. The decompressed size should be "
  13071. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13072. }
  13073. #endif
  13074. TEST(HostAndPortPropertiesTest, NoSSL) {
  13075. httplib::Client cli("www.google.com", 1234);
  13076. ASSERT_EQ("www.google.com", cli.host());
  13077. ASSERT_EQ(1234, cli.port());
  13078. }
  13079. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13080. httplib::Client cli("www.google.com:1234");
  13081. ASSERT_EQ("www.google.com", cli.host());
  13082. ASSERT_EQ(1234, cli.port());
  13083. }
  13084. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13085. // Port number that overflows int — should not crash, client becomes invalid
  13086. httplib::Client cli("http://www.google.com:99999999999999999999");
  13087. ASSERT_FALSE(cli.is_valid());
  13088. }
  13089. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13090. // Port 99999 exceeds valid range (1-65535) — should not crash
  13091. httplib::Client cli("http://www.google.com:99999");
  13092. ASSERT_FALSE(cli.is_valid());
  13093. auto res = cli.Get("/");
  13094. EXPECT_FALSE(res);
  13095. EXPECT_EQ(Error::Connection, res.error());
  13096. }
  13097. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13098. httplib::Client cli("http://user:pass@localhost:1234");
  13099. ASSERT_FALSE(cli.is_valid());
  13100. EXPECT_FALSE(cli.Get("/"));
  13101. }
  13102. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13103. httplib::Client cli("http://www.google.com:80abc");
  13104. ASSERT_FALSE(cli.is_valid());
  13105. }
  13106. #ifdef CPPHTTPLIB_SSL_ENABLED
  13107. TEST(HostAndPortPropertiesTest, SSL) {
  13108. httplib::SSLClient cli("www.google.com");
  13109. ASSERT_EQ("www.google.com", cli.host());
  13110. ASSERT_EQ(443, cli.port());
  13111. }
  13112. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13113. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13114. std::string cert;
  13115. read_file(CA_CERT_FILE, cert);
  13116. httplib::SSLClient httplib_client("www.google.com");
  13117. // Load CA store first time
  13118. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13119. // Load CA store second time (update)
  13120. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13121. // Verify client is still valid and can make connections
  13122. httplib_client.enable_server_certificate_verification(true);
  13123. auto res = httplib_client.Get("/");
  13124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13125. // Google may return 200 or 301 depending on various factors
  13126. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13127. res->status == StatusCode::MovedPermanently_301);
  13128. }
  13129. TEST(SSLClientTest, ServerNameIndication_Online) {
  13130. auto host = "httpbingo.org";
  13131. auto path = std::string{"/get"};
  13132. SSLClient cli(host, 443);
  13133. auto res = cli.Get(path);
  13134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13135. ASSERT_EQ(StatusCode::OK_200, res->status);
  13136. }
  13137. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13138. // Use a site that will cause SSL verification failure due to self-signed cert
  13139. SSLClient cli("self-signed.badssl.com", 443);
  13140. cli.enable_server_certificate_verification(true);
  13141. auto res = cli.Get("/");
  13142. ASSERT_TRUE(!res);
  13143. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13144. // Verify backend error is captured for SSLServerVerification
  13145. // This occurs when certificate verification fails
  13146. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13147. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13148. EXPECT_NE(0UL, res.ssl_backend_error());
  13149. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13150. // For OpenSSL, ssl_error is 0 for verification errors
  13151. EXPECT_EQ(0, res.ssl_error());
  13152. #if !defined(_WIN32) || \
  13153. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13154. // On non-Windows or when Windows Schannel is disabled, the error comes
  13155. // from OpenSSL's verification
  13156. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13157. res.ssl_backend_error());
  13158. #endif
  13159. #endif
  13160. }
  13161. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13162. // Use a site where hostname doesn't match the certificate
  13163. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13164. SSLClient cli("wrong.host.badssl.com", 443);
  13165. cli.enable_server_certificate_verification(true);
  13166. cli.enable_server_hostname_verification(true);
  13167. auto res = cli.Get("/");
  13168. ASSERT_TRUE(!res);
  13169. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13170. // Verify backend error is captured for hostname verification failure
  13171. EXPECT_NE(0UL, res.ssl_backend_error());
  13172. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13173. // For OpenSSL, ssl_error is 0 for verification errors
  13174. EXPECT_EQ(0, res.ssl_error());
  13175. #if !defined(_WIN32) || \
  13176. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13177. // On non-Windows or when Windows Schannel is disabled, the error comes
  13178. // from OpenSSL's hostname verification
  13179. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13180. res.ssl_backend_error());
  13181. #endif
  13182. #endif
  13183. }
  13184. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13185. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13186. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13187. SSLClient cli("www.google.com", 443);
  13188. cli.enable_server_certificate_verification(true);
  13189. auto res = cli.Get("/");
  13190. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13191. }
  13192. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13193. SSLClient cli("www.google.com", 443);
  13194. cli.enable_server_certificate_verification(true);
  13195. cli.enable_windows_certificate_verification(false);
  13196. auto res = cli.Get("/");
  13197. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13198. }
  13199. // The server sends an intermediate cross-signed by a root Windows trusts,
  13200. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13201. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13202. SSLClient cli("accounts.spotify.com", 443);
  13203. auto res = cli.Get("/");
  13204. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13205. << " ssl_backend_error=" << res.ssl_backend_error();
  13206. }
  13207. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13208. // policy status, which no backend reports for a self-signed certificate.
  13209. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13210. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13211. ASSERT_TRUE(svr.is_valid());
  13212. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13213. auto se = detail::scope_exit([&] {
  13214. svr.stop();
  13215. t.join();
  13216. ASSERT_FALSE(svr.is_running());
  13217. });
  13218. svr.wait_until_ready();
  13219. SSLClient cli("127.0.0.1", PORT);
  13220. cli.set_connection_timeout(30);
  13221. auto res = cli.Get("/");
  13222. ASSERT_FALSE(res);
  13223. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13224. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13225. }
  13226. #endif
  13227. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13228. Client cli("https://google.com");
  13229. auto res = cli.Get("/");
  13230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13231. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13232. }
  13233. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13234. SSLClient cli("google.com");
  13235. cli.set_ca_cert_path(CA_CERT_FILE);
  13236. auto res = cli.Get("/");
  13237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13238. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13239. }
  13240. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13241. SSLClient cli("google.com");
  13242. cli.enable_server_certificate_verification(true);
  13243. cli.set_ca_cert_path("hello");
  13244. auto res = cli.Get("/");
  13245. ASSERT_TRUE(!res);
  13246. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13247. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13248. // should be set
  13249. EXPECT_EQ(0, res.ssl_error());
  13250. // Verify backend error is captured for SSLLoadingCerts
  13251. // This error occurs when loading CA certificates fails
  13252. EXPECT_NE(0UL, res.ssl_backend_error());
  13253. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13254. // OpenSSL specific error codes:
  13255. // > openssl errstr 0x80000002
  13256. // error:80000002:system library::No such file or directory
  13257. // > openssl errstr 0xA000126
  13258. // error:0A000126:SSL routines::unexpected eof while reading
  13259. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13260. res.ssl_backend_error() == 0xA000126);
  13261. #endif
  13262. }
  13263. TEST(SSLClientTest, ServerCertificateVerification4) {
  13264. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13265. ASSERT_TRUE(svr.is_valid());
  13266. svr.Get("/test", [&](const Request &, Response &res) {
  13267. res.set_content("test", "text/plain");
  13268. svr.stop();
  13269. ASSERT_TRUE(true);
  13270. });
  13271. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13272. auto se = detail::scope_exit([&] {
  13273. t.join();
  13274. ASSERT_FALSE(svr.is_running());
  13275. });
  13276. svr.wait_until_ready();
  13277. SSLClient cli("127.0.0.1", PORT);
  13278. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13279. cli.enable_server_certificate_verification(true);
  13280. cli.set_connection_timeout(30);
  13281. auto res = cli.Get("/test");
  13282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13283. ASSERT_EQ(StatusCode::OK_200, res->status);
  13284. }
  13285. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13286. std::string cert;
  13287. read_file(CA_CERT_FILE, cert);
  13288. SSLClient cli("google.com");
  13289. cli.load_ca_cert_store(cert.data(), cert.size());
  13290. const auto res = cli.Get("/");
  13291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13292. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13293. }
  13294. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13295. // clang-format off
  13296. static constexpr char cert[] =
  13297. "GlobalSign Root CA\n"
  13298. "==================\n"
  13299. "-----BEGIN CERTIFICATE-----\n"
  13300. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13301. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13302. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13303. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13304. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13305. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13306. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13307. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13308. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13309. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13310. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13311. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13312. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13313. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13314. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13315. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13316. "-----END CERTIFICATE-----\n";
  13317. // clang-format on
  13318. SSLClient cli("google.com");
  13319. cli.load_ca_cert_store(cert, sizeof(cert));
  13320. const auto res = cli.Get("/");
  13321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13322. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13323. }
  13324. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13325. SSLClient cli("www.youtube.com");
  13326. cli.set_ca_cert_path(CA_CERT_FILE);
  13327. cli.enable_server_certificate_verification(true);
  13328. cli.set_follow_location(true);
  13329. auto res = cli.Get("/");
  13330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13331. ASSERT_EQ(StatusCode::OK_200, res->status);
  13332. }
  13333. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13334. SSLClient cli("wWw.YouTube.Com");
  13335. cli.set_ca_cert_path(CA_CERT_FILE);
  13336. cli.enable_server_certificate_verification(true);
  13337. cli.enable_server_hostname_verification(true);
  13338. cli.set_follow_location(true);
  13339. auto res = cli.Get("/");
  13340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13341. ASSERT_EQ(StatusCode::OK_200, res->status);
  13342. }
  13343. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13344. SSLClient cli("gOoGlE.COm");
  13345. cli.enable_server_certificate_verification(true);
  13346. cli.enable_server_hostname_verification(true);
  13347. cli.set_follow_location(true);
  13348. auto res = cli.Get("/");
  13349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13350. ASSERT_EQ(StatusCode::OK_200, res->status);
  13351. }
  13352. TEST(SSLClientTest, Issue2004_Online) {
  13353. Client client("https://google.com");
  13354. client.set_follow_location(true);
  13355. auto res = client.Get("/");
  13356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13357. ASSERT_EQ(StatusCode::OK_200, res->status);
  13358. auto body = res->body;
  13359. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13360. }
  13361. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13362. // Create SSLClient with invalid cert/key to make is_valid() return false
  13363. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13364. "nonexistent_key.pem");
  13365. // is_valid() should be false due to cert loading failure
  13366. ASSERT_FALSE(cli.is_valid());
  13367. auto res = cli.Get("/");
  13368. ASSERT_FALSE(res);
  13369. EXPECT_EQ(Error::SSLConnection, res.error());
  13370. }
  13371. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13372. // Test for Issue #2251: SSL error not properly reported when client cert
  13373. // and key paths are swapped or mismatched
  13374. // This simulates the scenario where user accidentally swaps the cert and key
  13375. // files
  13376. // Using client cert file as private key and vice versa (completely wrong)
  13377. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13378. // Should fail validation due to cert/key mismatch
  13379. ASSERT_FALSE(cli.is_valid());
  13380. // Attempt to make a request should fail with proper error
  13381. auto res = cli.Get("/");
  13382. ASSERT_FALSE(res);
  13383. EXPECT_EQ(Error::SSLConnection, res.error());
  13384. // SSL error should be recorded in the Result object (this is the key fix for
  13385. // Issue #2251)
  13386. auto backend_error = res.ssl_backend_error();
  13387. EXPECT_NE(0u, backend_error);
  13388. }
  13389. // Tests cert/key mismatch detection at the TLS context level
  13390. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13391. // Test that using mismatched cert/key causes connection failure.
  13392. // We verify this at the SSLClient level rather than through internal
  13393. // TLS API functions.
  13394. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13395. cli.enable_server_certificate_verification(false);
  13396. cli.set_connection_timeout(2);
  13397. // The mismatch should cause a connection or handshake error
  13398. auto res = cli.Get("/test");
  13399. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13400. // Either way, the request should fail
  13401. EXPECT_FALSE(res);
  13402. }
  13403. #endif
  13404. #if 0
  13405. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13406. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13407. ASSERT_TRUE(cli != nullptr);
  13408. cli->set_address_family(AF_INET6);
  13409. cli->set_interface("en0");
  13410. auto res = cli->Get("/get");
  13411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13412. ASSERT_EQ(StatusCode::OK_200, res->status);
  13413. }
  13414. #endif
  13415. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  13416. #ifdef CPPHTTPLIB_SSL_ENABLED
  13417. void ClientCertPresent(
  13418. const std::string &client_cert_file,
  13419. const std::string &client_private_key_file,
  13420. const std::string &client_encrypted_private_key_pass = std::string()) {
  13421. using namespace httplib::tls;
  13422. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13423. CLIENT_CA_CERT_DIR);
  13424. ASSERT_TRUE(svr.is_valid());
  13425. svr.Get("/test", [&](const Request &req, Response &res) {
  13426. res.set_content("test", "text/plain");
  13427. auto cert = req.peer_cert();
  13428. ASSERT_TRUE(static_cast<bool>(cert));
  13429. std::string common_name = cert.subject_cn();
  13430. EXPECT_EQ("Common Name", common_name);
  13431. });
  13432. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13433. auto se = detail::scope_exit([&] {
  13434. svr.stop();
  13435. t.join();
  13436. ASSERT_FALSE(svr.is_running());
  13437. });
  13438. svr.wait_until_ready();
  13439. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  13440. client_encrypted_private_key_pass);
  13441. cli.enable_server_certificate_verification(false);
  13442. cli.set_connection_timeout(30);
  13443. auto res = cli.Get("/test");
  13444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13445. ASSERT_EQ(StatusCode::OK_200, res->status);
  13446. }
  13447. TEST(SSLClientServerTest, ClientCertPresent) {
  13448. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13449. }
  13450. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13451. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13452. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13453. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13454. }
  13455. // PEM memory-based constructor tests (works with all TLS backends)
  13456. void PemMemoryClientCertPresent(
  13457. const std::string &client_cert_file,
  13458. const std::string &client_private_key_file,
  13459. const std::string &client_encrypted_private_key_pass = std::string()) {
  13460. // Read PEM files into memory
  13461. std::string server_cert_pem, server_key_pem;
  13462. std::string client_ca_pem;
  13463. std::string client_cert_pem, client_key_pem;
  13464. read_file(SERVER_CERT_FILE, server_cert_pem);
  13465. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13466. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13467. read_file(client_cert_file, client_cert_pem);
  13468. read_file(client_private_key_file, client_key_pem);
  13469. // Create server with PEM memory
  13470. SSLServer::PemMemory server_pem = {
  13471. server_cert_pem.c_str(),
  13472. server_cert_pem.size(),
  13473. server_key_pem.c_str(),
  13474. server_key_pem.size(),
  13475. client_ca_pem.c_str(),
  13476. client_ca_pem.size(),
  13477. nullptr // no password for server key
  13478. };
  13479. SSLServer svr(server_pem);
  13480. ASSERT_TRUE(svr.is_valid());
  13481. svr.Get("/test", [&](const Request &, Response &res) {
  13482. res.set_content("test", "text/plain");
  13483. });
  13484. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13485. auto se = detail::scope_exit([&] {
  13486. svr.stop();
  13487. t.join();
  13488. ASSERT_FALSE(svr.is_running());
  13489. });
  13490. svr.wait_until_ready();
  13491. // Create client with PEM memory
  13492. const char *password = client_encrypted_private_key_pass.empty()
  13493. ? nullptr
  13494. : client_encrypted_private_key_pass.c_str();
  13495. SSLClient::PemMemory client_pem = {
  13496. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  13497. client_key_pem.size(), password};
  13498. SSLClient cli(HOST, PORT, client_pem);
  13499. cli.enable_server_certificate_verification(false);
  13500. cli.set_connection_timeout(30);
  13501. auto res = cli.Get("/test");
  13502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13503. ASSERT_EQ(StatusCode::OK_200, res->status);
  13504. }
  13505. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13506. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13507. }
  13508. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13509. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13510. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13511. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13512. }
  13513. TEST(SSLClientServerTest, ClientCertMissing) {
  13514. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13515. CLIENT_CA_CERT_DIR);
  13516. ASSERT_TRUE(svr.is_valid());
  13517. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  13518. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13519. auto se = detail::scope_exit([&] {
  13520. svr.stop();
  13521. t.join();
  13522. ASSERT_FALSE(svr.is_running());
  13523. });
  13524. svr.wait_until_ready();
  13525. SSLClient cli(HOST, PORT);
  13526. cli.set_connection_timeout(30);
  13527. // cert.pem does not match HOST. Skip the hostname check, which runs before
  13528. // the chain check on Windows, so the result does not depend on the order.
  13529. cli.enable_server_hostname_verification(false);
  13530. auto res = cli.Get("/test");
  13531. ASSERT_TRUE(!res);
  13532. // When client cert is missing and server requires it, connection fails
  13533. // Error type depends on backend implementation
  13534. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13535. res.error() == Error::SSLConnection);
  13536. // Verify backend error is captured
  13537. // Note: This test may have different error codes depending on the exact
  13538. // verification failure
  13539. EXPECT_NE(0UL, res.ssl_backend_error());
  13540. }
  13541. TEST(SSLClientServerTest, TrustDirOptional) {
  13542. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13543. ASSERT_TRUE(svr.is_valid());
  13544. svr.Get("/test", [&](const Request &, Response &res) {
  13545. res.set_content("test", "text/plain");
  13546. });
  13547. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13548. auto se = detail::scope_exit([&] {
  13549. svr.stop();
  13550. t.join();
  13551. ASSERT_FALSE(svr.is_running());
  13552. });
  13553. svr.wait_until_ready();
  13554. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13555. cli.enable_server_certificate_verification(false);
  13556. cli.set_connection_timeout(30);
  13557. auto res = cli.Get("/test");
  13558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13559. ASSERT_EQ(StatusCode::OK_200, res->status);
  13560. }
  13561. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13562. class NoListenSSLServer : public SSLServer {
  13563. public:
  13564. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13565. const char *client_ca_cert_file_path,
  13566. const char *client_ca_cert_dir_path = nullptr)
  13567. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13568. client_ca_cert_dir_path),
  13569. stop_(false) {}
  13570. std::atomic_bool stop_;
  13571. private:
  13572. bool process_and_close_socket(socket_t /*sock*/) override {
  13573. // Don't create SSL context
  13574. while (!stop_.load()) {
  13575. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13576. }
  13577. return true;
  13578. }
  13579. };
  13580. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13581. CLIENT_CA_CERT_FILE);
  13582. ASSERT_TRUE(svr.is_valid());
  13583. svr.Get("/test", [&](const Request &, Response &res) {
  13584. res.set_content("test", "text/plain");
  13585. });
  13586. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13587. auto se = detail::scope_exit([&] {
  13588. svr.stop_ = true;
  13589. svr.stop();
  13590. t.join();
  13591. ASSERT_FALSE(svr.is_running());
  13592. });
  13593. svr.wait_until_ready();
  13594. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13595. cli.enable_server_certificate_verification(false);
  13596. cli.set_connection_timeout(1);
  13597. auto res = cli.Get("/test");
  13598. ASSERT_TRUE(!res);
  13599. EXPECT_EQ(Error::SSLConnection, res.error());
  13600. // Timeout results in WantRead error code (maps to backend-specific value)
  13601. EXPECT_NE(0, res.ssl_error());
  13602. }
  13603. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13604. // Test SSLServer with client certificate verification using the standard
  13605. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13606. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13607. CLIENT_CA_CERT_DIR);
  13608. ASSERT_TRUE(svr.is_valid());
  13609. svr.Get("/test", [&](const Request &req, Response &res) {
  13610. res.set_content("test", "text/plain");
  13611. auto cert = req.peer_cert();
  13612. ASSERT_TRUE(static_cast<bool>(cert));
  13613. auto common_name = cert.subject_cn();
  13614. EXPECT_EQ("Common Name", common_name);
  13615. });
  13616. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13617. auto se = detail::scope_exit([&] {
  13618. svr.stop();
  13619. t.join();
  13620. ASSERT_FALSE(svr.is_running());
  13621. });
  13622. svr.wait_until_ready();
  13623. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13624. cli.enable_server_certificate_verification(false);
  13625. cli.set_connection_timeout(30);
  13626. auto res = cli.Get("/test");
  13627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13628. ASSERT_EQ(StatusCode::OK_200, res->status);
  13629. }
  13630. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13631. // Verifies that wildcard matching and exact matching work consistently
  13632. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13633. using namespace httplib::tls;
  13634. // We need a running server to test against
  13635. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13636. ASSERT_TRUE(svr.is_valid());
  13637. svr.Get("/test", [](const Request &, Response &res) {
  13638. res.set_content("ok", "text/plain");
  13639. });
  13640. thread t([&]() { svr.listen(HOST, PORT); });
  13641. auto se = detail::scope_exit([&] {
  13642. svr.stop();
  13643. t.join();
  13644. });
  13645. svr.wait_until_ready();
  13646. bool verify_callback_called = false;
  13647. bool verify_result_wrong = false;
  13648. SSLClient cli(HOST, PORT);
  13649. cli.enable_server_certificate_verification(true);
  13650. cli.set_ca_cert_path(CA_CERT_FILE);
  13651. cli.set_connection_timeout(5);
  13652. // Note: Test certificate has CN="Common Name", not "localhost"
  13653. bool verify_result_cn = false;
  13654. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13655. verify_callback_called = true;
  13656. if (!ctx.cert) return false;
  13657. // Test 1: "Common Name" should match (our test server cert CN)
  13658. verify_result_cn = ctx.check_hostname("Common Name");
  13659. // Test 2: wrong hostname should not match
  13660. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13661. return true; // Accept for the purpose of this test
  13662. });
  13663. auto res = cli.Get("/test");
  13664. // The request may succeed or fail depending on cert configuration
  13665. // but the callback should have been called
  13666. ASSERT_TRUE(verify_callback_called)
  13667. << "Verify callback should have been called";
  13668. // CN="Common Name" should match our test certificate
  13669. //
  13670. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13671. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13672. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13673. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13674. // <openssl/base.h>, which is included transitively when
  13675. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13676. #if defined(OPENSSL_IS_BORINGSSL)
  13677. EXPECT_FALSE(verify_result_cn)
  13678. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13679. #else
  13680. EXPECT_TRUE(verify_result_cn)
  13681. << "verify_hostname should match 'Common Name' (certificate CN)";
  13682. #endif
  13683. // Wrong hostname should not match
  13684. EXPECT_FALSE(verify_result_wrong)
  13685. << "verify_hostname should not match 'wronghost.example.com'";
  13686. }
  13687. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13688. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13689. // X509_check_ip behavior and must hold for every backend.
  13690. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13691. using namespace httplib::tls;
  13692. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13693. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13694. ASSERT_TRUE(svr.is_valid());
  13695. svr.Get("/test", [](const Request &, Response &res) {
  13696. res.set_content("ok", "text/plain");
  13697. });
  13698. thread t([&]() { svr.listen(HOST, PORT); });
  13699. auto se = detail::scope_exit([&] {
  13700. svr.stop();
  13701. t.join();
  13702. });
  13703. svr.wait_until_ready();
  13704. bool verify_callback_called = false;
  13705. bool ip_matched_via_cn = true;
  13706. SSLClient cli(HOST, PORT);
  13707. cli.enable_server_certificate_verification(true);
  13708. cli.set_ca_cert_path(CA_CERT_FILE);
  13709. cli.set_connection_timeout(5);
  13710. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13711. verify_callback_called = true;
  13712. if (!ctx.cert) return false;
  13713. // The IP appears only in the CN, so it must NOT be accepted.
  13714. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13715. return true; // Accept for the purpose of this test
  13716. });
  13717. cli.Get("/test");
  13718. ASSERT_TRUE(verify_callback_called)
  13719. << "Verify callback should have been called";
  13720. EXPECT_FALSE(ip_matched_via_cn)
  13721. << "An IP host must not be authenticated via the certificate CN";
  13722. }
  13723. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13724. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13725. using namespace httplib::tls;
  13726. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13727. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13728. ASSERT_TRUE(svr.is_valid());
  13729. svr.Get("/test", [](const Request &, Response &res) {
  13730. res.set_content("ok", "text/plain");
  13731. });
  13732. thread t([&]() { svr.listen(HOST, PORT); });
  13733. auto se = detail::scope_exit([&] {
  13734. svr.stop();
  13735. t.join();
  13736. });
  13737. svr.wait_until_ready();
  13738. bool verify_callback_called = false;
  13739. bool san_matched = false;
  13740. bool wrong_ipv6_matched = true;
  13741. bool cn_ipv6_matched = true;
  13742. SSLClient cli(HOST, PORT);
  13743. cli.enable_server_certificate_verification(true);
  13744. cli.set_ca_cert_path(CA_CERT_FILE);
  13745. cli.set_connection_timeout(5);
  13746. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13747. verify_callback_called = true;
  13748. if (!ctx.cert) return false;
  13749. // Matches the IPv6 iPAddress SAN.
  13750. san_matched = ctx.check_hostname("2001:db8::1");
  13751. // A different IPv6 address must not match.
  13752. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13753. // "::1" lives only in the CN, so it must not be accepted.
  13754. cn_ipv6_matched = ctx.check_hostname("::1");
  13755. return true; // Accept for the purpose of this test
  13756. });
  13757. cli.Get("/test");
  13758. ASSERT_TRUE(verify_callback_called)
  13759. << "Verify callback should have been called";
  13760. EXPECT_TRUE(san_matched)
  13761. << "verify_hostname should match an IPv6 iPAddress SAN";
  13762. EXPECT_FALSE(wrong_ipv6_matched)
  13763. << "verify_hostname should not match a non-matching IPv6 address";
  13764. EXPECT_FALSE(cn_ipv6_matched)
  13765. << "An IPv6 host must not be authenticated via the certificate CN";
  13766. }
  13767. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13768. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13769. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13770. using namespace httplib::tls;
  13771. // SANs: DNS:a.zz, IP:42.46.122.122
  13772. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13773. ASSERT_TRUE(svr.is_valid());
  13774. svr.Get("/test", [](const Request &, Response &res) {
  13775. res.set_content("ok", "text/plain");
  13776. });
  13777. auto port = svr.bind_to_any_port(HOST);
  13778. thread t([&]() { svr.listen_after_bind(); });
  13779. auto se = detail::scope_exit([&] {
  13780. svr.stop();
  13781. t.join();
  13782. });
  13783. svr.wait_until_ready();
  13784. bool verify_callback_called = false;
  13785. bool dns_san_matched = false;
  13786. bool ip_san_matched = false;
  13787. bool ip_matched_via_dns_san = true;
  13788. bool dns_matched_via_ip_san = true;
  13789. bool cn_matched_next_to_dns_san = true;
  13790. SSLClient cli(HOST, port);
  13791. cli.enable_server_certificate_verification(true);
  13792. cli.set_ca_cert_path(CA_CERT_FILE);
  13793. cli.set_connection_timeout(5);
  13794. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13795. verify_callback_called = true;
  13796. if (!ctx.cert) return false;
  13797. dns_san_matched = ctx.check_hostname("a.zz");
  13798. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13799. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13800. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13801. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  13802. return true; // Accept for the purpose of this test
  13803. });
  13804. cli.Get("/test");
  13805. ASSERT_TRUE(verify_callback_called)
  13806. << "Verify callback should have been called";
  13807. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13808. EXPECT_TRUE(ip_san_matched)
  13809. << "verify_hostname should match an iPAddress SAN";
  13810. EXPECT_FALSE(ip_matched_via_dns_san)
  13811. << "An IP host must not be authenticated via a dNSName SAN";
  13812. EXPECT_FALSE(dns_matched_via_ip_san)
  13813. << "A DNS host must not be authenticated via an iPAddress SAN";
  13814. EXPECT_FALSE(cn_matched_next_to_dns_san)
  13815. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  13816. }
  13817. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13818. // "www.*.example.test" names one host and not every host under example.test.
  13819. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13820. using namespace httplib::tls;
  13821. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13822. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13823. ASSERT_TRUE(svr.is_valid());
  13824. svr.Get("/test", [](const Request &, Response &res) {
  13825. res.set_content("ok", "text/plain");
  13826. });
  13827. auto port = svr.bind_to_any_port(HOST);
  13828. thread t([&]() { svr.listen_after_bind(); });
  13829. auto se = detail::scope_exit([&] {
  13830. svr.stop();
  13831. t.join();
  13832. });
  13833. svr.wait_until_ready();
  13834. bool verify_callback_called = false;
  13835. bool leftmost_wildcard_matched = false;
  13836. bool wildcard_spanned_labels = true;
  13837. bool inner_wildcard_matched = true;
  13838. SSLClient cli(HOST, port);
  13839. cli.enable_server_certificate_verification(true);
  13840. cli.set_ca_cert_path(CA_CERT_FILE);
  13841. cli.set_connection_timeout(5);
  13842. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13843. verify_callback_called = true;
  13844. if (!ctx.cert) return false;
  13845. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13846. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13847. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13848. return true; // Accept for the purpose of this test
  13849. });
  13850. cli.Get("/test");
  13851. ASSERT_TRUE(verify_callback_called)
  13852. << "Verify callback should have been called";
  13853. EXPECT_TRUE(leftmost_wildcard_matched)
  13854. << "A leftmost wildcard should match a single label";
  13855. EXPECT_FALSE(wildcard_spanned_labels)
  13856. << "A wildcard label must not match more than one label";
  13857. EXPECT_FALSE(inner_wildcard_matched)
  13858. << "A wildcard outside the leftmost label must not be honoured";
  13859. }
  13860. // sans() must report each SAN entry under its own type.
  13861. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13862. using namespace httplib::tls;
  13863. // SANs: DNS:a.zz, IP:42.46.122.122
  13864. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13865. ASSERT_TRUE(svr.is_valid());
  13866. svr.Get("/test", [](const Request &, Response &res) {
  13867. res.set_content("ok", "text/plain");
  13868. });
  13869. auto port = svr.bind_to_any_port(HOST);
  13870. thread t([&]() { svr.listen_after_bind(); });
  13871. auto se = detail::scope_exit([&] {
  13872. svr.stop();
  13873. t.join();
  13874. });
  13875. svr.wait_until_ready();
  13876. bool verify_callback_called = false;
  13877. std::vector<SanEntry> sans;
  13878. SSLClient cli(HOST, port);
  13879. cli.enable_server_certificate_verification(true);
  13880. cli.set_ca_cert_path(CA_CERT_FILE);
  13881. cli.set_connection_timeout(5);
  13882. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13883. verify_callback_called = true;
  13884. if (!ctx.cert) return false;
  13885. sans = ctx.sans();
  13886. return true; // Accept for the purpose of this test
  13887. });
  13888. cli.Get("/test");
  13889. ASSERT_TRUE(verify_callback_called)
  13890. << "Verify callback should have been called";
  13891. auto has_san = [&](SanType type, const std::string &value) {
  13892. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13893. return san.type == type && san.value == value;
  13894. });
  13895. };
  13896. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13897. << "sans() should report the dNSName SAN";
  13898. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13899. << "sans() should report the iPAddress SAN";
  13900. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13901. << "sans() must not report the dNSName SAN as an address";
  13902. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13903. << "sans() must not report the iPAddress SAN as a DNS name";
  13904. }
  13905. #endif
  13906. // mbedTLS-specific callback constructor test
  13907. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13908. #ifdef CPPHTTPLIB_SSL_ENABLED
  13909. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13910. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13911. ASSERT_TRUE(svr.is_valid());
  13912. // Set up a handler to verify client certificate is present
  13913. bool client_cert_verified = false;
  13914. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13915. // Verify that client certificate was provided
  13916. client_cert_verified = true;
  13917. res.set_content("success", "text/plain");
  13918. });
  13919. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13920. auto se = detail::scope_exit([&] {
  13921. svr.stop();
  13922. t.join();
  13923. ASSERT_FALSE(svr.is_running());
  13924. });
  13925. svr.wait_until_ready();
  13926. // Client with certificate
  13927. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13928. cli.enable_server_certificate_verification(false);
  13929. cli.set_connection_timeout(30);
  13930. auto res = cli.Get("/test");
  13931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13932. ASSERT_EQ(StatusCode::OK_200, res->status);
  13933. ASSERT_TRUE(client_cert_verified);
  13934. EXPECT_EQ("success", res->body);
  13935. }
  13936. #endif
  13937. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13938. // backends
  13939. #ifdef CPPHTTPLIB_SSL_ENABLED
  13940. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13941. using namespace httplib::tls;
  13942. // Test that when client CA cert file is provided,
  13943. // the server properly requests and validates client certificates
  13944. // Create a server with client authentication
  13945. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13946. ASSERT_TRUE(svr.is_valid());
  13947. bool handler_called = false;
  13948. svr.Get("/test", [&](const Request &req, Response &res) {
  13949. handler_called = true;
  13950. // Verify that a client certificate was provided
  13951. auto cert = req.peer_cert();
  13952. ASSERT_TRUE(static_cast<bool>(cert));
  13953. // Get the issuer name
  13954. std::string issuer_str = cert.issuer_name();
  13955. ASSERT_FALSE(issuer_str.empty());
  13956. // The client certificate should be issued by our test CA
  13957. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13958. res.set_content("authenticated", "text/plain");
  13959. });
  13960. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13961. auto se = detail::scope_exit([&] {
  13962. svr.stop();
  13963. t.join();
  13964. ASSERT_FALSE(svr.is_running());
  13965. });
  13966. svr.wait_until_ready();
  13967. // Connect with a client certificate issued by the CA
  13968. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13969. cli.enable_server_certificate_verification(false);
  13970. cli.set_connection_timeout(30);
  13971. auto res = cli.Get("/test");
  13972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13973. ASSERT_EQ(StatusCode::OK_200, res->status);
  13974. ASSERT_TRUE(handler_called);
  13975. EXPECT_EQ("authenticated", res->body);
  13976. }
  13977. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13978. using namespace httplib::tls;
  13979. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13980. ASSERT_TRUE(svr.is_valid());
  13981. svr.Get("/test", [](const Request &, Response &res) {
  13982. res.set_content("ok", "text/plain");
  13983. });
  13984. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13985. auto se = detail::scope_exit([&] {
  13986. svr.stop();
  13987. t.join();
  13988. });
  13989. svr.wait_until_ready();
  13990. SSLClient cli(HOST, PORT);
  13991. cli.enable_server_certificate_verification(false);
  13992. cli.set_connection_timeout(30);
  13993. bool cert_checked = false;
  13994. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13995. if (ctx.cert) {
  13996. auto sans = ctx.sans();
  13997. // Test certificate may or may not have SANs - just verify the API
  13998. // works If SANs exist, verify the types are valid
  13999. for (const auto &san : sans) {
  14000. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14001. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14002. san.type == SanType::OTHER);
  14003. EXPECT_FALSE(san.value.empty());
  14004. }
  14005. cert_checked = true;
  14006. }
  14007. return true;
  14008. });
  14009. auto res = cli.Get("/test");
  14010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14011. EXPECT_TRUE(cert_checked);
  14012. }
  14013. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14014. using namespace httplib::tls;
  14015. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14016. ASSERT_TRUE(svr.is_valid());
  14017. svr.Get("/test", [](const Request &, Response &res) {
  14018. res.set_content("ok", "text/plain");
  14019. });
  14020. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14021. auto se = detail::scope_exit([&] {
  14022. svr.stop();
  14023. t.join();
  14024. });
  14025. svr.wait_until_ready();
  14026. SSLClient cli(HOST, PORT);
  14027. cli.enable_server_certificate_verification(false);
  14028. cli.set_connection_timeout(30);
  14029. bool validity_checked = false;
  14030. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14031. if (ctx.cert) {
  14032. time_t not_before = 0, not_after = 0;
  14033. bool result = ctx.validity(not_before, not_after);
  14034. EXPECT_TRUE(result);
  14035. // Verify that not_before < now < not_after for a valid cert
  14036. time_t now = time(nullptr);
  14037. EXPECT_LT(not_before, now);
  14038. EXPECT_GT(not_after, now);
  14039. validity_checked = true;
  14040. }
  14041. return true;
  14042. });
  14043. auto res = cli.Get("/test");
  14044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14045. EXPECT_TRUE(validity_checked);
  14046. }
  14047. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14048. using namespace httplib::tls;
  14049. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14050. ASSERT_TRUE(svr.is_valid());
  14051. svr.Get("/test", [](const Request &, Response &res) {
  14052. res.set_content("ok", "text/plain");
  14053. });
  14054. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14055. auto se = detail::scope_exit([&] {
  14056. svr.stop();
  14057. t.join();
  14058. });
  14059. svr.wait_until_ready();
  14060. SSLClient cli(HOST, PORT);
  14061. cli.enable_server_certificate_verification(false);
  14062. cli.set_connection_timeout(30);
  14063. bool serial_checked = false;
  14064. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14065. if (ctx.cert) {
  14066. std::string serial = ctx.serial();
  14067. EXPECT_FALSE(serial.empty());
  14068. // Serial should be a hex string
  14069. for (char c : serial) {
  14070. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14071. (c >= 'a' && c <= 'f'));
  14072. }
  14073. serial_checked = true;
  14074. }
  14075. return true;
  14076. });
  14077. auto res = cli.Get("/test");
  14078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14079. EXPECT_TRUE(serial_checked);
  14080. }
  14081. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14082. // Test 1: Valid CA file - no error should be recorded
  14083. {
  14084. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14085. CLIENT_CA_CERT_FILE);
  14086. ASSERT_TRUE(svr.is_valid());
  14087. // With valid setup, last_ssl_error should be 0
  14088. EXPECT_EQ(0, svr.ssl_last_error());
  14089. }
  14090. // Test 2: Invalid CA file content
  14091. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14092. {
  14093. // Create a temporary file with completely invalid content
  14094. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14095. {
  14096. std::ofstream ofs(temp_invalid_ca);
  14097. ofs << "This is not a certificate file at all\n";
  14098. ofs << "Just plain text content\n";
  14099. }
  14100. // Create server with invalid CA file
  14101. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14102. // Clean up temporary file
  14103. std::remove(temp_invalid_ca);
  14104. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14105. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14106. // Note: SSL_CTX_load_verify_locations typically fails first,
  14107. // but our error handling code path is still exercised
  14108. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14109. }
  14110. }
  14111. TEST(VerifyCallbackTest, VerifyContextFields) {
  14112. using namespace httplib::tls;
  14113. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14114. ASSERT_TRUE(svr.is_valid());
  14115. svr.Get("/test", [](const Request &, Response &res) {
  14116. res.set_content("ok", "text/plain");
  14117. });
  14118. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14119. auto se = detail::scope_exit([&] {
  14120. svr.stop();
  14121. t.join();
  14122. });
  14123. svr.wait_until_ready();
  14124. SSLClient cli(HOST, PORT);
  14125. cli.enable_server_certificate_verification(false);
  14126. cli.set_connection_timeout(30);
  14127. int callback_count = 0;
  14128. bool saw_leaf_cert = false;
  14129. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14130. if (ctx.cert) {
  14131. callback_count++;
  14132. // We should see at least one certificate (the leaf)
  14133. std::string cn = ctx.subject_cn();
  14134. if (!cn.empty()) { saw_leaf_cert = true; }
  14135. // Verify context fields are populated
  14136. EXPECT_NE(ctx.session, nullptr);
  14137. EXPECT_GE(ctx.depth, 0);
  14138. }
  14139. return true;
  14140. });
  14141. auto res = cli.Get("/test");
  14142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14143. EXPECT_GT(callback_count, 0);
  14144. EXPECT_TRUE(saw_leaf_cert);
  14145. }
  14146. // A verifier belongs to the client that set it, not to the thread that set it.
  14147. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14148. using namespace httplib::tls;
  14149. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14150. ASSERT_TRUE(svr.is_valid());
  14151. svr.Get("/test", [](const Request &, Response &res) {
  14152. res.set_content("ok", "text/plain");
  14153. });
  14154. auto port = svr.bind_to_any_port(HOST);
  14155. thread t([&]() { svr.listen_after_bind(); });
  14156. auto se = detail::scope_exit([&] {
  14157. svr.stop();
  14158. t.join();
  14159. });
  14160. svr.wait_until_ready();
  14161. auto rejecting_calls = 0;
  14162. SSLClient rejecting(HOST, port);
  14163. rejecting.enable_server_certificate_verification(false);
  14164. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14165. rejecting_calls++;
  14166. return false;
  14167. });
  14168. auto accepting_calls = 0;
  14169. SSLClient accepting(HOST, port);
  14170. accepting.enable_server_certificate_verification(false);
  14171. // Set on another thread than the requests below.
  14172. thread([&]() {
  14173. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14174. accepting_calls++;
  14175. return true;
  14176. });
  14177. }).join();
  14178. // Requested on another thread than the verifier was set on.
  14179. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14180. EXPECT_GT(rejecting_calls, 0);
  14181. auto res = accepting.Get("/test");
  14182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14183. EXPECT_GT(accepting_calls, 0);
  14184. }
  14185. // VerifyContext::session is the same handle the other tls:: functions take.
  14186. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14187. using namespace httplib::tls;
  14188. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14189. ASSERT_TRUE(svr.is_valid());
  14190. svr.Get("/test", [](const Request &, Response &res) {
  14191. res.set_content("ok", "text/plain");
  14192. });
  14193. auto port = svr.bind_to_any_port(HOST);
  14194. thread t([&]() { svr.listen_after_bind(); });
  14195. auto se = detail::scope_exit([&] {
  14196. svr.stop();
  14197. t.join();
  14198. });
  14199. svr.wait_until_ready();
  14200. SSLClient cli(HOST, port);
  14201. cli.enable_server_certificate_verification(false);
  14202. session_t verifier_session = nullptr;
  14203. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14204. verifier_session = ctx.session;
  14205. return true;
  14206. });
  14207. session_t session_verifier_session = nullptr;
  14208. cli.set_session_verifier([&](session_t session) {
  14209. session_verifier_session = session;
  14210. return SSLVerifierResponse::NoDecisionMade;
  14211. });
  14212. auto res = cli.Get("/test");
  14213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14214. EXPECT_NE(nullptr, verifier_session);
  14215. EXPECT_EQ(session_verifier_session, verifier_session);
  14216. }
  14217. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14218. using httplib::tls::TlsError;
  14219. // Test that verify_error_to_string returns empty for success
  14220. std::string success_str = TlsError::verify_error_to_string(0);
  14221. EXPECT_TRUE(success_str.empty());
  14222. // Test that verify_error_to_string returns non-empty for error codes
  14223. // Using a common error code (certificate expired)
  14224. std::string error_str =
  14225. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14226. EXPECT_FALSE(error_str.empty());
  14227. }
  14228. TEST(SessionVerifierTest, CertificateAccepted) {
  14229. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14230. ASSERT_TRUE(svr.is_valid());
  14231. svr.Get("/test", [](const Request &, Response &res) {
  14232. res.set_content("ok", "text/plain");
  14233. });
  14234. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14235. auto se = detail::scope_exit([&] {
  14236. svr.stop();
  14237. t.join();
  14238. });
  14239. svr.wait_until_ready();
  14240. SSLClient cli(HOST, PORT);
  14241. cli.enable_server_certificate_verification(false);
  14242. cli.set_connection_timeout(30);
  14243. bool callback_called = false;
  14244. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14245. EXPECT_NE(session, nullptr);
  14246. callback_called = true;
  14247. return SSLVerifierResponse::CertificateAccepted;
  14248. });
  14249. auto res = cli.Get("/test");
  14250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14251. EXPECT_EQ(200, res->status);
  14252. EXPECT_TRUE(callback_called);
  14253. }
  14254. TEST(SessionVerifierTest, CertificateRejected) {
  14255. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14256. ASSERT_TRUE(svr.is_valid());
  14257. svr.Get("/test", [](const Request &, Response &res) {
  14258. res.set_content("ok", "text/plain");
  14259. });
  14260. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14261. auto se = detail::scope_exit([&] {
  14262. svr.stop();
  14263. t.join();
  14264. });
  14265. svr.wait_until_ready();
  14266. SSLClient cli(HOST, PORT);
  14267. cli.enable_server_certificate_verification(false);
  14268. cli.set_connection_timeout(30);
  14269. bool callback_called = false;
  14270. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14271. EXPECT_NE(session, nullptr);
  14272. callback_called = true;
  14273. return SSLVerifierResponse::CertificateRejected;
  14274. });
  14275. auto res = cli.Get("/test");
  14276. EXPECT_FALSE(res);
  14277. EXPECT_TRUE(callback_called);
  14278. }
  14279. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14280. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14281. ASSERT_TRUE(svr.is_valid());
  14282. svr.Get("/test", [](const Request &, Response &res) {
  14283. res.set_content("ok", "text/plain");
  14284. });
  14285. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14286. auto se = detail::scope_exit([&] {
  14287. svr.stop();
  14288. t.join();
  14289. });
  14290. svr.wait_until_ready();
  14291. // NoDecisionMade with verification disabled should succeed (no default check)
  14292. SSLClient cli(HOST, PORT);
  14293. cli.enable_server_certificate_verification(false);
  14294. cli.set_connection_timeout(30);
  14295. bool callback_called = false;
  14296. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14297. EXPECT_NE(session, nullptr);
  14298. callback_called = true;
  14299. return SSLVerifierResponse::NoDecisionMade;
  14300. });
  14301. auto res = cli.Get("/test");
  14302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14303. EXPECT_EQ(200, res->status);
  14304. EXPECT_TRUE(callback_called);
  14305. }
  14306. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14307. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14308. ASSERT_TRUE(svr.is_valid());
  14309. svr.Get("/test", [](const Request &, Response &res) {
  14310. res.set_content("ok", "text/plain");
  14311. });
  14312. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14313. auto se = detail::scope_exit([&] {
  14314. svr.stop();
  14315. t.join();
  14316. });
  14317. svr.wait_until_ready();
  14318. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14319. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14320. // so we only check that the request fails, not whether the callback was
  14321. // called.
  14322. SSLClient cli(HOST, PORT);
  14323. cli.enable_server_certificate_verification(true);
  14324. cli.set_connection_timeout(30);
  14325. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14326. EXPECT_NE(session, nullptr);
  14327. return SSLVerifierResponse::NoDecisionMade;
  14328. });
  14329. auto res = cli.Get("/test");
  14330. EXPECT_FALSE(res);
  14331. }
  14332. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14333. // Test SSL server using PemMemory constructor with client CA certificates
  14334. // Read PEM files
  14335. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14336. read_file(SERVER_CERT_FILE, server_cert_pem);
  14337. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14338. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14339. // Create SSLServer with PemMemory constructor including client CA
  14340. SSLServer::PemMemory server_pem = {
  14341. server_cert_pem.c_str(),
  14342. server_cert_pem.size(),
  14343. server_key_pem.c_str(),
  14344. server_key_pem.size(),
  14345. client_ca_pem.c_str(),
  14346. client_ca_pem.size(),
  14347. nullptr // no password for server key
  14348. };
  14349. SSLServer svr(server_pem);
  14350. ASSERT_TRUE(svr.is_valid());
  14351. // No SSL error should be recorded for valid setup
  14352. EXPECT_EQ(0, svr.ssl_last_error());
  14353. // Set up server endpoints
  14354. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14355. res.set_content("ok", "text/plain");
  14356. });
  14357. // Start server in a thread
  14358. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14359. svr.wait_until_ready();
  14360. // Connect with client certificate (using constructor with paths)
  14361. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14362. cli.enable_server_certificate_verification(false);
  14363. auto res = cli.Get("/test-pem-ca");
  14364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14365. EXPECT_EQ(200, res->status);
  14366. EXPECT_EQ("ok", res->body);
  14367. svr.stop();
  14368. server_thread.join();
  14369. }
  14370. #endif
  14371. #ifdef _WIN32
  14372. TEST(CleanupTest, WSACleanup) {
  14373. int ret = WSACleanup();
  14374. ASSERT_EQ(0, ret);
  14375. }
  14376. #endif
  14377. #ifndef CPPHTTPLIB_SSL_ENABLED
  14378. TEST(NoSSLSupport, SimpleInterface) {
  14379. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14380. }
  14381. #endif
  14382. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14383. TEST(InvalidScheme, SimpleInterface) {
  14384. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14385. }
  14386. #endif
  14387. TEST(NoScheme, SimpleInterface) {
  14388. Client cli("yahoo.com:80");
  14389. ASSERT_TRUE(cli.is_valid());
  14390. }
  14391. TEST(SendAPI, SimpleInterface_Online) {
  14392. Client cli("http://yahoo.com");
  14393. Request req;
  14394. req.method = "GET";
  14395. req.path = "/";
  14396. auto res = cli.send(req);
  14397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14398. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14399. }
  14400. TEST(SendAPI, WithParamsInRequest) {
  14401. Server svr;
  14402. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14403. EXPECT_TRUE(req.has_param("test"));
  14404. EXPECT_EQ("test_value", req.get_param_value("test"));
  14405. });
  14406. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14407. auto se = detail::scope_exit([&] {
  14408. svr.stop();
  14409. t.join();
  14410. ASSERT_FALSE(svr.is_running());
  14411. });
  14412. svr.wait_until_ready();
  14413. Client cli(HOST, PORT);
  14414. {
  14415. Request req;
  14416. req.method = "GET";
  14417. req.path = "/";
  14418. req.params.emplace("test", "test_value");
  14419. auto res = cli.send(req);
  14420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14421. }
  14422. {
  14423. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14425. }
  14426. }
  14427. TEST(ClientImplMethods, GetSocketTest) {
  14428. httplib::Server svr;
  14429. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14430. res.status = StatusCode::OK_200;
  14431. });
  14432. auto port = svr.bind_to_any_port("127.0.0.1");
  14433. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14434. auto se = detail::scope_exit([&] {
  14435. svr.stop();
  14436. thread.join();
  14437. ASSERT_FALSE(svr.is_running());
  14438. });
  14439. svr.wait_until_ready();
  14440. {
  14441. httplib::Client cli("127.0.0.1", port);
  14442. cli.set_keep_alive(true);
  14443. // Use the behavior of cpp-httplib of opening the connection
  14444. // only when the first request happens. If that changes,
  14445. // this test would be obsolete.
  14446. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14447. // This also implicitly tests the server. But other tests would fail much
  14448. // earlier than this one to be considered.
  14449. auto res = cli.Get("/");
  14450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14451. EXPECT_EQ(StatusCode::OK_200, res->status);
  14452. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14453. }
  14454. }
  14455. #ifdef CPPHTTPLIB_SSL_ENABLED
  14456. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14457. Client cli("http://yahoo.com");
  14458. auto res = cli.Get("/");
  14459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14460. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14461. cli.set_follow_location(true);
  14462. res = cli.Get("/");
  14463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14464. EXPECT_EQ(StatusCode::OK_200, res->status);
  14465. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14466. }
  14467. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14468. Client cli("https://yahoo.com");
  14469. auto res = cli.Get("/");
  14470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14471. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14472. cli.set_follow_location(true);
  14473. res = cli.Get("/");
  14474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14475. EXPECT_EQ(StatusCode::OK_200, res->status);
  14476. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14477. }
  14478. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14479. Client cli("https://yahoo.com");
  14480. auto res = cli.Get("/");
  14481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14482. ASSERT_FALSE(!res);
  14483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14484. ASSERT_FALSE(res == nullptr);
  14485. ASSERT_TRUE(res != nullptr);
  14486. EXPECT_EQ(Error::Success, res.error());
  14487. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14488. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14489. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14490. cli.set_follow_location(true);
  14491. res = cli.Get("/");
  14492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14493. EXPECT_EQ(Error::Success, res.error());
  14494. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14495. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14496. EXPECT_EQ(StatusCode::OK_200, res->status);
  14497. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14498. }
  14499. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14500. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14501. Client cli("https://cdnjs.cloudflare.com");
  14502. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14503. Headers{{"Accept-Encoding", "br"}});
  14504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14505. EXPECT_EQ(StatusCode::OK_200, res->status);
  14506. EXPECT_EQ(287630U, res->body.size());
  14507. EXPECT_EQ("application/javascript; charset=utf-8",
  14508. res->get_header_value("Content-Type"));
  14509. }
  14510. #endif
  14511. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14512. #undef REDIR_HOST // Silence compiler warning
  14513. #define REDIR_HOST "https://httpbingo.org"
  14514. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14515. Client cli(REDIR_HOST);
  14516. cli.set_follow_location(true);
  14517. auto res =
  14518. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14520. EXPECT_EQ(StatusCode::OK_200, res->status);
  14521. }
  14522. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14523. Client cli(REDIR_HOST);
  14524. cli.set_follow_location(true);
  14525. Params params;
  14526. params.emplace("url", "http://example.com");
  14527. params.emplace("status_code", "302");
  14528. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14530. EXPECT_EQ(StatusCode::OK_200, res->status);
  14531. }
  14532. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14533. Client cli(REDIR_HOST);
  14534. cli.set_follow_location(true);
  14535. Params params;
  14536. params.emplace("url", "http://example.com");
  14537. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14539. EXPECT_EQ(StatusCode::OK_200, res->status);
  14540. }
  14541. TEST(HttpToHttpsRedirectTest, CertFile) {
  14542. auto ssl_port = PORT + 1;
  14543. Server svr;
  14544. ASSERT_TRUE(svr.is_valid());
  14545. svr.Get("/index", [&](const Request &, Response &res) {
  14546. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14547. "/index");
  14548. svr.stop();
  14549. });
  14550. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14551. ASSERT_TRUE(ssl_svr.is_valid());
  14552. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14553. res.set_content("test", "text/plain");
  14554. ssl_svr.stop();
  14555. });
  14556. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14557. thread t2 =
  14558. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14559. auto se = detail::scope_exit([&] {
  14560. t2.join();
  14561. t.join();
  14562. ASSERT_FALSE(svr.is_running());
  14563. });
  14564. svr.wait_until_ready();
  14565. ssl_svr.wait_until_ready();
  14566. Client cli("127.0.0.1", PORT);
  14567. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14568. cli.enable_server_certificate_verification(true);
  14569. cli.set_follow_location(true);
  14570. cli.set_connection_timeout(30);
  14571. auto res = cli.Get("/index");
  14572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14573. ASSERT_EQ(StatusCode::OK_200, res->status);
  14574. }
  14575. TEST(SSLClientRedirectTest, CertFile) {
  14576. auto ssl_port = PORT + 1;
  14577. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14578. ASSERT_TRUE(ssl_svr1.is_valid());
  14579. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14580. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14581. "/index");
  14582. ssl_svr1.stop();
  14583. });
  14584. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14585. ASSERT_TRUE(ssl_svr2.is_valid());
  14586. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14587. res.set_content("test", "text/plain");
  14588. ssl_svr2.stop();
  14589. });
  14590. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14591. thread t2 =
  14592. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14593. auto se = detail::scope_exit([&] {
  14594. t2.join();
  14595. t.join();
  14596. ASSERT_FALSE(ssl_svr1.is_running());
  14597. });
  14598. ssl_svr1.wait_until_ready();
  14599. ssl_svr2.wait_until_ready();
  14600. SSLClient cli("127.0.0.1", PORT);
  14601. std::string cert;
  14602. read_file(SERVER_CERT2_FILE, cert);
  14603. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14604. cli.enable_server_certificate_verification(true);
  14605. cli.set_follow_location(true);
  14606. cli.set_connection_timeout(30);
  14607. auto res = cli.Get("/index");
  14608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14609. ASSERT_EQ(StatusCode::OK_200, res->status);
  14610. }
  14611. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14612. // another port, so the client follows it with a new client.
  14613. static Result GetThroughTlsRedirectToDifferentPort(
  14614. const std::function<void(SSLClient &)> &setup,
  14615. const char *target_cert = SERVER_CERT2_FILE,
  14616. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  14617. auto ssl_port = PORT + 1;
  14618. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14619. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14620. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14621. "/index");
  14622. });
  14623. SSLServer ssl_svr2(target_cert, target_key);
  14624. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14625. res.set_content("test", "text/plain");
  14626. });
  14627. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14628. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14629. auto se = detail::scope_exit([&] {
  14630. ssl_svr2.stop();
  14631. ssl_svr1.stop();
  14632. t2.join();
  14633. t.join();
  14634. });
  14635. ssl_svr1.wait_until_ready();
  14636. ssl_svr2.wait_until_ready();
  14637. SSLClient cli("127.0.0.1", PORT);
  14638. cli.set_follow_location(true);
  14639. cli.set_connection_timeout(30);
  14640. setup(cli);
  14641. return cli.Get("/index");
  14642. }
  14643. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14644. auto calls = 0;
  14645. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14646. cli.enable_server_certificate_verification(false);
  14647. // Accept the first server only.
  14648. cli.set_session_verifier([&](tls::session_t) {
  14649. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14650. : SSLVerifierResponse::CertificateRejected;
  14651. });
  14652. });
  14653. EXPECT_FALSE(res);
  14654. EXPECT_EQ(2, calls);
  14655. }
  14656. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14657. std::string pinned;
  14658. auto res = GetThroughTlsRedirectToDifferentPort(
  14659. [&](SSLClient &cli) {
  14660. cli.enable_server_certificate_verification(false);
  14661. // Pin the first certificate seen.
  14662. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14663. if (pinned.empty()) { pinned = ctx.serial(); }
  14664. return ctx.serial() == pinned;
  14665. });
  14666. },
  14667. // A certificate other than the first server's.
  14668. SERVER_CERT_FILE);
  14669. EXPECT_FALSE(res);
  14670. EXPECT_FALSE(pinned.empty());
  14671. }
  14672. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14673. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14674. std::string cert;
  14675. read_file(SERVER_CERT2_FILE, cert);
  14676. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14677. });
  14678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14679. EXPECT_EQ(StatusCode::OK_200, res->status);
  14680. }
  14681. // The target's certificate is signed by the root CA, which the first server's
  14682. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  14683. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  14684. auto res = GetThroughTlsRedirectToDifferentPort(
  14685. [](SSLClient &cli) {
  14686. std::string root_ca, cert;
  14687. read_file(CLIENT_CA_CERT_FILE, root_ca);
  14688. read_file(SERVER_CERT2_FILE, cert);
  14689. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  14690. cli.load_ca_cert_store(cert.data(), cert.size());
  14691. cli.enable_server_hostname_verification(false);
  14692. },
  14693. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14695. EXPECT_EQ(StatusCode::OK_200, res->status);
  14696. }
  14697. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  14698. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  14699. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  14700. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  14701. auto res = GetThroughTlsRedirectToDifferentPort(
  14702. [](SSLClient &cli) {
  14703. std::string root_ca, cert;
  14704. read_file(CLIENT_CA_CERT_FILE, root_ca);
  14705. read_file(SERVER_CERT2_FILE, cert);
  14706. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  14707. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14708. cli.enable_server_hostname_verification(false);
  14709. },
  14710. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14711. ASSERT_FALSE(res);
  14712. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14713. }
  14714. #endif
  14715. #endif
  14716. #ifdef CPPHTTPLIB_SSL_ENABLED
  14717. // Test that set_ca_cert_store() skips system certs (consistent with
  14718. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  14719. // should be trusted - system certs should NOT be loaded.
  14720. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  14721. // Load a specific cert that is NOT a system CA cert
  14722. std::string cert;
  14723. read_file(SERVER_CERT2_FILE, cert);
  14724. SSLClient cli("google.com");
  14725. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14726. cli.enable_server_certificate_verification(true);
  14727. // This should FAIL because:
  14728. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  14729. // 2. System certs should NOT be loaded when custom store is set
  14730. // If system certs WERE loaded, this would succeed
  14731. auto res = cli.Get("/");
  14732. ASSERT_FALSE(res);
  14733. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14734. }
  14735. // Same as above, but through the native store handle path. Regression test:
  14736. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  14737. // merged system certs into the user-provided store.
  14738. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  14739. std::string cert;
  14740. read_file(SERVER_CERT2_FILE, cert);
  14741. SSLClient cli("google.com");
  14742. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14743. cli.enable_server_certificate_verification(true);
  14744. auto res = cli.Get("/");
  14745. ASSERT_FALSE(res);
  14746. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14747. }
  14748. // A custom store set via the native handle must still verify a server whose
  14749. // cert it does contain.
  14750. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  14751. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14752. ASSERT_TRUE(svr.is_valid());
  14753. svr.Get("/test", [&](const Request &, Response &res) {
  14754. res.set_content("test", "text/plain");
  14755. });
  14756. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14757. auto se = detail::scope_exit([&] {
  14758. svr.stop();
  14759. t.join();
  14760. ASSERT_FALSE(svr.is_running());
  14761. });
  14762. svr.wait_until_ready();
  14763. SSLClient cli("127.0.0.1", PORT);
  14764. std::string cert;
  14765. read_file(SERVER_CERT2_FILE, cert);
  14766. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14767. cli.enable_server_certificate_verification(true);
  14768. cli.set_connection_timeout(30);
  14769. auto res = cli.Get("/test");
  14770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14771. ASSERT_EQ(StatusCode::OK_200, res->status);
  14772. }
  14773. // CA certs loaded through the universal Client must be transferred to the
  14774. // client created internally for following an HTTPS redirect. Regression test:
  14775. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  14776. // the CA data for redirect transfer.
  14777. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  14778. auto ssl_port = PORT + 1;
  14779. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14780. ASSERT_TRUE(ssl_svr1.is_valid());
  14781. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14782. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14783. "/index");
  14784. });
  14785. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14786. ASSERT_TRUE(ssl_svr2.is_valid());
  14787. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14788. res.set_content("test", "text/plain");
  14789. });
  14790. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14791. thread t2 =
  14792. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14793. auto se = detail::scope_exit([&] {
  14794. ssl_svr2.stop();
  14795. ssl_svr1.stop();
  14796. t2.join();
  14797. t.join();
  14798. ASSERT_FALSE(ssl_svr1.is_running());
  14799. });
  14800. ssl_svr1.wait_until_ready();
  14801. ssl_svr2.wait_until_ready();
  14802. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14803. std::string cert;
  14804. read_file(SERVER_CERT2_FILE, cert);
  14805. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14806. cli.enable_server_certificate_verification(true);
  14807. cli.set_follow_location(true);
  14808. cli.set_connection_timeout(30);
  14809. auto res = cli.Get("/index");
  14810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14811. ASSERT_EQ(StatusCode::OK_200, res->status);
  14812. }
  14813. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14814. // so a host signed by a system CA verifies even though a custom CA is set
  14815. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14816. std::string cert;
  14817. read_file(SERVER_CERT2_FILE, cert);
  14818. SSLClient cli("google.com");
  14819. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14820. cli.enable_system_ca(true);
  14821. cli.enable_server_certificate_verification(true);
  14822. auto res = cli.Get("/");
  14823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14824. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14825. }
  14826. // The custom CA remains effective when combined with the system CA
  14827. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14828. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14829. ASSERT_TRUE(svr.is_valid());
  14830. svr.Get("/test", [&](const Request &, Response &res) {
  14831. res.set_content("test", "text/plain");
  14832. });
  14833. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14834. auto se = detail::scope_exit([&] {
  14835. svr.stop();
  14836. t.join();
  14837. ASSERT_FALSE(svr.is_running());
  14838. });
  14839. svr.wait_until_ready();
  14840. SSLClient cli("127.0.0.1", PORT);
  14841. std::string cert;
  14842. read_file(SERVER_CERT2_FILE, cert);
  14843. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14844. cli.enable_system_ca(true);
  14845. cli.enable_server_certificate_verification(true);
  14846. cli.set_connection_timeout(30);
  14847. auto res = cli.Get("/test");
  14848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14849. ASSERT_EQ(StatusCode::OK_200, res->status);
  14850. }
  14851. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14852. // skip chain verification entirely (only the certificate identity was
  14853. // checked), so a server presenting an untrusted certificate with a matching
  14854. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14855. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14856. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14857. ASSERT_TRUE(svr.is_valid());
  14858. svr.Get("/test", [&](const Request &, Response &res) {
  14859. res.set_content("test", "text/plain");
  14860. });
  14861. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14862. auto se = detail::scope_exit([&] {
  14863. svr.stop();
  14864. t.join();
  14865. ASSERT_FALSE(svr.is_running());
  14866. });
  14867. svr.wait_until_ready();
  14868. SSLClient cli("127.0.0.1", PORT);
  14869. std::string cert;
  14870. // A trusted CA that did not sign the server certificate. The server cert
  14871. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14872. // this connection.
  14873. read_file(CLIENT_CA_CERT_FILE, cert);
  14874. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14875. cli.enable_server_certificate_verification(true);
  14876. cli.set_connection_timeout(30);
  14877. auto res = cli.Get("/test");
  14878. ASSERT_FALSE(res);
  14879. }
  14880. // enable_system_ca(false) prevents system CA loading entirely
  14881. TEST(SSLClientTest, DisableSystemCa_Online) {
  14882. SSLClient cli("google.com");
  14883. cli.enable_system_ca(false);
  14884. cli.enable_server_certificate_verification(true);
  14885. auto res = cli.Get("/");
  14886. ASSERT_FALSE(res);
  14887. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14888. // itself when the CA chain is empty
  14889. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14890. res.error() == Error::SSLConnection);
  14891. }
  14892. // The universal Client forwards enable_system_ca()
  14893. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14894. std::string cert;
  14895. read_file(SERVER_CERT2_FILE, cert);
  14896. Client cli("https://google.com");
  14897. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14898. cli.enable_system_ca(true);
  14899. cli.enable_server_certificate_verification(true);
  14900. auto res = cli.Get("/");
  14901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14902. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14903. }
  14904. // The system CA policy must carry over to the client created internally for
  14905. // following a cross-host HTTPS redirect
  14906. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14907. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14908. ASSERT_TRUE(svr.is_valid());
  14909. svr.Get("/index", [&](const Request &, Response &res) {
  14910. res.set_redirect("https://www.google.com/");
  14911. });
  14912. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14913. auto se = detail::scope_exit([&] {
  14914. svr.stop();
  14915. t.join();
  14916. ASSERT_FALSE(svr.is_running());
  14917. });
  14918. svr.wait_until_ready();
  14919. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14920. std::string cert;
  14921. read_file(SERVER_CERT2_FILE, cert);
  14922. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14923. cli.enable_system_ca(true);
  14924. cli.enable_server_certificate_verification(true);
  14925. cli.set_follow_location(true);
  14926. cli.set_connection_timeout(30);
  14927. // Receiving any response proves the redirect client completed the TLS
  14928. // handshake with a system-CA-signed host
  14929. auto res = cli.Get("/index");
  14930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14931. }
  14932. TEST(MultipartFormDataTest, LargeData) {
  14933. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14934. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14935. const ContentReader &content_reader) {
  14936. if (req.is_multipart_form_data()) {
  14937. std::vector<FormData> items;
  14938. content_reader(
  14939. [&](const FormData &file) {
  14940. items.push_back(file);
  14941. return true;
  14942. },
  14943. [&](const char *data, size_t data_length) {
  14944. items.back().content.append(data, data_length);
  14945. return true;
  14946. });
  14947. EXPECT_TRUE(std::string(items[0].name) == "document");
  14948. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14949. EXPECT_TRUE(items[0].filename == "2MB_data");
  14950. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14951. EXPECT_TRUE(items[1].name == "hello");
  14952. EXPECT_TRUE(items[1].content == "world");
  14953. EXPECT_TRUE(items[1].filename == "");
  14954. EXPECT_TRUE(items[1].content_type == "");
  14955. } else {
  14956. std::string body;
  14957. content_reader([&](const char *data, size_t data_length) {
  14958. body.append(data, data_length);
  14959. return true;
  14960. });
  14961. }
  14962. });
  14963. auto port = svr.bind_to_any_port(HOST);
  14964. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14965. auto se = detail::scope_exit([&] {
  14966. svr.stop();
  14967. t.join();
  14968. ASSERT_FALSE(svr.is_running());
  14969. });
  14970. svr.wait_until_ready();
  14971. {
  14972. std::string data(1024 * 1024 * 2, '.');
  14973. std::stringstream buffer;
  14974. buffer << data;
  14975. SSLClient cli(HOST, port);
  14976. cli.enable_server_certificate_verification(false);
  14977. UploadFormDataItems items{
  14978. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14979. {"hello", "world", "", ""},
  14980. };
  14981. auto res = cli.Post("/post", items);
  14982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14983. ASSERT_EQ(StatusCode::OK_200, res->status);
  14984. }
  14985. }
  14986. TEST(MultipartFormDataTest, DataProviderItems) {
  14987. std::random_device seed_gen;
  14988. std::mt19937 random(seed_gen());
  14989. std::string rand1;
  14990. rand1.resize(1000);
  14991. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14992. std::string rand2;
  14993. rand2.resize(3000);
  14994. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14995. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14996. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14997. const ContentReader &content_reader) {
  14998. ASSERT_FALSE(req.is_multipart_form_data());
  14999. std::string body;
  15000. content_reader([&](const char *data, size_t data_length) {
  15001. body.append(data, data_length);
  15002. return true;
  15003. });
  15004. EXPECT_EQ(body, "");
  15005. });
  15006. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15007. const ContentReader &content_reader) {
  15008. ASSERT_TRUE(req.is_multipart_form_data());
  15009. std::vector<FormData> items;
  15010. content_reader(
  15011. [&](const FormData &file) {
  15012. items.push_back(file);
  15013. return true;
  15014. },
  15015. [&](const char *data, size_t data_length) {
  15016. items.back().content.append(data, data_length);
  15017. return true;
  15018. });
  15019. ASSERT_TRUE(items.size() == 2);
  15020. EXPECT_EQ(std::string(items[0].name), "name1");
  15021. EXPECT_EQ(items[0].content, "Testing123");
  15022. EXPECT_EQ(items[0].filename, "filename1");
  15023. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15024. EXPECT_EQ(items[1].name, "name2");
  15025. EXPECT_EQ(items[1].content, "Testing456");
  15026. EXPECT_EQ(items[1].filename, "");
  15027. EXPECT_EQ(items[1].content_type, "");
  15028. });
  15029. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15030. const ContentReader &content_reader) {
  15031. ASSERT_TRUE(req.is_multipart_form_data());
  15032. std::vector<FormData> items;
  15033. content_reader(
  15034. [&](const FormData &file) {
  15035. items.push_back(file);
  15036. return true;
  15037. },
  15038. [&](const char *data, size_t data_length) {
  15039. items.back().content.append(data, data_length);
  15040. return true;
  15041. });
  15042. ASSERT_TRUE(items.size() == 2);
  15043. EXPECT_EQ(items[0].name, "name3");
  15044. EXPECT_EQ(items[0].content, rand1);
  15045. EXPECT_EQ(items[0].filename, "filename3");
  15046. EXPECT_EQ(items[0].content_type, "");
  15047. EXPECT_EQ(items[1].name, "name4");
  15048. EXPECT_EQ(items[1].content, rand2);
  15049. EXPECT_EQ(items[1].filename, "filename4");
  15050. EXPECT_EQ(items[1].content_type, "");
  15051. });
  15052. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15053. const ContentReader &content_reader) {
  15054. ASSERT_TRUE(req.is_multipart_form_data());
  15055. std::vector<FormData> items;
  15056. content_reader(
  15057. [&](const FormData &file) {
  15058. items.push_back(file);
  15059. return true;
  15060. },
  15061. [&](const char *data, size_t data_length) {
  15062. items.back().content.append(data, data_length);
  15063. return true;
  15064. });
  15065. ASSERT_TRUE(items.size() == 4);
  15066. EXPECT_EQ(std::string(items[0].name), "name1");
  15067. EXPECT_EQ(items[0].content, "Testing123");
  15068. EXPECT_EQ(items[0].filename, "filename1");
  15069. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15070. EXPECT_EQ(items[1].name, "name2");
  15071. EXPECT_EQ(items[1].content, "Testing456");
  15072. EXPECT_EQ(items[1].filename, "");
  15073. EXPECT_EQ(items[1].content_type, "");
  15074. EXPECT_EQ(items[2].name, "name3");
  15075. EXPECT_EQ(items[2].content, rand1);
  15076. EXPECT_EQ(items[2].filename, "filename3");
  15077. EXPECT_EQ(items[2].content_type, "");
  15078. EXPECT_EQ(items[3].name, "name4");
  15079. EXPECT_EQ(items[3].content, rand2);
  15080. EXPECT_EQ(items[3].filename, "filename4");
  15081. EXPECT_EQ(items[3].content_type, "");
  15082. });
  15083. auto port = svr.bind_to_any_port("localhost");
  15084. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15085. auto se = detail::scope_exit([&] {
  15086. svr.stop();
  15087. t.join();
  15088. ASSERT_FALSE(svr.is_running());
  15089. });
  15090. svr.wait_until_ready();
  15091. {
  15092. SSLClient cli("localhost", port);
  15093. cli.enable_server_certificate_verification(false);
  15094. UploadFormDataItems items{
  15095. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15096. {"name2", "Testing456", "", ""}, // not a file
  15097. };
  15098. {
  15099. auto res = cli.Post("/post-none", {}, {}, {});
  15100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15101. ASSERT_EQ(StatusCode::OK_200, res->status);
  15102. }
  15103. FormDataProviderItems providers;
  15104. {
  15105. auto res =
  15106. cli.Post("/post-items", {}, items, providers); // empty providers
  15107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15108. ASSERT_EQ(StatusCode::OK_200, res->status);
  15109. }
  15110. providers.push_back({"name3",
  15111. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15112. // test the offset is given correctly at each step
  15113. if (!offset)
  15114. sink.os.write(rand1.data(), 30);
  15115. else if (offset == 30)
  15116. sink.os.write(rand1.data() + 30, 300);
  15117. else if (offset == 330)
  15118. sink.os.write(rand1.data() + 330, 670);
  15119. else if (offset == rand1.size())
  15120. sink.done();
  15121. return true;
  15122. },
  15123. "filename3",
  15124. {}});
  15125. providers.push_back({"name4",
  15126. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15127. // test the offset is given correctly at each step
  15128. if (!offset)
  15129. sink.os.write(rand2.data(), 2000);
  15130. else if (offset == 2000)
  15131. sink.os.write(rand2.data() + 2000, 1);
  15132. else if (offset == 2001)
  15133. sink.os.write(rand2.data() + 2001, 999);
  15134. else if (offset == rand2.size())
  15135. sink.done();
  15136. return true;
  15137. },
  15138. "filename4",
  15139. {}});
  15140. {
  15141. auto res = cli.Post("/post-providers", {}, {}, providers);
  15142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15143. ASSERT_EQ(StatusCode::OK_200, res->status);
  15144. }
  15145. {
  15146. auto res = cli.Post("/post-both", {}, items, providers);
  15147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15148. ASSERT_EQ(StatusCode::OK_200, res->status);
  15149. }
  15150. }
  15151. }
  15152. TEST(MultipartFormDataTest, BadHeader) {
  15153. Server svr;
  15154. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15155. res.set_content("ok", "text/plain");
  15156. });
  15157. thread t = thread([&] { svr.listen(HOST, PORT); });
  15158. auto se = detail::scope_exit([&] {
  15159. svr.stop();
  15160. t.join();
  15161. ASSERT_FALSE(svr.is_running());
  15162. });
  15163. svr.wait_until_ready();
  15164. const std::string body =
  15165. "This is the preamble. It is to be ignored, though it\r\n"
  15166. "is a handy place for composition agents to include an\r\n"
  15167. "explanatory note to non-MIME conformant readers.\r\n"
  15168. "\r\n"
  15169. "\r\n"
  15170. "--simple boundary\r\n"
  15171. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15172. ": BAD...\r\n"
  15173. "\r\n"
  15174. "value1\r\n"
  15175. "--simple boundary\r\n"
  15176. "Content-Disposition: form-data; name=\"field2\"; "
  15177. "filename=\"example.txt\"\r\n"
  15178. "\r\n"
  15179. "value2\r\n"
  15180. "--simple boundary--\r\n"
  15181. "This is the epilogue. It is also to be ignored.\r\n";
  15182. std::string content_type =
  15183. R"(multipart/form-data; boundary="simple boundary")";
  15184. Client cli(HOST, PORT);
  15185. auto res = cli.Post("/post", body, content_type.c_str());
  15186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15187. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15188. }
  15189. TEST(MultipartFormDataTest, WithPreamble) {
  15190. Server svr;
  15191. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15192. res.set_content("ok", "text/plain");
  15193. });
  15194. thread t = thread([&] { svr.listen(HOST, PORT); });
  15195. auto se = detail::scope_exit([&] {
  15196. svr.stop();
  15197. t.join();
  15198. ASSERT_FALSE(svr.is_running());
  15199. });
  15200. svr.wait_until_ready();
  15201. const std::string body =
  15202. "This is the preamble. It is to be ignored, though it\r\n"
  15203. "is a handy place for composition agents to include an\r\n"
  15204. "explanatory note to non-MIME conformant readers.\r\n"
  15205. "\r\n"
  15206. "\r\n"
  15207. "--simple boundary\r\n"
  15208. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15209. "\r\n"
  15210. "value1\r\n"
  15211. "--simple boundary\r\n"
  15212. "Content-Disposition: form-data; name=\"field2\"; "
  15213. "filename=\"example.txt\"\r\n"
  15214. "\r\n"
  15215. "value2\r\n"
  15216. "--simple boundary--\r\n"
  15217. "This is the epilogue. It is also to be ignored.\r\n";
  15218. std::string content_type =
  15219. R"(multipart/form-data; boundary="simple boundary")";
  15220. Client cli(HOST, PORT);
  15221. auto res = cli.Post("/post", body, content_type.c_str());
  15222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15223. EXPECT_EQ(StatusCode::OK_200, res->status);
  15224. }
  15225. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15226. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15227. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15228. const ContentReader &content_reader) {
  15229. if (req.is_multipart_form_data()) {
  15230. std::vector<FormData> items;
  15231. content_reader(
  15232. [&](const FormData &file) {
  15233. items.push_back(file);
  15234. return true;
  15235. },
  15236. [&](const char *data, size_t data_length) {
  15237. items.back().content.append(data, data_length);
  15238. return true;
  15239. });
  15240. EXPECT_TRUE(std::string(items[0].name) == "document");
  15241. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15242. EXPECT_TRUE(items[0].filename == "2MB_data");
  15243. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15244. EXPECT_TRUE(items[1].name == "hello");
  15245. EXPECT_TRUE(items[1].content == "world");
  15246. EXPECT_TRUE(items[1].filename == "");
  15247. EXPECT_TRUE(items[1].content_type == "");
  15248. } else {
  15249. std::string body;
  15250. content_reader([&](const char *data, size_t data_length) {
  15251. body.append(data, data_length);
  15252. return true;
  15253. });
  15254. }
  15255. });
  15256. auto port = svr.bind_to_any_port("localhost");
  15257. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15258. auto se = detail::scope_exit([&] {
  15259. svr.stop();
  15260. t.join();
  15261. ASSERT_FALSE(svr.is_running());
  15262. });
  15263. svr.wait_until_ready();
  15264. {
  15265. std::string data(1024 * 1024 * 2, '.');
  15266. std::stringstream buffer;
  15267. buffer << data;
  15268. SSLClient cli("localhost", port);
  15269. cli.enable_server_certificate_verification(false);
  15270. UploadFormDataItems items{
  15271. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15272. {"hello", "world", "", ""},
  15273. };
  15274. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15276. ASSERT_EQ(StatusCode::OK_200, res->status);
  15277. }
  15278. }
  15279. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15280. std::string data(1024 * 1024 * 2, '&');
  15281. std::stringstream buffer;
  15282. buffer << data;
  15283. Client cli("https://localhost:8080");
  15284. UploadFormDataItems items{
  15285. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15286. {"hello", "world", "", ""},
  15287. };
  15288. for (const char &c : " \t\r\n") {
  15289. auto res =
  15290. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15291. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15292. ASSERT_FALSE(res);
  15293. }
  15294. }
  15295. TEST(MultipartFormDataTest, PutFormData) {
  15296. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15297. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15298. const ContentReader &content_reader) {
  15299. if (req.is_multipart_form_data()) {
  15300. std::vector<FormData> items;
  15301. content_reader(
  15302. [&](const FormData &file) {
  15303. items.push_back(file);
  15304. return true;
  15305. },
  15306. [&](const char *data, size_t data_length) {
  15307. items.back().content.append(data, data_length);
  15308. return true;
  15309. });
  15310. EXPECT_TRUE(std::string(items[0].name) == "document");
  15311. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15312. EXPECT_TRUE(items[0].filename == "2MB_data");
  15313. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15314. EXPECT_TRUE(items[1].name == "hello");
  15315. EXPECT_TRUE(items[1].content == "world");
  15316. EXPECT_TRUE(items[1].filename == "");
  15317. EXPECT_TRUE(items[1].content_type == "");
  15318. } else {
  15319. std::string body;
  15320. content_reader([&](const char *data, size_t data_length) {
  15321. body.append(data, data_length);
  15322. return true;
  15323. });
  15324. }
  15325. });
  15326. auto port = svr.bind_to_any_port("localhost");
  15327. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15328. auto se = detail::scope_exit([&] {
  15329. svr.stop();
  15330. t.join();
  15331. ASSERT_FALSE(svr.is_running());
  15332. });
  15333. svr.wait_until_ready();
  15334. {
  15335. std::string data(1024 * 1024 * 2, '&');
  15336. std::stringstream buffer;
  15337. buffer << data;
  15338. SSLClient cli("localhost", port);
  15339. cli.enable_server_certificate_verification(false);
  15340. UploadFormDataItems items{
  15341. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15342. {"hello", "world", "", ""},
  15343. };
  15344. auto res = cli.Put("/put", items);
  15345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15346. ASSERT_EQ(StatusCode::OK_200, res->status);
  15347. }
  15348. }
  15349. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15350. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15351. svr.Put("/put_customboundary",
  15352. [&](const Request &req, const Response & /*res*/,
  15353. const ContentReader &content_reader) {
  15354. if (req.is_multipart_form_data()) {
  15355. std::vector<FormData> items;
  15356. content_reader(
  15357. [&](const FormData &file) {
  15358. items.push_back(file);
  15359. return true;
  15360. },
  15361. [&](const char *data, size_t data_length) {
  15362. items.back().content.append(data, data_length);
  15363. return true;
  15364. });
  15365. EXPECT_TRUE(std::string(items[0].name) == "document");
  15366. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15367. EXPECT_TRUE(items[0].filename == "2MB_data");
  15368. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15369. EXPECT_TRUE(items[1].name == "hello");
  15370. EXPECT_TRUE(items[1].content == "world");
  15371. EXPECT_TRUE(items[1].filename == "");
  15372. EXPECT_TRUE(items[1].content_type == "");
  15373. } else {
  15374. std::string body;
  15375. content_reader([&](const char *data, size_t data_length) {
  15376. body.append(data, data_length);
  15377. return true;
  15378. });
  15379. }
  15380. });
  15381. auto port = svr.bind_to_any_port("localhost");
  15382. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15383. auto se = detail::scope_exit([&] {
  15384. svr.stop();
  15385. t.join();
  15386. ASSERT_FALSE(svr.is_running());
  15387. });
  15388. svr.wait_until_ready();
  15389. {
  15390. std::string data(1024 * 1024 * 2, '&');
  15391. std::stringstream buffer;
  15392. buffer << data;
  15393. SSLClient cli("localhost", port);
  15394. cli.enable_server_certificate_verification(false);
  15395. UploadFormDataItems items{
  15396. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15397. {"hello", "world", "", ""},
  15398. };
  15399. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15401. ASSERT_EQ(StatusCode::OK_200, res->status);
  15402. }
  15403. }
  15404. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15405. std::string data(1024 * 1024 * 2, '&');
  15406. std::stringstream buffer;
  15407. buffer << data;
  15408. Client cli("https://localhost:8080");
  15409. cli.enable_server_certificate_verification(false);
  15410. UploadFormDataItems items{
  15411. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15412. {"hello", "world", "", ""},
  15413. };
  15414. for (const char &c : " \t\r\n") {
  15415. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15416. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15417. ASSERT_FALSE(res);
  15418. }
  15419. }
  15420. TEST(MultipartFormDataTest, AlternateFilename) {
  15421. auto handled = false;
  15422. Server svr;
  15423. svr.Post("/test", [&](const Request &req, Response &res) {
  15424. ASSERT_EQ(2u, req.form.files.size());
  15425. ASSERT_EQ(1u, req.form.fields.size());
  15426. // Test files
  15427. const auto &file1 = req.form.get_file("file1");
  15428. ASSERT_EQ("file1", file1.name);
  15429. ASSERT_EQ("A.txt", file1.filename);
  15430. ASSERT_EQ("text/plain", file1.content_type);
  15431. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15432. const auto &file2 = req.form.get_file("file2");
  15433. ASSERT_EQ("file2", file2.name);
  15434. ASSERT_EQ("a.html", file2.filename);
  15435. ASSERT_EQ("text/html", file2.content_type);
  15436. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15437. file2.content);
  15438. // Test text field
  15439. const auto &text = req.form.get_field("text");
  15440. ASSERT_EQ("text default", text);
  15441. res.set_content("ok", "text/plain");
  15442. handled = true;
  15443. });
  15444. thread t = thread([&] { svr.listen(HOST, PORT); });
  15445. auto se = detail::scope_exit([&] {
  15446. svr.stop();
  15447. t.join();
  15448. ASSERT_FALSE(svr.is_running());
  15449. ASSERT_TRUE(handled);
  15450. });
  15451. svr.wait_until_ready();
  15452. auto req = "POST /test HTTP/1.1\r\n"
  15453. "Host: localhost\r\n"
  15454. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15455. "Content-Length: 399\r\n"
  15456. "\r\n"
  15457. "----------\r\n"
  15458. "Content-Disposition: form-data; name=\"text\"\r\n"
  15459. "\r\n"
  15460. "text default\r\n"
  15461. "----------\r\n"
  15462. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15463. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15464. "Content-Type: text/plain\r\n"
  15465. "\r\n"
  15466. "Content of a.txt.\r\n"
  15467. "\r\n"
  15468. "----------\r\n"
  15469. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  15470. "\"a.html\"\r\n"
  15471. "Content-Type: text/html\r\n"
  15472. "\r\n"
  15473. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  15474. "\r\n"
  15475. "------------\r\n";
  15476. ASSERT_TRUE(send_request(1, req));
  15477. }
  15478. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15479. auto handled = false;
  15480. Server svr;
  15481. svr.Post("/test", [&](const Request &req, Response &res) {
  15482. // Case-insensitive "utf-8''" prefix with a long value
  15483. const auto &file = req.form.get_file("file1");
  15484. ASSERT_EQ("file1", file.name);
  15485. // 8000 chars exercises both the Content-Disposition parser and the
  15486. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15487. // Prior to the fix, std::regex_match on this header would cause O(N)
  15488. // stack recursion in libstdc++, leading to SIGSEGV.
  15489. std::string expected_filename(8000, 'A');
  15490. ASSERT_EQ(expected_filename, file.filename);
  15491. res.set_content("ok", "text/plain");
  15492. handled = true;
  15493. });
  15494. thread t = thread([&] { svr.listen(HOST, PORT); });
  15495. auto se = detail::scope_exit([&] {
  15496. svr.stop();
  15497. t.join();
  15498. ASSERT_FALSE(svr.is_running());
  15499. ASSERT_TRUE(handled);
  15500. });
  15501. svr.wait_until_ready();
  15502. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15503. // Regression test for GHSA-qq6v-r583-3h69
  15504. std::string long_filename(8000, 'A');
  15505. std::string body = "----------\r\n"
  15506. "Content-Disposition: form-data; name=\"file1\"; "
  15507. "filename*=\"Utf-8''" +
  15508. long_filename +
  15509. "\"\r\n"
  15510. "\r\n"
  15511. "hello\r\n"
  15512. "------------\r\n";
  15513. auto req = "POST /test HTTP/1.1\r\n"
  15514. "Host: localhost\r\n"
  15515. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15516. "Content-Length: " +
  15517. std::to_string(body.size()) + "\r\n\r\n" + body;
  15518. ASSERT_TRUE(send_request(1, req));
  15519. }
  15520. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15521. auto handled = false;
  15522. Server svr;
  15523. svr.Post("/test", [&](const Request &req, Response &) {
  15524. ASSERT_EQ(2u, req.form.fields.size());
  15525. const auto &text1 = req.form.get_field("text1");
  15526. ASSERT_EQ("text1", text1);
  15527. const auto &text2 = req.form.get_field("text2");
  15528. ASSERT_EQ("text2", text2);
  15529. handled = true;
  15530. });
  15531. thread t = thread([&] { svr.listen(HOST, PORT); });
  15532. auto se = detail::scope_exit([&] {
  15533. svr.stop();
  15534. t.join();
  15535. ASSERT_FALSE(svr.is_running());
  15536. ASSERT_TRUE(handled);
  15537. });
  15538. svr.wait_until_ready();
  15539. auto req = "POST /test HTTP/1.1\r\n"
  15540. "Host: localhost\r\n"
  15541. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15542. "Content-Length: 146\r\n"
  15543. "\r\n----------\r\n"
  15544. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15545. "\r\n"
  15546. "text1"
  15547. "\r\n----------\r\n"
  15548. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15549. "\r\n"
  15550. "text2"
  15551. "\r\n------------";
  15552. std::string response;
  15553. ASSERT_TRUE(send_request(1, req, &response));
  15554. ASSERT_EQ("200", response.substr(9, 3));
  15555. }
  15556. TEST(MultipartFormDataTest, ContentLength) {
  15557. auto handled = false;
  15558. Server svr;
  15559. svr.Post("/test", [&](const Request &req, Response &) {
  15560. ASSERT_EQ(2u, req.form.fields.size());
  15561. const auto &text1 = req.form.get_field("text1");
  15562. ASSERT_EQ("text1", text1);
  15563. const auto &text2 = req.form.get_field("text2");
  15564. ASSERT_EQ("text2", text2);
  15565. handled = true;
  15566. });
  15567. thread t = thread([&] { svr.listen(HOST, PORT); });
  15568. auto se = detail::scope_exit([&] {
  15569. svr.stop();
  15570. t.join();
  15571. ASSERT_FALSE(svr.is_running());
  15572. ASSERT_TRUE(handled);
  15573. });
  15574. svr.wait_until_ready();
  15575. auto req = "POST /test HTTP/1.1\r\n"
  15576. "Host: localhost\r\n"
  15577. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15578. "Content-Length: 167\r\n"
  15579. "\r\n----------\r\n"
  15580. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15581. "Content-Length: 5\r\n"
  15582. "\r\n"
  15583. "text1"
  15584. "\r\n----------\r\n"
  15585. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15586. "\r\n"
  15587. "text2"
  15588. "\r\n------------\r\n";
  15589. std::string response;
  15590. ASSERT_TRUE(send_request(1, req, &response));
  15591. ASSERT_EQ("200", response.substr(9, 3));
  15592. }
  15593. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15594. auto handled = false;
  15595. Server svr;
  15596. svr.Post("/test", [&](const Request &req, Response &) {
  15597. ASSERT_EQ(2u, req.form.fields.size());
  15598. const auto &text1 = req.form.get_field("text1");
  15599. ASSERT_EQ("text1", text1);
  15600. // TODO: Add header access for text fields if needed
  15601. const auto &text2 = req.form.get_field("text2");
  15602. ASSERT_EQ("text2", text2);
  15603. // TODO: Header access for text fields needs to be implemented
  15604. // auto &headers = it->second.headers;
  15605. // ASSERT_EQ(3U, headers.size());
  15606. // auto custom_header = headers.find("x-whatever");
  15607. // ASSERT_TRUE(custom_header != headers.end());
  15608. // ASSERT_NE("customvalue", custom_header->second);
  15609. // ASSERT_EQ("CustomValue", custom_header->second);
  15610. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15611. handled = true;
  15612. });
  15613. thread t = thread([&] { svr.listen(HOST, PORT); });
  15614. auto se = detail::scope_exit([&] {
  15615. svr.stop();
  15616. t.join();
  15617. ASSERT_FALSE(svr.is_running());
  15618. ASSERT_TRUE(handled);
  15619. });
  15620. svr.wait_until_ready();
  15621. auto req = "POST /test HTTP/1.1\r\n"
  15622. "Host: localhost\r\n"
  15623. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15624. "Content-Length: 232\r\n"
  15625. "\r\n----------\r\n"
  15626. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15627. "Content-Length: 5\r\n"
  15628. "X-Test: 1\r\n"
  15629. "\r\n"
  15630. "text1"
  15631. "\r\n----------\r\n"
  15632. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15633. "Content-Type: text/plain\r\n"
  15634. "X-Whatever: CustomValue\r\n"
  15635. "\r\n"
  15636. "text2"
  15637. "\r\n------------\r\n"
  15638. "That should be disregarded. Not even read";
  15639. std::string response;
  15640. ASSERT_TRUE(send_request(1, req, &response));
  15641. ASSERT_EQ("200", response.substr(9, 3));
  15642. }
  15643. TEST(MultipartFormDataTest, LargeHeader) {
  15644. auto handled = false;
  15645. Server svr;
  15646. svr.Post("/test", [&](const Request &req, Response &) {
  15647. ASSERT_EQ(1u, req.form.fields.size());
  15648. const auto &text = req.form.get_field("name1");
  15649. ASSERT_EQ("text1", text);
  15650. handled = true;
  15651. });
  15652. thread t = thread([&] { svr.listen(HOST, PORT); });
  15653. auto se = detail::scope_exit([&] {
  15654. svr.stop();
  15655. t.join();
  15656. ASSERT_FALSE(svr.is_running());
  15657. ASSERT_TRUE(handled);
  15658. });
  15659. svr.wait_until_ready();
  15660. auto boundary = std::string("cpp-httplib-multipart-data");
  15661. std::string content = "--" + boundary +
  15662. "\r\n"
  15663. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15664. "\r\n"
  15665. "text1\r\n"
  15666. "--" +
  15667. boundary + "--\r\n";
  15668. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15669. "Host: localhost\r\n"
  15670. "Content-Type: multipart/form-data;boundary=" +
  15671. boundary +
  15672. "\r\n"
  15673. "Content-Length: " +
  15674. std::to_string(content.size()) +
  15675. "\r\n"
  15676. "Dummy-Header: ";
  15677. std::string header_suffix = "\r\n"
  15678. "\r\n";
  15679. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  15680. size_t header_dummy_size =
  15681. read_buff_size -
  15682. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  15683. auto header_dummy = std::string(header_dummy_size, '@');
  15684. auto req = header_prefix + header_dummy + header_suffix + content;
  15685. std::string response;
  15686. ASSERT_TRUE(send_request(1, req, &response));
  15687. ASSERT_EQ("200", response.substr(9, 3));
  15688. }
  15689. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  15690. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  15691. // (not chunked Transfer-Encoding) after the streaming refactor.
  15692. auto handled = false;
  15693. Server svr;
  15694. svr.Post("/upload", [&](const Request &req, Response &res) {
  15695. auto cl_it = req.headers.find("Content-Length");
  15696. EXPECT_TRUE(cl_it != req.headers.end());
  15697. auto te_it = req.headers.find("Transfer-Encoding");
  15698. EXPECT_TRUE(te_it == req.headers.end());
  15699. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15700. res.set_content("ok", "text/plain");
  15701. handled = true;
  15702. });
  15703. auto port = svr.bind_to_any_port(HOST);
  15704. auto t = thread([&] { svr.listen_after_bind(); });
  15705. auto se = detail::scope_exit([&] {
  15706. svr.stop();
  15707. t.join();
  15708. ASSERT_FALSE(svr.is_running());
  15709. ASSERT_TRUE(handled);
  15710. });
  15711. svr.wait_until_ready();
  15712. UploadFormDataItems items = {
  15713. {"field1", "hello", "", "text/plain"},
  15714. {"file1", "world", "test.txt", "application/octet-stream"},
  15715. };
  15716. Client cli(HOST, port);
  15717. auto res = cli.Post("/upload", {}, items);
  15718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15719. EXPECT_EQ(StatusCode::OK_200, res->status);
  15720. }
  15721. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  15722. // Verify that make_multipart_content_provider coalesces many small segments
  15723. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  15724. constexpr size_t kItemCount = 1000;
  15725. UploadFormDataItems items;
  15726. items.reserve(kItemCount);
  15727. for (size_t i = 0; i < kItemCount; i++) {
  15728. items.push_back(
  15729. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15730. }
  15731. const std::string boundary = "----test-boundary";
  15732. auto content_length = detail::get_multipart_content_length(items, boundary);
  15733. auto provider = detail::make_multipart_content_provider(items, boundary);
  15734. // Drive the provider the same way write_content_with_progress does
  15735. size_t write_count = 0;
  15736. size_t total_bytes = 0;
  15737. DataSink sink;
  15738. size_t offset = 0;
  15739. sink.write = [&](const char *d, size_t l) -> bool {
  15740. (void)d;
  15741. write_count++;
  15742. total_bytes += l;
  15743. offset += l;
  15744. return true;
  15745. };
  15746. sink.is_writable = []() -> bool { return true; };
  15747. while (offset < content_length) {
  15748. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  15749. }
  15750. EXPECT_EQ(content_length, total_bytes);
  15751. // The total number of segments is 3 * kItemCount + 1 = 3001.
  15752. // With buffering into 64KB blocks, write_count should be much smaller.
  15753. auto segment_count = 3 * kItemCount + 1;
  15754. EXPECT_LT(write_count, segment_count / 10);
  15755. }
  15756. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  15757. // Integration test: send many UploadFormDataItems and verify the server
  15758. // receives all of them correctly (#2410).
  15759. constexpr size_t kItemCount = 500;
  15760. auto handled = false;
  15761. Server svr;
  15762. svr.Post("/upload", [&](const Request &req, Response &res) {
  15763. EXPECT_EQ(kItemCount, req.form.fields.size());
  15764. for (size_t i = 0; i < kItemCount; i++) {
  15765. auto key = "field" + std::to_string(i);
  15766. auto val = "value" + std::to_string(i);
  15767. auto it = req.form.fields.find(key);
  15768. if (it != req.form.fields.end()) {
  15769. EXPECT_EQ(val, it->second.content);
  15770. } else {
  15771. ADD_FAILURE() << "Missing field: " << key;
  15772. }
  15773. }
  15774. res.set_content("ok", "text/plain");
  15775. handled = true;
  15776. });
  15777. auto port = svr.bind_to_any_port(HOST);
  15778. auto t = thread([&] { svr.listen_after_bind(); });
  15779. auto se = detail::scope_exit([&] {
  15780. svr.stop();
  15781. t.join();
  15782. ASSERT_FALSE(svr.is_running());
  15783. ASSERT_TRUE(handled);
  15784. });
  15785. svr.wait_until_ready();
  15786. UploadFormDataItems items;
  15787. items.reserve(kItemCount);
  15788. for (size_t i = 0; i < kItemCount; i++) {
  15789. items.push_back(
  15790. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15791. }
  15792. Client cli(HOST, port);
  15793. auto res = cli.Post("/upload", items);
  15794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15795. EXPECT_EQ(StatusCode::OK_200, res->status);
  15796. }
  15797. TEST(MultipartFormDataTest, MakeFileProvider) {
  15798. // Verify make_file_provider sends a file's contents correctly.
  15799. const std::string file_content(4096, 'Z');
  15800. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  15801. {
  15802. std::ofstream ofs(tmp_path, std::ios::binary);
  15803. ofs.write(file_content.data(),
  15804. static_cast<std::streamsize>(file_content.size()));
  15805. }
  15806. auto handled = false;
  15807. Server svr;
  15808. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  15809. const ContentReader &content_reader) {
  15810. ASSERT_TRUE(req.is_multipart_form_data());
  15811. std::vector<FormData> items;
  15812. content_reader(
  15813. [&](const FormData &file) {
  15814. items.push_back(file);
  15815. return true;
  15816. },
  15817. [&](const char *data, size_t data_length) {
  15818. items.back().content.append(data, data_length);
  15819. return true;
  15820. });
  15821. ASSERT_EQ(1u, items.size());
  15822. EXPECT_EQ("myfile", items[0].name);
  15823. EXPECT_EQ("data.bin", items[0].filename);
  15824. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15825. EXPECT_EQ(file_content, items[0].content);
  15826. handled = true;
  15827. });
  15828. auto port = svr.bind_to_any_port(HOST);
  15829. auto t = thread([&] { svr.listen_after_bind(); });
  15830. auto se = detail::scope_exit([&] {
  15831. svr.stop();
  15832. t.join();
  15833. ASSERT_FALSE(svr.is_running());
  15834. ASSERT_TRUE(handled);
  15835. std::remove(tmp_path.c_str());
  15836. });
  15837. svr.wait_until_ready();
  15838. FormDataProviderItems providers;
  15839. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15840. "application/octet-stream"));
  15841. Client cli(HOST, port);
  15842. auto res = cli.Post("/upload", {}, {}, providers);
  15843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15844. EXPECT_EQ(StatusCode::OK_200, res->status);
  15845. }
  15846. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15847. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15848. // (100) headers is rejected with a 400 Bad Request response.
  15849. Server svr;
  15850. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15851. res.set_content("ok", "text/plain");
  15852. });
  15853. thread t = thread([&] { svr.listen(HOST, PORT); });
  15854. auto se = detail::scope_exit([&] {
  15855. svr.stop();
  15856. t.join();
  15857. ASSERT_FALSE(svr.is_running());
  15858. });
  15859. svr.wait_until_ready();
  15860. // Build a multipart part with 101 custom headers (exceeding
  15861. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15862. std::stringstream body;
  15863. body << "--simpleboundary\r\n"
  15864. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15865. for (int i = 0; i < 101; i++) {
  15866. body << "X-Custom-Header-" << i << ": value\r\n";
  15867. }
  15868. body << "\r\n"
  15869. << "value1\r\n"
  15870. << "--simpleboundary--\r\n";
  15871. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15872. Client cli(HOST, PORT);
  15873. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15875. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15876. }
  15877. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15878. // A body that never contains the declared boundary must not be accumulated
  15879. // while the parser waits for it. Buffering it would also make every read
  15880. // rescan everything seen so far, which is quadratic in the body size.
  15881. Server svr;
  15882. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15883. res.set_content("ok", "text/plain");
  15884. });
  15885. auto port = svr.bind_to_any_port(HOST);
  15886. thread t = thread([&] { svr.listen_after_bind(); });
  15887. auto se = detail::scope_exit([&] {
  15888. svr.stop();
  15889. t.join();
  15890. ASSERT_FALSE(svr.is_running());
  15891. });
  15892. svr.wait_until_ready();
  15893. Client cli(HOST, port);
  15894. cli.set_read_timeout(60, 0);
  15895. cli.set_write_timeout(60, 0);
  15896. // '-' is the worst case: it matches the first character of the boundary, so
  15897. // every position has to be checked against it.
  15898. auto post_dashes = [&](size_t size) {
  15899. const std::string body(size, '-');
  15900. auto start = std::chrono::steady_clock::now();
  15901. auto res =
  15902. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15903. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15904. std::chrono::steady_clock::now() - start)
  15905. .count();
  15906. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15907. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15908. return ms;
  15909. };
  15910. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15911. // Windows.
  15912. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15913. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15914. // Comparing the two sizes rather than checking an absolute duration keeps
  15915. // this meaningful across build types and CI load, both of which move the
  15916. // absolute numbers by more than an order of magnitude. Four times the bytes
  15917. // costs about four times the time when parsing is linear, and about sixteen
  15918. // times when the body is buffered and rescanned.
  15919. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15920. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15921. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15922. << "ms, which suggests the body is being buffered and rescanned";
  15923. }
  15924. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15925. // A boundary can only be followed by CRLF or by "--", so anything else is
  15926. // malformed no matter what comes next. The parser must say so right away
  15927. // instead of buffering the rest of the declared body.
  15928. Server svr;
  15929. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15930. res.set_content("ok", "text/plain");
  15931. });
  15932. auto port = svr.bind_to_any_port(HOST);
  15933. thread t = thread([&] { svr.listen_after_bind(); });
  15934. auto se = detail::scope_exit([&] {
  15935. svr.stop();
  15936. t.join();
  15937. ASSERT_FALSE(svr.is_running());
  15938. });
  15939. svr.wait_until_ready();
  15940. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15941. // buffers instead of failing would still be waiting for the remaining bytes.
  15942. const std::string body = "--zzzz\r\n"
  15943. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15944. "\r\n"
  15945. "text1"
  15946. "\r\n--zzzzXX";
  15947. const std::string req = "POST /post HTTP/1.1\r\n"
  15948. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15949. "Content-Length: 1048576\r\n"
  15950. "\r\n" +
  15951. body;
  15952. std::string response;
  15953. ASSERT_TRUE(send_request(3, req, &response, port));
  15954. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15955. EXPECT_EQ("400", response.substr(9, 3));
  15956. }
  15957. // Posts a multipart body split into two writes, so that the server sees the
  15958. // split at whatever offset the caller chose, and expects the single "text1"
  15959. // field to come through.
  15960. static void expect_split_multipart_ok(const std::string &body1,
  15961. const std::string &body2) {
  15962. auto handled = false;
  15963. Server svr;
  15964. svr.Post("/post", [&](const Request &req, Response &) {
  15965. EXPECT_EQ(1u, req.form.fields.size());
  15966. EXPECT_EQ("text1", req.form.get_field("text1"));
  15967. handled = true;
  15968. });
  15969. auto port = svr.bind_to_any_port(HOST);
  15970. thread t = thread([&] { svr.listen_after_bind(); });
  15971. auto se = detail::scope_exit([&] {
  15972. svr.stop();
  15973. t.join();
  15974. ASSERT_FALSE(svr.is_running());
  15975. ASSERT_TRUE(handled);
  15976. });
  15977. svr.wait_until_ready();
  15978. // "Connection: close" makes the server close once it has answered, so the
  15979. // response drain ends immediately instead of idling until the read timeout.
  15980. const std::string head =
  15981. "POST /post HTTP/1.1\r\n"
  15982. "Host: localhost\r\n"
  15983. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15984. "Connection: close\r\n"
  15985. "Content-Length: " +
  15986. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15987. std::string response;
  15988. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15989. ASSERT_GE(response.size(), 12u) << "no response";
  15990. EXPECT_EQ("200", response.substr(9, 3));
  15991. }
  15992. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15993. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15994. // ignored, including when it does not arrive in the same read as the
  15995. // close-delimiter itself.
  15996. expect_split_multipart_ok("--zzzz\r\n"
  15997. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15998. "\r\n"
  15999. "text1"
  16000. "\r\n--zzzz--",
  16001. "\r\nthis epilogue must be ignored\r\n");
  16002. }
  16003. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16004. // The initial boundary may be preceded by a preamble of any length and may
  16005. // straddle a read boundary. Discarding data while waiting for it must not
  16006. // throw away a partial boundary sitting at the end of the buffer.
  16007. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16008. "zz\r\n"
  16009. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16010. "\r\n"
  16011. "text1"
  16012. "\r\n--zzzz--\r\n");
  16013. }
  16014. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16015. // The received boundary was only checked for being non-empty, so it could be
  16016. // as long as a header is allowed to be. The parser scans the body for
  16017. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16018. // costs a nearly full comparison at nearly every position, making the
  16019. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16020. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16021. Server svr;
  16022. svr.Post("/post", [](const Request &req, Response &res) {
  16023. EXPECT_EQ(1u, req.form.fields.size());
  16024. EXPECT_EQ("text1", req.form.get_field("text1"));
  16025. res.set_content("ok", "text/plain");
  16026. });
  16027. auto port = svr.bind_to_any_port(HOST);
  16028. thread t = thread([&] { svr.listen_after_bind(); });
  16029. auto se = detail::scope_exit([&] {
  16030. svr.stop();
  16031. t.join();
  16032. ASSERT_FALSE(svr.is_running());
  16033. });
  16034. svr.wait_until_ready();
  16035. Client cli(HOST, port);
  16036. auto post_with_boundary_of_length = [&](size_t len) {
  16037. const std::string boundary(len, 'a');
  16038. const std::string body =
  16039. "--" + boundary +
  16040. "\r\n"
  16041. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16042. "\r\n"
  16043. "text1"
  16044. "\r\n--" +
  16045. boundary + "--\r\n";
  16046. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16047. };
  16048. auto res = post_with_boundary_of_length(70);
  16049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16050. EXPECT_EQ(StatusCode::OK_200, res->status);
  16051. res = post_with_boundary_of_length(71);
  16052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16053. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16054. }
  16055. TEST(MakeFileBodyTest, Basic) {
  16056. const std::string file_content(4096, 'Z');
  16057. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16058. {
  16059. std::ofstream ofs(tmp_path, std::ios::binary);
  16060. ofs.write(file_content.data(),
  16061. static_cast<std::streamsize>(file_content.size()));
  16062. }
  16063. auto handled = false;
  16064. Server svr;
  16065. svr.Post("/upload", [&](const Request &req, Response &res) {
  16066. EXPECT_EQ(file_content, req.body);
  16067. handled = true;
  16068. res.status = StatusCode::OK_200;
  16069. });
  16070. auto port = svr.bind_to_any_port(HOST);
  16071. auto t = thread([&] { svr.listen_after_bind(); });
  16072. auto se = detail::scope_exit([&] {
  16073. svr.stop();
  16074. t.join();
  16075. ASSERT_FALSE(svr.is_running());
  16076. ASSERT_TRUE(handled);
  16077. std::remove(tmp_path.c_str());
  16078. });
  16079. svr.wait_until_ready();
  16080. auto fb = make_file_body(tmp_path);
  16081. ASSERT_GT(fb.first, 0u);
  16082. Client cli(HOST, port);
  16083. auto res =
  16084. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16086. EXPECT_EQ(StatusCode::OK_200, res->status);
  16087. }
  16088. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16089. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16090. {
  16091. std::ofstream ofs(path, std::ios::binary);
  16092. const std::string content(100, 'A');
  16093. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16094. }
  16095. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16096. auto body = make_file_body(path);
  16097. ASSERT_EQ(100u, body.first);
  16098. ASSERT_TRUE(static_cast<bool>(body.second));
  16099. // Rewritten shorter after its length was measured - and, on a server, after
  16100. // that length has already gone out as Content-Length.
  16101. {
  16102. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16103. const std::string content(10, 'A');
  16104. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16105. }
  16106. std::string written;
  16107. DataSink sink;
  16108. sink.write = [&](const char *d, size_t l) {
  16109. written.append(d, l);
  16110. return true;
  16111. };
  16112. // The provider has to report failure. write_content_with_progress() advances
  16113. // its offset only by what was written, so a provider that returns true
  16114. // without completing the length it promised is called again straight away,
  16115. // and again.
  16116. EXPECT_FALSE(body.second(0, body.first, sink));
  16117. EXPECT_EQ(std::string(10, 'A'), written);
  16118. }
  16119. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16120. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16121. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16122. {
  16123. std::ofstream ofs(path, std::ios::binary);
  16124. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16125. }
  16126. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16127. auto body = make_file_body(path);
  16128. ASSERT_EQ(content.size(), body.first);
  16129. ASSERT_TRUE(static_cast<bool>(body.second));
  16130. std::string written;
  16131. DataSink sink;
  16132. sink.write = [&](const char *d, size_t l) {
  16133. written.append(d, l);
  16134. return true;
  16135. };
  16136. EXPECT_TRUE(body.second(0, body.first, sink));
  16137. EXPECT_EQ(content, written);
  16138. }
  16139. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16140. static constexpr unsigned int number_of_tasks{1000000};
  16141. std::atomic_uint count{0};
  16142. std::unique_ptr<TaskQueue> task_queue{
  16143. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16144. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16145. auto queued = task_queue->enqueue(
  16146. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16147. EXPECT_TRUE(queued);
  16148. }
  16149. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16150. task_queue->shutdown();
  16151. #else
  16152. EXPECT_NO_THROW(task_queue->shutdown());
  16153. #endif
  16154. EXPECT_EQ(number_of_tasks, count.load());
  16155. }
  16156. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16157. static constexpr unsigned int number_of_tasks{1000000};
  16158. static constexpr unsigned int qlimit{2};
  16159. unsigned int queued_count{0};
  16160. std::atomic_uint count{0};
  16161. std::unique_ptr<TaskQueue> task_queue{
  16162. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16163. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16164. if (task_queue->enqueue(
  16165. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16166. queued_count++;
  16167. }
  16168. }
  16169. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16170. task_queue->shutdown();
  16171. #else
  16172. EXPECT_NO_THROW(task_queue->shutdown());
  16173. #endif
  16174. EXPECT_EQ(queued_count, count.load());
  16175. EXPECT_TRUE(queued_count <= number_of_tasks);
  16176. EXPECT_TRUE(queued_count >= qlimit);
  16177. }
  16178. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16179. // Use a short idle timeout so a dynamic thread spawns, times out and
  16180. // exits during the test, and the pool keeps working afterwards.
  16181. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16182. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16183. /*idle_timeout_sec=*/1}};
  16184. std::atomic_uint count{0};
  16185. std::condition_variable cv;
  16186. std::mutex mtx;
  16187. bool release = false;
  16188. // Block the base thread so the second task spawns a dynamic thread.
  16189. EXPECT_TRUE(task_queue->enqueue([&] {
  16190. std::unique_lock<std::mutex> lock(mtx);
  16191. while (!release) {
  16192. cv.wait(lock);
  16193. }
  16194. count++;
  16195. }));
  16196. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16197. // Let the dynamic thread finish its task and exceed the idle timeout.
  16198. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16199. {
  16200. std::unique_lock<std::mutex> lock(mtx);
  16201. release = true;
  16202. }
  16203. cv.notify_all();
  16204. // The pool must still accept and run tasks after the dynamic thread exited.
  16205. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16206. task_queue->shutdown();
  16207. EXPECT_EQ(3u, count.load());
  16208. }
  16209. TEST(TaskQueueTest, MaxQueuedRequests) {
  16210. static constexpr unsigned int qlimit{3};
  16211. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16212. std::condition_variable sem_cv;
  16213. std::mutex sem_mtx;
  16214. int credits = 0;
  16215. bool queued;
  16216. /* Fill up the queue with tasks that will block until we give them credits to
  16217. * complete. */
  16218. for (unsigned int n = 0; n <= qlimit;) {
  16219. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16220. std::unique_lock<std::mutex> lock(sem_mtx);
  16221. while (credits <= 0) {
  16222. sem_cv.wait(lock);
  16223. }
  16224. /* Consume the credit and signal the test code if they are all gone. */
  16225. if (--credits == 0) { sem_cv.notify_one(); }
  16226. });
  16227. if (n < qlimit) {
  16228. /* The first qlimit enqueues must succeed. */
  16229. EXPECT_TRUE(queued);
  16230. } else {
  16231. /* The last one will succeed only when the worker thread
  16232. * starts and dequeues the first blocking task. Although
  16233. * not necessary for the correctness of this test, we sleep for
  16234. * a short while to avoid busy waiting. */
  16235. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16236. }
  16237. if (queued) { n++; }
  16238. }
  16239. /* Further enqueues must fail since the queue is full. */
  16240. for (auto i = 0; i < 4; i++) {
  16241. queued = task_queue->enqueue([] {});
  16242. EXPECT_FALSE(queued);
  16243. }
  16244. /* Give the credits to allow the previous tasks to complete. */
  16245. {
  16246. std::unique_lock<std::mutex> lock(sem_mtx);
  16247. credits += qlimit + 1;
  16248. }
  16249. sem_cv.notify_all();
  16250. /* Wait for all the credits to be consumed. */
  16251. {
  16252. std::unique_lock<std::mutex> lock(sem_mtx);
  16253. while (credits > 0) {
  16254. sem_cv.wait(lock);
  16255. }
  16256. }
  16257. /* Check that we are able again to enqueue at least qlimit tasks. */
  16258. for (unsigned int i = 0; i < qlimit; i++) {
  16259. queued = task_queue->enqueue([] {});
  16260. EXPECT_TRUE(queued);
  16261. }
  16262. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16263. task_queue->shutdown();
  16264. #else
  16265. EXPECT_NO_THROW(task_queue->shutdown());
  16266. #endif
  16267. }
  16268. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16269. Server svr;
  16270. std::string method;
  16271. std::string body;
  16272. auto has_content_length = false;
  16273. auto has_transfer_encoding = false;
  16274. std::atomic<int> bad_requests{0};
  16275. // Leftover body bytes get parsed as a malformed request and answered with
  16276. // 400
  16277. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16278. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16279. });
  16280. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16281. res.set_redirect("/down", StatusCode::SeeOther_303);
  16282. });
  16283. svr.Get("/down", [&](const Request &req, Response &res) {
  16284. method = req.method;
  16285. body = req.body;
  16286. has_content_length = req.has_header("Content-Length");
  16287. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16288. res.set_content("ok", "text/plain");
  16289. });
  16290. auto port = svr.bind_to_any_port(HOST);
  16291. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16292. auto se = detail::scope_exit([&] {
  16293. svr.stop();
  16294. thread.join();
  16295. ASSERT_FALSE(svr.is_running());
  16296. });
  16297. svr.wait_until_ready();
  16298. const std::string payload = "SECRET-BODY";
  16299. auto check = [&](Client &cli, const Result &res) {
  16300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16301. EXPECT_EQ(StatusCode::OK_200, res->status);
  16302. EXPECT_EQ("ok", res->body);
  16303. EXPECT_EQ("GET", method);
  16304. EXPECT_TRUE(body.empty());
  16305. EXPECT_FALSE(has_content_length);
  16306. EXPECT_FALSE(has_transfer_encoding);
  16307. // Nothing of the original body may be left on the connection
  16308. auto res2 = cli.Get("/down");
  16309. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16310. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16311. EXPECT_EQ("ok", res2->body);
  16312. EXPECT_EQ(0, bad_requests);
  16313. };
  16314. // With content length
  16315. {
  16316. Client cli(HOST, port);
  16317. cli.set_keep_alive(true);
  16318. cli.set_follow_location(true);
  16319. auto res = cli.Post(
  16320. "/up", payload.size(),
  16321. [&](size_t offset, size_t length, DataSink &sink) {
  16322. return sink.write(payload.data() + offset, length);
  16323. },
  16324. "text/plain");
  16325. check(cli, res);
  16326. }
  16327. // Without content length (chunked)
  16328. {
  16329. Client cli(HOST, port);
  16330. cli.set_keep_alive(true);
  16331. cli.set_follow_location(true);
  16332. auto res = cli.Post(
  16333. "/up",
  16334. [&](size_t /*offset*/, DataSink &sink) {
  16335. sink.write(payload.data(), payload.size());
  16336. sink.done();
  16337. return true;
  16338. },
  16339. "text/plain");
  16340. check(cli, res);
  16341. }
  16342. }
  16343. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16344. Server svr;
  16345. std::string target;
  16346. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16347. // Echo the still-encoded name back in the Location
  16348. const std::string prefix = "/start/";
  16349. res.status = StatusCode::Found_302;
  16350. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16351. });
  16352. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16353. target = req.target;
  16354. res.set_content("ok", "text/plain");
  16355. });
  16356. auto port = svr.bind_to_any_port(HOST);
  16357. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16358. auto se = detail::scope_exit([&] {
  16359. svr.stop();
  16360. thread.join();
  16361. ASSERT_FALSE(svr.is_running());
  16362. });
  16363. svr.wait_until_ready();
  16364. // Decoding the Location path would turn the first four into a path
  16365. // separator, a query delimiter, a fragment delimiter and a different
  16366. // percent-encoded octet. The rest must keep reaching the server as they are.
  16367. const std::vector<std::string> names = {
  16368. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16369. };
  16370. for (auto path_encode : {true, false}) {
  16371. Client cli(HOST, port);
  16372. cli.set_follow_location(true);
  16373. cli.set_path_encode(path_encode);
  16374. for (const auto &name : names) {
  16375. target.clear();
  16376. auto res = cli.Get("/start/" + name);
  16377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16378. EXPECT_EQ(StatusCode::OK_200, res->status);
  16379. EXPECT_EQ("/dest/" + name, target);
  16380. }
  16381. }
  16382. }
  16383. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  16384. Server svr;
  16385. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16386. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  16387. });
  16388. svr.Get("/hello", [](const Request &req, Response &res) {
  16389. res.set_content(req.get_param_value("key"), "text/plain");
  16390. });
  16391. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16392. auto se = detail::scope_exit([&] {
  16393. svr.stop();
  16394. thread.join();
  16395. ASSERT_FALSE(svr.is_running());
  16396. });
  16397. svr.wait_until_ready();
  16398. {
  16399. Client cli(HOST, PORT);
  16400. cli.set_follow_location(true);
  16401. auto res = cli.Get("/");
  16402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16403. EXPECT_EQ(StatusCode::OK_200, res->status);
  16404. EXPECT_EQ("val&key2=val2", res->body);
  16405. }
  16406. }
  16407. #endif
  16408. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  16409. Server svr;
  16410. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16411. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  16412. });
  16413. svr.Get("/hello", [](const Request &req, Response &res) {
  16414. res.set_content(req.get_param_value("key"), "text/plain");
  16415. });
  16416. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16417. auto se = detail::scope_exit([&] {
  16418. svr.stop();
  16419. thread.join();
  16420. ASSERT_FALSE(svr.is_running());
  16421. });
  16422. svr.wait_until_ready();
  16423. {
  16424. Client cli(HOST, PORT);
  16425. cli.set_follow_location(true);
  16426. auto res = cli.Get("/");
  16427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16428. EXPECT_EQ(StatusCode::OK_200, res->status);
  16429. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  16430. }
  16431. }
  16432. TEST(RedirectTest, RedirectWithPlusInPath) {
  16433. Server svr;
  16434. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16435. res.set_redirect("/a+b");
  16436. });
  16437. // Route pattern uses regex; escape + as \\+
  16438. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  16439. res.set_content(req.path, "text/plain");
  16440. });
  16441. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16442. auto se = detail::scope_exit([&] {
  16443. svr.stop();
  16444. thread.join();
  16445. ASSERT_FALSE(svr.is_running());
  16446. });
  16447. svr.wait_until_ready();
  16448. {
  16449. Client cli(HOST, PORT);
  16450. cli.set_follow_location(true);
  16451. auto res = cli.Get("/");
  16452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16453. EXPECT_EQ(StatusCode::OK_200, res->status);
  16454. EXPECT_EQ("/a+b", res->body);
  16455. }
  16456. }
  16457. TEST(RedirectTest, ResolveRelativeLocation) {
  16458. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  16459. const std::vector<std::pair<std::string, std::string>> cases = {
  16460. {"g", "/b/c/g"},
  16461. {"./g", "/b/c/g"},
  16462. {"g/", "/b/c/g/"},
  16463. {"?y", "/b/c/d;p?y"},
  16464. {"g?y", "/b/c/g?y"},
  16465. {"#s", "/b/c/d;p?q#s"},
  16466. {"g#s", "/b/c/g#s"},
  16467. {"g?y#s", "/b/c/g?y#s"},
  16468. {";x", "/b/c/;x"},
  16469. {"g;x", "/b/c/g;x"},
  16470. {".", "/b/c/"},
  16471. {"./", "/b/c/"},
  16472. {"..", "/b/"},
  16473. {"../", "/b/"},
  16474. {"../g", "/b/g"},
  16475. {"../..", "/"},
  16476. {"../../", "/"},
  16477. {"../../g", "/g"},
  16478. {"../../../g", "/g"},
  16479. {"g.", "/b/c/g."},
  16480. {".g", "/b/c/.g"},
  16481. {"g..", "/b/c/g.."},
  16482. {"..g", "/b/c/..g"},
  16483. {"./../g", "/b/g"},
  16484. {"./g/.", "/b/c/g/"},
  16485. {"g/./h", "/b/c/g/h"},
  16486. {"g/../h", "/b/c/h"},
  16487. {"g;x=1/./y", "/b/c/g;x=1/y"},
  16488. {"g;x=1/../y", "/b/c/y"},
  16489. {"g?y/./x", "/b/c/g?y/./x"},
  16490. {"g#s/../x", "/b/c/g#s/../x"},
  16491. // Not relative-path references, so left for parse_url.
  16492. {"/g", "/g"},
  16493. {"//g", "//g"},
  16494. {"http://g/x", "http://g/x"},
  16495. {"g:h", "g:h"},
  16496. };
  16497. for (const auto &c : cases) {
  16498. EXPECT_EQ(c.second,
  16499. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  16500. << c.first;
  16501. }
  16502. }
  16503. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  16504. Server svr;
  16505. svr.Get("/dir/page", [](const Request &req, Response &res) {
  16506. res.set_redirect(req.get_param_value("to"));
  16507. });
  16508. svr.Get("/dir/next", [](const Request &req, Response &res) {
  16509. res.set_content(req.target, "text/plain");
  16510. });
  16511. svr.Get("/other", [](const Request &req, Response &res) {
  16512. res.set_content(req.target, "text/plain");
  16513. });
  16514. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16515. auto se = detail::scope_exit([&] {
  16516. svr.stop();
  16517. thread.join();
  16518. ASSERT_FALSE(svr.is_running());
  16519. });
  16520. svr.wait_until_ready();
  16521. const std::vector<std::pair<std::string, std::string>> cases = {
  16522. {"next", "/dir/next"},
  16523. {"./next?x=1", "/dir/next?x=1"},
  16524. {"../other", "/other"},
  16525. };
  16526. for (const auto &c : cases) {
  16527. Client cli(HOST, PORT);
  16528. cli.set_follow_location(true);
  16529. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  16530. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  16531. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16532. EXPECT_EQ(c.second, res->body) << c.first;
  16533. }
  16534. }
  16535. #ifdef CPPHTTPLIB_SSL_ENABLED
  16536. TEST(RedirectTest, Issue2185_Online) {
  16537. SSLClient client("github.com");
  16538. client.set_follow_location(true);
  16539. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16540. "Coollab-Windows.zip");
  16541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16542. EXPECT_EQ(StatusCode::OK_200, res->status);
  16543. EXPECT_EQ(9920427U, res->body.size());
  16544. }
  16545. #endif
  16546. TEST(VulnerabilityTest, CRLFInjection) {
  16547. Server svr;
  16548. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16549. res.set_content("Hello 1", "text/plain");
  16550. });
  16551. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16552. res.set_content("Hello 2", "text/plain");
  16553. });
  16554. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16555. res.set_content("Hello 3", "text/plain");
  16556. });
  16557. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16558. res.set_content("Hello 4", "text/plain");
  16559. });
  16560. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16561. for (const auto &x : req.headers) {
  16562. auto key = x.first;
  16563. EXPECT_STRNE("evil", key.c_str());
  16564. }
  16565. });
  16566. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16567. auto se = detail::scope_exit([&] {
  16568. svr.stop();
  16569. thread.join();
  16570. ASSERT_FALSE(svr.is_running());
  16571. });
  16572. svr.wait_until_ready();
  16573. {
  16574. Client cli(HOST, PORT);
  16575. cli.Post("/test1", "A=B",
  16576. "application/x-www-form-urlencoded\r\nevil: hello1");
  16577. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16578. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16579. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16580. }
  16581. }
  16582. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16583. auto server_thread = std::thread([] {
  16584. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16585. default_socket_options(srv);
  16586. sockaddr_in addr{};
  16587. addr.sin_family = AF_INET;
  16588. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16589. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16590. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  16591. ::listen(srv, 1);
  16592. sockaddr_in cli_addr{};
  16593. socklen_t cli_len = sizeof(cli_addr);
  16594. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16595. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  16596. std::string buf_all;
  16597. char buf[2048];
  16598. ssize_t n;
  16599. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  16600. buf_all.append(buf, static_cast<size_t>(n));
  16601. size_t pos;
  16602. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  16603. auto request_block = buf_all.substr(0, pos + 4); // include separator
  16604. auto e = request_block.find("\r\n");
  16605. if (e != std::string::npos) {
  16606. auto request_line = request_block.substr(0, e);
  16607. std::string msg =
  16608. "CRLF injection detected in request line: '" + request_line + "'";
  16609. EXPECT_FALSE(true) << msg;
  16610. }
  16611. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  16612. ::send(cli,
  16613. #ifdef _WIN32
  16614. static_cast<const char *>(resp.c_str()),
  16615. static_cast<int>(resp.size()),
  16616. #else
  16617. resp.c_str(), resp.size(),
  16618. #endif
  16619. 0);
  16620. buf_all.erase(0, pos + 4);
  16621. }
  16622. }
  16623. detail::close_socket(cli);
  16624. detail::close_socket(srv);
  16625. });
  16626. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16627. auto cli = Client("127.0.0.1", PORT + 1);
  16628. auto headers = Headers{
  16629. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  16630. {"Connection", "keep-alive"}};
  16631. auto res = cli.Get("/hi", headers);
  16632. EXPECT_FALSE(res);
  16633. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16634. server_thread.join();
  16635. }
  16636. // A request rejected before any byte reaches the socket must fail right away
  16637. // instead of waiting for a response the server will never send.
  16638. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  16639. // The kernel completes the TCP handshake from the listen backlog, so the
  16640. // client connects, but nothing ever reads, responds or closes.
  16641. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16642. default_socket_options(srv);
  16643. sockaddr_in addr{};
  16644. addr.sin_family = AF_INET;
  16645. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16646. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16647. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16648. ASSERT_EQ(0, ::listen(srv, 8));
  16649. auto cli = Client("127.0.0.1", PORT + 1);
  16650. cli.set_read_timeout(10, 0);
  16651. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  16652. return std::chrono::duration_cast<std::chrono::milliseconds>(
  16653. std::chrono::steady_clock::now() - start)
  16654. .count();
  16655. };
  16656. {
  16657. Request req;
  16658. req.method = "GE T";
  16659. req.path = "/";
  16660. auto start = std::chrono::steady_clock::now();
  16661. auto res = cli.send(req);
  16662. EXPECT_FALSE(res);
  16663. EXPECT_EQ(Error::Write, res.error());
  16664. EXPECT_LT(elapsed_ms(start), 1000);
  16665. }
  16666. {
  16667. auto start = std::chrono::steady_clock::now();
  16668. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  16669. EXPECT_FALSE(res);
  16670. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16671. EXPECT_LT(elapsed_ms(start), 1000);
  16672. }
  16673. EXPECT_FALSE(cli.is_socket_open());
  16674. detail::close_socket(srv);
  16675. }
  16676. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  16677. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16678. default_socket_options(srv);
  16679. sockaddr_in addr{};
  16680. addr.sin_family = AF_INET;
  16681. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16682. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16683. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16684. ASSERT_EQ(0, ::listen(srv, 1));
  16685. std::string received;
  16686. auto server_thread = std::thread([&] {
  16687. auto sock = ::accept(srv, nullptr, nullptr);
  16688. if (sock == INVALID_SOCKET) { return; }
  16689. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  16690. char buf[2048];
  16691. ssize_t n;
  16692. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  16693. received.append(buf, static_cast<size_t>(n));
  16694. }
  16695. detail::close_socket(sock);
  16696. });
  16697. {
  16698. auto cli = Client("127.0.0.1", PORT + 1);
  16699. // "Z" sorts after the default headers, so writing straight to the socket
  16700. // would have sent the request line and those headers before the rejection.
  16701. auto handle =
  16702. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  16703. EXPECT_FALSE(handle.is_valid());
  16704. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  16705. }
  16706. server_thread.join();
  16707. detail::close_socket(srv);
  16708. EXPECT_TRUE(received.empty()) << received;
  16709. }
  16710. TEST(PathParamsTest, StaticMatch) {
  16711. const auto pattern = "/users/all";
  16712. detail::PathParamsMatcher matcher(pattern);
  16713. Request request;
  16714. request.path = "/users/all";
  16715. ASSERT_TRUE(matcher.match(request));
  16716. std::unordered_map<std::string, std::string> expected_params = {};
  16717. EXPECT_EQ(request.path_params, expected_params);
  16718. }
  16719. TEST(PathParamsTest, StaticMismatch) {
  16720. const auto pattern = "/users/all";
  16721. detail::PathParamsMatcher matcher(pattern);
  16722. Request request;
  16723. request.path = "/users/1";
  16724. ASSERT_FALSE(matcher.match(request));
  16725. }
  16726. TEST(PathParamsTest, SingleParamInTheMiddle) {
  16727. const auto pattern = "/users/:id/subscriptions";
  16728. detail::PathParamsMatcher matcher(pattern);
  16729. Request request;
  16730. request.path = "/users/42/subscriptions";
  16731. ASSERT_TRUE(matcher.match(request));
  16732. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16733. EXPECT_EQ(request.path_params, expected_params);
  16734. }
  16735. TEST(PathParamsTest, SingleParamInTheEnd) {
  16736. const auto pattern = "/users/:id";
  16737. detail::PathParamsMatcher matcher(pattern);
  16738. Request request;
  16739. request.path = "/users/24";
  16740. ASSERT_TRUE(matcher.match(request));
  16741. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  16742. EXPECT_EQ(request.path_params, expected_params);
  16743. }
  16744. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  16745. const auto pattern = "/users/:id/";
  16746. detail::PathParamsMatcher matcher(pattern);
  16747. Request request;
  16748. request.path = "/users/42/";
  16749. ASSERT_TRUE(matcher.match(request));
  16750. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16751. EXPECT_EQ(request.path_params, expected_params);
  16752. }
  16753. TEST(PathParamsTest, EmptyParam) {
  16754. const auto pattern = "/users/:id/";
  16755. detail::PathParamsMatcher matcher(pattern);
  16756. Request request;
  16757. request.path = "/users//";
  16758. ASSERT_TRUE(matcher.match(request));
  16759. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  16760. EXPECT_EQ(request.path_params, expected_params);
  16761. }
  16762. TEST(PathParamsTest, FragmentMismatch) {
  16763. const auto pattern = "/users/:id/";
  16764. detail::PathParamsMatcher matcher(pattern);
  16765. Request request;
  16766. request.path = "/admins/24/";
  16767. ASSERT_FALSE(matcher.match(request));
  16768. }
  16769. TEST(PathParamsTest, ExtraFragments) {
  16770. const auto pattern = "/users/:id";
  16771. detail::PathParamsMatcher matcher(pattern);
  16772. Request request;
  16773. request.path = "/users/42/subscriptions";
  16774. ASSERT_FALSE(matcher.match(request));
  16775. }
  16776. TEST(PathParamsTest, MissingTrailingParam) {
  16777. const auto pattern = "/users/:id";
  16778. detail::PathParamsMatcher matcher(pattern);
  16779. Request request;
  16780. request.path = "/users";
  16781. ASSERT_FALSE(matcher.match(request));
  16782. }
  16783. TEST(PathParamsTest, MissingParamInTheMiddle) {
  16784. const auto pattern = "/users/:id/subscriptions";
  16785. detail::PathParamsMatcher matcher(pattern);
  16786. Request request;
  16787. request.path = "/users/subscriptions";
  16788. ASSERT_FALSE(matcher.match(request));
  16789. }
  16790. TEST(PathParamsTest, MultipleParams) {
  16791. const auto pattern = "/users/:userid/subscriptions/:subid";
  16792. detail::PathParamsMatcher matcher(pattern);
  16793. Request request;
  16794. request.path = "/users/42/subscriptions/2";
  16795. ASSERT_TRUE(matcher.match(request));
  16796. std::unordered_map<std::string, std::string> expected_params = {
  16797. {"userid", "42"}, {"subid", "2"}};
  16798. EXPECT_EQ(request.path_params, expected_params);
  16799. }
  16800. TEST(PathParamsTest, SequenceOfParams) {
  16801. const auto pattern = "/values/:x/:y/:z";
  16802. detail::PathParamsMatcher matcher(pattern);
  16803. Request request;
  16804. request.path = "/values/1/2/3";
  16805. ASSERT_TRUE(matcher.match(request));
  16806. std::unordered_map<std::string, std::string> expected_params = {
  16807. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  16808. EXPECT_EQ(request.path_params, expected_params);
  16809. }
  16810. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  16811. const auto pattern = "/prefix:suffix";
  16812. detail::PathParamsMatcher matcher(pattern);
  16813. Request request;
  16814. request.path = "/prefix:suffix";
  16815. ASSERT_TRUE(matcher.match(request));
  16816. const std::unordered_map<std::string, std::string> expected_params = {};
  16817. EXPECT_EQ(request.path_params, expected_params);
  16818. }
  16819. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16820. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16821. // calling thread's stack on a long enough path for a quantified pattern;
  16822. // RegexMatcher must refuse to run regex matching on paths beyond
  16823. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16824. detail::RegexMatcher matcher("/files/(.*)");
  16825. Request within_limit;
  16826. within_limit.path = "/files/" + std::string(10, 'A');
  16827. EXPECT_TRUE(matcher.match(within_limit));
  16828. Request over_limit;
  16829. over_limit.path =
  16830. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16831. EXPECT_FALSE(matcher.match(over_limit));
  16832. }
  16833. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16834. Server svr;
  16835. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16836. res.set_content("ok", "text/plain");
  16837. });
  16838. auto port = svr.bind_to_any_port(HOST);
  16839. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16840. auto se = detail::scope_exit([&] {
  16841. svr.stop();
  16842. thread.join();
  16843. ASSERT_FALSE(svr.is_running());
  16844. });
  16845. svr.wait_until_ready();
  16846. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16847. // request URI limit; this used to be able to crash the process.
  16848. std::string path =
  16849. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16850. std::string req = "GET " + path +
  16851. " HTTP/1.1\r\n"
  16852. "Host: " +
  16853. std::string(HOST) + ":" + std::to_string(port) +
  16854. "\r\n"
  16855. "Connection: close\r\n"
  16856. "\r\n";
  16857. std::string response;
  16858. ASSERT_TRUE(send_request(5, req, &response, port));
  16859. EXPECT_NE(std::string::npos, response.find("404"));
  16860. }
  16861. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16862. Server svr;
  16863. auto handler = [](const Request & /*req*/, Response &res) {
  16864. res.set_content("hit", "text/plain");
  16865. };
  16866. // No regex metacharacter, so this one is compared literally
  16867. svr.Get("/literal/route", handler);
  16868. // '.' is a regex metacharacter, so this one must keep regex semantics
  16869. svr.Get("/a.c", handler);
  16870. auto port = svr.bind_to_any_port(HOST);
  16871. std::thread t([&]() { svr.listen_after_bind(); });
  16872. auto se = detail::scope_exit([&] {
  16873. svr.stop();
  16874. t.join();
  16875. ASSERT_FALSE(svr.is_running());
  16876. });
  16877. svr.wait_until_ready();
  16878. Client cli(HOST, port);
  16879. struct {
  16880. const char *path;
  16881. int status;
  16882. } cases[] = {
  16883. {"/literal/route", StatusCode::OK_200},
  16884. {"/literal/routes", StatusCode::NotFound_404},
  16885. {"/literal/rout", StatusCode::NotFound_404},
  16886. {"/abc", StatusCode::OK_200},
  16887. {"/a.c", StatusCode::OK_200},
  16888. };
  16889. for (const auto &x : cases) {
  16890. auto res = cli.Get(x.path);
  16891. ASSERT_TRUE(res) << x.path;
  16892. EXPECT_EQ(x.status, res->status) << x.path;
  16893. }
  16894. }
  16895. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16896. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16897. // from exhausting the stack, so it must only constrain routes that actually
  16898. // run a regular expression. A literal route is matched by comparison and
  16899. // stays usable at any length.
  16900. Server svr;
  16901. const std::string pattern =
  16902. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16903. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16904. res.set_content("hit", "text/plain");
  16905. });
  16906. auto port = svr.bind_to_any_port(HOST);
  16907. std::thread t([&]() { svr.listen_after_bind(); });
  16908. auto se = detail::scope_exit([&] {
  16909. svr.stop();
  16910. t.join();
  16911. ASSERT_FALSE(svr.is_running());
  16912. });
  16913. svr.wait_until_ready();
  16914. Client cli(HOST, port);
  16915. auto res = cli.Get(pattern);
  16916. ASSERT_TRUE(res);
  16917. EXPECT_EQ(StatusCode::OK_200, res->status);
  16918. }
  16919. TEST(ParseUrlTest, VariousPatterns) {
  16920. {
  16921. detail::UrlComponents uc;
  16922. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16923. EXPECT_EQ("http", uc.scheme);
  16924. EXPECT_EQ("example.com", uc.host);
  16925. EXPECT_EQ("8080", uc.port);
  16926. EXPECT_EQ("/path", uc.path);
  16927. EXPECT_EQ("?q=1", uc.query);
  16928. }
  16929. {
  16930. detail::UrlComponents uc;
  16931. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16932. EXPECT_EQ("https", uc.scheme);
  16933. EXPECT_EQ("example.com", uc.host);
  16934. EXPECT_TRUE(uc.port.empty());
  16935. EXPECT_EQ("/path", uc.path);
  16936. }
  16937. {
  16938. detail::UrlComponents uc;
  16939. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16940. EXPECT_EQ("::1", uc.host);
  16941. EXPECT_EQ("8080", uc.port);
  16942. EXPECT_EQ("/path", uc.path);
  16943. }
  16944. {
  16945. detail::UrlComponents uc;
  16946. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16947. }
  16948. {
  16949. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16950. // the path while the connection still targets the bracketed host.
  16951. detail::UrlComponents uc;
  16952. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16953. }
  16954. {
  16955. detail::UrlComponents uc;
  16956. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16957. }
  16958. {
  16959. detail::UrlComponents uc;
  16960. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16961. EXPECT_EQ("::1", uc.host);
  16962. EXPECT_TRUE(uc.port.empty());
  16963. EXPECT_EQ("/path", uc.path);
  16964. }
  16965. {
  16966. detail::UrlComponents uc;
  16967. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16968. EXPECT_TRUE(uc.scheme.empty());
  16969. EXPECT_EQ("example.com", uc.host);
  16970. EXPECT_EQ("/path", uc.path);
  16971. EXPECT_EQ("?q=1", uc.query);
  16972. }
  16973. {
  16974. detail::UrlComponents uc;
  16975. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16976. EXPECT_TRUE(uc.host.empty());
  16977. EXPECT_EQ("/path", uc.path);
  16978. EXPECT_EQ("?q=1", uc.query);
  16979. }
  16980. {
  16981. detail::UrlComponents uc;
  16982. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16983. EXPECT_EQ("example.com", uc.host);
  16984. EXPECT_EQ("8080", uc.port);
  16985. }
  16986. {
  16987. // Unix socket path — must not be parsed as host
  16988. detail::UrlComponents uc;
  16989. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16990. EXPECT_TRUE(uc.host.empty());
  16991. }
  16992. {
  16993. detail::UrlComponents uc;
  16994. ASSERT_TRUE(detail::parse_url("", uc));
  16995. EXPECT_TRUE(uc.host.empty());
  16996. EXPECT_TRUE(uc.path.empty());
  16997. }
  16998. {
  16999. detail::UrlComponents uc;
  17000. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17001. }
  17002. {
  17003. detail::UrlComponents uc;
  17004. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17005. }
  17006. {
  17007. // Accepted by parse_url; callers restrict to http/https
  17008. detail::UrlComponents uc;
  17009. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17010. EXPECT_EQ("ftp", uc.scheme);
  17011. }
  17012. {
  17013. detail::UrlComponents uc;
  17014. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17015. }
  17016. {
  17017. detail::UrlComponents uc;
  17018. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17019. }
  17020. }
  17021. TEST(ParseUrlTest, FragmentHandling) {
  17022. {
  17023. detail::UrlComponents uc;
  17024. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17025. EXPECT_EQ("/path", uc.path);
  17026. EXPECT_TRUE(uc.query.empty());
  17027. }
  17028. {
  17029. detail::UrlComponents uc;
  17030. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17031. EXPECT_TRUE(uc.path.empty());
  17032. EXPECT_TRUE(uc.query.empty());
  17033. }
  17034. }
  17035. TEST(ParseUrlTest, UserinfoHandling) {
  17036. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17037. // parsers would see evil.com as the host.
  17038. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17039. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17040. for (auto url : urls) {
  17041. detail::UrlComponents uc;
  17042. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17043. }
  17044. }
  17045. TEST(ParseUrlTest, IPv6EdgeCases) {
  17046. {
  17047. detail::UrlComponents uc;
  17048. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17049. EXPECT_TRUE(uc.scheme.empty());
  17050. EXPECT_EQ("::1", uc.host);
  17051. EXPECT_EQ("8080", uc.port);
  17052. }
  17053. {
  17054. // Zone ID '%25' is not in [a-fA-F0-9:]
  17055. detail::UrlComponents uc;
  17056. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17057. }
  17058. }
  17059. TEST(ParseUrlTest, SchemeEdgeCases) {
  17060. {
  17061. detail::UrlComponents uc;
  17062. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17063. }
  17064. {
  17065. detail::UrlComponents uc;
  17066. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17067. }
  17068. {
  17069. detail::UrlComponents uc;
  17070. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17071. }
  17072. }
  17073. TEST(ParseUrlTest, PortEdgeCases) {
  17074. {
  17075. detail::UrlComponents uc;
  17076. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17077. EXPECT_TRUE(uc.port.empty());
  17078. EXPECT_EQ("/path", uc.path);
  17079. }
  17080. {
  17081. // parse_url accepts any port string; validation is done by parse_port
  17082. detail::UrlComponents uc;
  17083. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17084. EXPECT_EQ("abc", uc.port);
  17085. }
  17086. }
  17087. TEST(ParseUrlTest, WebSocketPatterns) {
  17088. {
  17089. detail::UrlComponents uc;
  17090. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17091. EXPECT_EQ("ws", uc.scheme);
  17092. EXPECT_EQ("echo.example.com", uc.host);
  17093. EXPECT_EQ("8080", uc.port);
  17094. EXPECT_EQ("/ws", uc.path);
  17095. }
  17096. {
  17097. detail::UrlComponents uc;
  17098. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17099. EXPECT_EQ("wss", uc.scheme);
  17100. EXPECT_EQ("echo.example.com", uc.host);
  17101. EXPECT_TRUE(uc.port.empty());
  17102. EXPECT_EQ("/ws", uc.path);
  17103. }
  17104. }
  17105. TEST(ParseUrlTest, QueryOnly) {
  17106. detail::UrlComponents uc;
  17107. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17108. EXPECT_TRUE(uc.host.empty());
  17109. EXPECT_TRUE(uc.path.empty());
  17110. EXPECT_EQ("?q=1&r=2", uc.query);
  17111. }
  17112. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17113. detail::UrlComponents uc;
  17114. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17115. EXPECT_TRUE(uc.scheme.empty());
  17116. EXPECT_EQ("example.com", uc.host);
  17117. EXPECT_EQ("443", uc.port);
  17118. EXPECT_EQ("/path", uc.path);
  17119. }
  17120. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17121. // If ipv6 regex working, regex match codepath is taken.
  17122. // else port will default to 80 in Client impl
  17123. int clientImplMagicPort = 80;
  17124. int port = 4321;
  17125. // above ports must be different to avoid false negative
  17126. EXPECT_NE(clientImplMagicPort, port);
  17127. std::string ipV6TestURL = "http://[ff06::c3]";
  17128. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17129. CLIENT_PRIVATE_KEY_FILE);
  17130. EXPECT_EQ(cli.port(), port);
  17131. }
  17132. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17133. auto file_path = "./www/dir/index.html";
  17134. auto dir_path = "./www/dir";
  17135. detail::FileStat stat_file(file_path);
  17136. EXPECT_TRUE(stat_file.is_file());
  17137. EXPECT_FALSE(stat_file.is_dir());
  17138. detail::FileStat stat_dir(dir_path);
  17139. EXPECT_FALSE(stat_dir.is_file());
  17140. EXPECT_TRUE(stat_dir.is_dir());
  17141. }
  17142. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17143. // IPv4 with default HTTP port (80)
  17144. EXPECT_EQ("example.com",
  17145. detail::make_host_and_port_string("example.com", 80, false));
  17146. // IPv4 with default HTTPS port (443)
  17147. EXPECT_EQ("example.com",
  17148. detail::make_host_and_port_string("example.com", 443, true));
  17149. // IPv4 with non-default HTTP port
  17150. EXPECT_EQ("example.com:8080",
  17151. detail::make_host_and_port_string("example.com", 8080, false));
  17152. // IPv4 with non-default HTTPS port
  17153. EXPECT_EQ("example.com:8443",
  17154. detail::make_host_and_port_string("example.com", 8443, true));
  17155. // IPv6 with default HTTP port (80)
  17156. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17157. // IPv6 with default HTTPS port (443)
  17158. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17159. // IPv6 with non-default HTTP port
  17160. EXPECT_EQ("[::1]:8080",
  17161. detail::make_host_and_port_string("::1", 8080, false));
  17162. // IPv6 with non-default HTTPS port
  17163. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17164. // IPv6 full address with default port
  17165. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17166. detail::make_host_and_port_string(
  17167. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17168. // IPv6 full address with non-default port
  17169. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17170. detail::make_host_and_port_string(
  17171. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17172. // IPv6 localhost with non-default port
  17173. EXPECT_EQ("[::1]:3000",
  17174. detail::make_host_and_port_string("::1", 3000, false));
  17175. // IPv6 with zone ID (link-local address) with default port
  17176. EXPECT_EQ("[fe80::1%eth0]",
  17177. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17178. // IPv6 with zone ID (link-local address) with non-default port
  17179. EXPECT_EQ("[fe80::1%eth0]:8080",
  17180. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17181. // Edge case: Port 443 with is_ssl=false (should add port)
  17182. EXPECT_EQ("example.com:443",
  17183. detail::make_host_and_port_string("example.com", 443, false));
  17184. // Edge case: Port 80 with is_ssl=true (should add port)
  17185. EXPECT_EQ("example.com:80",
  17186. detail::make_host_and_port_string("example.com", 80, true));
  17187. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17188. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17189. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17190. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17191. // Security fix: Already bracketed IPv6 should not get double brackets
  17192. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17193. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17194. EXPECT_EQ("[::1]:8080",
  17195. detail::make_host_and_port_string("[::1]", 8080, false));
  17196. EXPECT_EQ("[2001:db8::1]:8080",
  17197. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17198. EXPECT_EQ("[fe80::1%eth0]",
  17199. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17200. EXPECT_EQ("[fe80::1%eth0]:8080",
  17201. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17202. // Edge case: Empty host (should return as-is)
  17203. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17204. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17205. // This is a known limitation but shouldn't crash
  17206. EXPECT_EQ("[host:name]",
  17207. detail::make_host_and_port_string("host:name", 80, false));
  17208. // Port number edge cases (no validation, but should not crash)
  17209. EXPECT_EQ("example.com:0",
  17210. detail::make_host_and_port_string("example.com", 0, false));
  17211. EXPECT_EQ("example.com:-1",
  17212. detail::make_host_and_port_string("example.com", -1, false));
  17213. EXPECT_EQ("example.com:65535",
  17214. detail::make_host_and_port_string("example.com", 65535, false));
  17215. EXPECT_EQ("example.com:65536",
  17216. detail::make_host_and_port_string("example.com", 65536, false));
  17217. }
  17218. #ifdef CPPHTTPLIB_SSL_ENABLED
  17219. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17220. httplib::SSLClient cli("roblox.com", 443);
  17221. cli.set_follow_location(true);
  17222. auto res = cli.Get("/");
  17223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17224. EXPECT_EQ(StatusCode::OK_200, res->status);
  17225. }
  17226. #endif
  17227. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17228. Server svr;
  17229. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17230. EXPECT_EQ(res.status, 400);
  17231. });
  17232. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17233. auto se = detail::scope_exit([&] {
  17234. svr.stop();
  17235. thread.join();
  17236. ASSERT_FALSE(svr.is_running());
  17237. });
  17238. svr.wait_until_ready();
  17239. Client cli(HOST, PORT);
  17240. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17241. }
  17242. TEST(InvalidHeaderCharsTest, is_field_name) {
  17243. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17244. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17245. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17246. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17247. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17248. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17249. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17250. EXPECT_FALSE(detail::fields::is_field_name(""));
  17251. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17252. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17253. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17254. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17255. }
  17256. TEST(InvalidHeaderCharsTest, is_field_value) {
  17257. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17258. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17259. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17260. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17261. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17262. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17263. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17264. EXPECT_TRUE(detail::fields::is_field_value(""));
  17265. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17266. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17267. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17268. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17269. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17270. }
  17271. TEST(InvalidHeaderCharsTest, OnServer) {
  17272. Server svr;
  17273. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17274. std::string header = "Not Set";
  17275. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17276. res.set_header(header, "value");
  17277. res.set_content("Page Content Page Content", "text/plain");
  17278. });
  17279. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17280. std::string header = "Not Set";
  17281. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17282. res.set_header("X-Test", header);
  17283. res.set_content("Page Content Page Content", "text/plain");
  17284. });
  17285. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17286. auto se = detail::scope_exit([&] {
  17287. svr.stop();
  17288. thread.join();
  17289. ASSERT_FALSE(svr.is_running());
  17290. });
  17291. svr.wait_until_ready();
  17292. Client cli(HOST, PORT);
  17293. {
  17294. auto res = cli.Get(
  17295. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17297. EXPECT_EQ("Page Content Page Content", res->body);
  17298. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17299. }
  17300. {
  17301. auto res = cli.Get(
  17302. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17304. EXPECT_EQ("Page Content Page Content", res->body);
  17305. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17306. }
  17307. }
  17308. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17309. auto handled = false;
  17310. Server svr;
  17311. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17312. thread t = thread([&] { svr.listen(HOST, PORT); });
  17313. auto se = detail::scope_exit([&] {
  17314. svr.stop();
  17315. t.join();
  17316. ASSERT_FALSE(svr.is_running());
  17317. ASSERT_FALSE(handled);
  17318. });
  17319. svr.wait_until_ready();
  17320. auto req = "POST /test HTTP/1.1\r\n"
  17321. "Content-Length: x\r\n"
  17322. "\r\n";
  17323. std::string response;
  17324. ASSERT_TRUE(send_request(1, req, &response));
  17325. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17326. response.substr(0, response.find("\r\n")));
  17327. }
  17328. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17329. // case-insensitive, and a server that receives a 100-continue expectation in
  17330. // an HTTP/1.0 request MUST ignore it.
  17331. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17332. std::string response;
  17333. ASSERT_TRUE(send_request(1, req, &response, port));
  17334. *got_100 = response.find("100 Continue") != std::string::npos;
  17335. }
  17336. class ExpectTokenTest : public ::testing::Test {
  17337. protected:
  17338. void SetUp() override {
  17339. svr_.Post("/p", [](const Request &, Response &res) {
  17340. res.set_content("ok", "text/plain");
  17341. });
  17342. port_ = svr_.bind_to_any_port(HOST);
  17343. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17344. svr_.wait_until_ready();
  17345. }
  17346. void TearDown() override {
  17347. svr_.stop();
  17348. if (thread_.joinable()) { thread_.join(); }
  17349. }
  17350. std::string request(const char *version, const char *expect_value) const {
  17351. return std::string("POST /p ") + version +
  17352. "\r\n"
  17353. "Host: localhost\r\n"
  17354. "Content-Length: 2\r\n"
  17355. "Connection: close\r\n"
  17356. "Expect: " +
  17357. expect_value +
  17358. "\r\n"
  17359. "\r\n"
  17360. "hi";
  17361. }
  17362. Server svr_;
  17363. int port_ = 0;
  17364. thread thread_;
  17365. };
  17366. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  17367. bool got_100 = false;
  17368. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  17369. EXPECT_TRUE(got_100);
  17370. }
  17371. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  17372. bool got_100 = true;
  17373. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  17374. EXPECT_FALSE(got_100);
  17375. }
  17376. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  17377. bool got_100 = false;
  17378. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  17379. EXPECT_TRUE(got_100);
  17380. }
  17381. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  17382. bool got_100 = false;
  17383. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  17384. EXPECT_TRUE(got_100);
  17385. }
  17386. // `100 Continue` is sent only when the server starts reading the body, so a
  17387. // request rejected before that never invites the client to send it. The
  17388. // requests below carry the expectation but withhold the body, as a client
  17389. // waiting for `100 Continue` would.
  17390. // A POST that expects `100 Continue` and withholds its two-byte body.
  17391. static std::string expect_headers_only(const std::string &path) {
  17392. return "POST " + path +
  17393. " HTTP/1.1\r\n"
  17394. "Host: localhost\r\n"
  17395. "Content-Length: 2\r\n"
  17396. "Expect: 100-continue\r\n"
  17397. "\r\n";
  17398. }
  17399. class ExpectLazyContinueTest : public ::testing::Test {
  17400. protected:
  17401. void SetUp() override {
  17402. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  17403. if (req.path == "/pre-routing") {
  17404. res.status = StatusCode::Unauthorized_401;
  17405. return Server::HandlerResponse::Handled;
  17406. }
  17407. return Server::HandlerResponse::Unhandled;
  17408. });
  17409. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  17410. if (req.matched_route == "/pre-request") {
  17411. res.status = StatusCode::Forbidden_403;
  17412. return Server::HandlerResponse::Handled;
  17413. }
  17414. return Server::HandlerResponse::Unhandled;
  17415. });
  17416. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  17417. res.set_content("ok", "text/plain");
  17418. });
  17419. svr_.Post("/pre-request", [](const Request &, Response &res) {
  17420. res.set_content("ok", "text/plain");
  17421. });
  17422. svr_.Post("/reader-used", [](const Request &, Response &res,
  17423. const ContentReader &content_reader) {
  17424. std::string body;
  17425. content_reader([&](const char *data, size_t len) {
  17426. body.append(data, len);
  17427. return true;
  17428. });
  17429. res.set_content(body, "text/plain");
  17430. });
  17431. svr_.Post("/reader-unused",
  17432. [](const Request &, Response &res, const ContentReader &) {
  17433. res.set_content("ignored", "text/plain");
  17434. });
  17435. port_ = svr_.bind_to_any_port(HOST);
  17436. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17437. svr_.wait_until_ready();
  17438. }
  17439. void TearDown() override {
  17440. svr_.stop();
  17441. if (thread_.joinable()) { thread_.join(); }
  17442. }
  17443. // Sends `req` and reads until the server closes the connection. Returns
  17444. // false if the read had to wait for the client-side timeout instead.
  17445. bool send_until_closed(const std::string &req, std::string *resp) const {
  17446. auto start = std::chrono::steady_clock::now();
  17447. if (!send_request(3, req, resp, port_)) { return false; }
  17448. auto elapsed = std::chrono::steady_clock::now() - start;
  17449. return elapsed < std::chrono::seconds(2);
  17450. }
  17451. // The final response comes without `100 Continue`, and the server closes
  17452. // the connection since the body may or may not follow.
  17453. void expect_final_without_interim(const std::string &path,
  17454. const char *status_line) const {
  17455. std::string resp;
  17456. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  17457. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  17458. EXPECT_EQ(0u, resp.find(status_line));
  17459. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17460. }
  17461. Server svr_;
  17462. int port_ = 0;
  17463. thread thread_;
  17464. };
  17465. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  17466. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  17467. }
  17468. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  17469. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  17470. }
  17471. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  17472. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  17473. }
  17474. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  17475. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  17476. }
  17477. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  17478. // The body follows once `100 Continue` has had time to arrive.
  17479. auto req = expect_headers_only("/reader-used");
  17480. req.insert(req.size() - 2, "Connection: close\r\n");
  17481. std::string resp;
  17482. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  17483. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  17484. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  17485. EXPECT_NE(std::string::npos, resp.find("hi"));
  17486. }
  17487. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  17488. // Large enough for the client to add `Expect: 100-continue` itself.
  17489. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  17490. std::atomic<bool> body_sent{false};
  17491. Client cli(HOST, port_);
  17492. auto res = cli.Post(
  17493. "/pre-request", length,
  17494. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  17495. body_sent = true;
  17496. std::string chunk(len, 'x');
  17497. sink.write(chunk.data(), chunk.size());
  17498. return true;
  17499. },
  17500. "application/octet-stream");
  17501. ASSERT_TRUE(res);
  17502. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17503. EXPECT_FALSE(body_sent);
  17504. }
  17505. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  17506. Server svr;
  17507. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  17508. return StatusCode::ExpectationFailed_417;
  17509. });
  17510. svr.Post("/p", [](const Request &, Response &res) {
  17511. res.set_content("ok", "text/plain");
  17512. });
  17513. auto port = svr.bind_to_any_port(HOST);
  17514. thread t = thread([&] { svr.listen_after_bind(); });
  17515. auto se = detail::scope_exit([&] {
  17516. svr.stop();
  17517. t.join();
  17518. });
  17519. svr.wait_until_ready();
  17520. std::string resp;
  17521. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  17522. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  17523. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17524. // Exactly one response: the route handler must not run after the 417.
  17525. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  17526. }
  17527. #ifndef _WIN32
  17528. TEST(Expect100ContinueTest, ServerClosesConnection) {
  17529. static constexpr char reject[] = "Unauthorized";
  17530. static constexpr char accept[] = "Upload accepted";
  17531. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17532. Server svr;
  17533. svr.set_expect_100_continue_handler(
  17534. [](const Request & /*req*/, Response &res) {
  17535. res.status = StatusCode::Unauthorized_401;
  17536. res.set_content(reject, "text/plain");
  17537. return res.status;
  17538. });
  17539. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17540. res.set_content(accept, "text/plain");
  17541. });
  17542. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17543. auto se = detail::scope_exit([&] {
  17544. svr.stop();
  17545. thread.join();
  17546. ASSERT_FALSE(svr.is_running());
  17547. });
  17548. svr.wait_until_ready();
  17549. {
  17550. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17551. curl_easy_init(), &curl_easy_cleanup};
  17552. ASSERT_NE(curl, nullptr);
  17553. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17554. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17555. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17556. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17557. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17558. &curl_slist_free_all};
  17559. ASSERT_NE(list, nullptr);
  17560. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17561. struct read_data {
  17562. size_t read_size;
  17563. size_t total_size;
  17564. } data = {0, total_size};
  17565. using read_callback_t =
  17566. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17567. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17568. void *userdata) -> size_t {
  17569. read_data *d = (read_data *)userdata;
  17570. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17571. std::fill_n(ptr, size * nmemb, 'A');
  17572. d->read_size += size * nmemb;
  17573. return size * nmemb;
  17574. };
  17575. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  17576. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17577. std::vector<char> buffer;
  17578. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17579. using write_callback_t =
  17580. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17581. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17582. void *userdata) -> size_t {
  17583. std::vector<char> *buf = (std::vector<char> *)userdata;
  17584. buf->reserve(buf->size() + size * nmemb + 1);
  17585. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17586. return size * nmemb;
  17587. };
  17588. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  17589. {
  17590. const auto res = curl_easy_perform(curl.get());
  17591. ASSERT_EQ(res, CURLE_OK);
  17592. }
  17593. {
  17594. auto response_code = long{};
  17595. const auto res =
  17596. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  17597. ASSERT_EQ(res, CURLE_OK);
  17598. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  17599. }
  17600. {
  17601. auto dl = curl_off_t{};
  17602. const auto res =
  17603. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  17604. ASSERT_EQ(res, CURLE_OK);
  17605. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  17606. }
  17607. {
  17608. buffer.push_back('\0');
  17609. ASSERT_STRCASEEQ(buffer.data(), reject);
  17610. }
  17611. }
  17612. }
  17613. #endif
  17614. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  17615. // Regression test for #2458.
  17616. //
  17617. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  17618. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  17619. // ticket can make the client socket spuriously readable during the
  17620. // 100-continue wait. If the readiness is mistaken for an incoming response,
  17621. // the client withholds the body and then blocks reading a response that never
  17622. // comes, failing with `Failed to read connection`.
  17623. //
  17624. // A correct client (like curl) sends the body once no `100 Continue` arrives
  17625. // within the timeout. This raw OpenSSL server deliberately never sends
  17626. // `100 Continue`; the client must still deliver the body and receive 200.
  17627. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  17628. signal(SIGPIPE, SIG_IGN);
  17629. const auto port = PORT + 4;
  17630. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17631. ASSERT_NE(srv, INVALID_SOCKET);
  17632. int opt = 1;
  17633. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  17634. sockaddr_in addr{};
  17635. addr.sin_family = AF_INET;
  17636. addr.sin_port = htons(static_cast<uint16_t>(port));
  17637. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17638. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17639. ASSERT_EQ(0, ::listen(srv, 1));
  17640. std::atomic<size_t> server_body_bytes{0};
  17641. auto server_thread = std::thread([&] {
  17642. sockaddr_in cli_addr{};
  17643. socklen_t cli_len = sizeof(cli_addr);
  17644. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17645. if (cli == INVALID_SOCKET) { return; }
  17646. // Bound the lifetime of the server side so a buggy client (which never
  17647. // sends the body) cannot make this thread block forever on join.
  17648. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  17649. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  17650. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  17651. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  17652. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  17653. SSL *ssl = SSL_new(ctx);
  17654. SSL_set_fd(ssl, static_cast<int>(cli));
  17655. if (SSL_accept(ssl) > 0) {
  17656. // Read the request headers. Reading here also flushes the TLS 1.3
  17657. // session tickets to the client. Deliberately do NOT send
  17658. // `100 Continue`.
  17659. std::string buf;
  17660. char tmp[1024];
  17661. while (buf.find("\r\n\r\n") == std::string::npos) {
  17662. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17663. if (n <= 0) { break; }
  17664. buf.append(tmp, static_cast<size_t>(n));
  17665. }
  17666. // A correct client sends the body now; count what arrives.
  17667. auto pos = buf.find("\r\n\r\n");
  17668. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  17669. while (body < 4096) {
  17670. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17671. if (n <= 0) { break; }
  17672. body += static_cast<size_t>(n);
  17673. }
  17674. server_body_bytes = body;
  17675. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  17676. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  17677. SSL_shutdown(ssl);
  17678. }
  17679. SSL_free(ssl);
  17680. detail::close_socket(cli);
  17681. SSL_CTX_free(ctx);
  17682. });
  17683. auto se = detail::scope_exit([&] {
  17684. server_thread.join();
  17685. detail::close_socket(srv);
  17686. });
  17687. SSLClient cli("127.0.0.1", port);
  17688. cli.enable_server_certificate_verification(false);
  17689. cli.set_connection_timeout(5, 0);
  17690. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  17691. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  17692. std::string body(4096, 'A');
  17693. auto res = cli.Put("/api/test", body, "application/json");
  17694. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  17695. EXPECT_EQ(StatusCode::OK_200, res->status);
  17696. EXPECT_EQ(body.size(), server_body_bytes.load());
  17697. }
  17698. #endif
  17699. template <typename S, typename C>
  17700. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  17701. svr.Get("/stream", [&](const Request &, Response &res) {
  17702. auto data = new std::string("01234567890123456789");
  17703. res.set_content_provider(
  17704. data->size(), "text/plain",
  17705. [&, data](size_t offset, size_t length, DataSink &sink) {
  17706. const size_t DATA_CHUNK_SIZE = 4;
  17707. const auto &d = *data;
  17708. std::this_thread::sleep_for(std::chrono::seconds(1));
  17709. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  17710. return true;
  17711. },
  17712. [data](bool success) {
  17713. EXPECT_FALSE(success);
  17714. delete data;
  17715. });
  17716. });
  17717. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  17718. auto i = new size_t(0);
  17719. res.set_content_provider(
  17720. "text/plain",
  17721. [i](size_t, DataSink &sink) {
  17722. if (*i < 5) {
  17723. std::this_thread::sleep_for(std::chrono::seconds(1));
  17724. sink.write("abcd", 4);
  17725. (*i)++;
  17726. } else {
  17727. sink.done();
  17728. }
  17729. return true;
  17730. },
  17731. [i](bool success) {
  17732. EXPECT_FALSE(success);
  17733. delete i;
  17734. });
  17735. });
  17736. svr.Get("/chunked", [&](const Request &, Response &res) {
  17737. auto i = new size_t(0);
  17738. res.set_chunked_content_provider(
  17739. "text/plain",
  17740. [i](size_t, DataSink &sink) {
  17741. if (*i < 5) {
  17742. std::this_thread::sleep_for(std::chrono::seconds(1));
  17743. sink.os << "abcd";
  17744. (*i)++;
  17745. } else {
  17746. sink.done();
  17747. }
  17748. return true;
  17749. },
  17750. [i](bool success) {
  17751. EXPECT_FALSE(success);
  17752. delete i;
  17753. });
  17754. });
  17755. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17756. auto se = detail::scope_exit([&] {
  17757. svr.stop();
  17758. listen_thread.join();
  17759. ASSERT_FALSE(svr.is_running());
  17760. });
  17761. svr.wait_until_ready();
  17762. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  17763. {
  17764. auto start = std::chrono::steady_clock::now();
  17765. auto res = cli.Get("/stream");
  17766. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17767. std::chrono::steady_clock::now() - start)
  17768. .count();
  17769. ASSERT_FALSE(res);
  17770. EXPECT_EQ(Error::Read, res.error());
  17771. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17772. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17773. }
  17774. {
  17775. auto start = std::chrono::steady_clock::now();
  17776. auto res = cli.Get("/stream_without_length");
  17777. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17778. std::chrono::steady_clock::now() - start)
  17779. .count();
  17780. ASSERT_FALSE(res);
  17781. EXPECT_EQ(Error::Read, res.error());
  17782. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17783. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17784. }
  17785. {
  17786. auto start = std::chrono::steady_clock::now();
  17787. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  17788. EXPECT_EQ("abcd", string(data, data_length));
  17789. return true;
  17790. });
  17791. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17792. std::chrono::steady_clock::now() - start)
  17793. .count();
  17794. ASSERT_FALSE(res);
  17795. EXPECT_EQ(Error::Read, res.error());
  17796. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17797. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17798. }
  17799. }
  17800. TEST(MaxTimeoutTest, ContentStream) {
  17801. time_t timeout = 2000;
  17802. time_t threshold = 200;
  17803. Server svr;
  17804. Client cli("localhost", PORT);
  17805. max_timeout_test(svr, cli, timeout, threshold);
  17806. }
  17807. #ifdef CPPHTTPLIB_SSL_ENABLED
  17808. TEST(MaxTimeoutTest, ContentStreamSSL) {
  17809. time_t timeout = 2000;
  17810. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  17811. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17812. SSLClient cli("localhost", PORT);
  17813. cli.enable_server_certificate_verification(false);
  17814. max_timeout_test(svr, cli, timeout, threshold);
  17815. }
  17816. #endif
  17817. class EventDispatcher {
  17818. public:
  17819. EventDispatcher() {}
  17820. bool wait_event(DataSink *sink) {
  17821. unique_lock<mutex> lk(m_);
  17822. int id = id_;
  17823. // Wait with timeout to prevent hanging if client disconnects
  17824. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17825. [&] { return cid_ == id; })) {
  17826. return false; // Timeout occurred
  17827. }
  17828. sink->write(message_.data(), message_.size());
  17829. return true;
  17830. }
  17831. void send_event(const string &message) {
  17832. lock_guard<mutex> lk(m_);
  17833. cid_ = id_++;
  17834. message_ = message;
  17835. cv_.notify_all();
  17836. }
  17837. private:
  17838. mutex m_;
  17839. condition_variable cv_;
  17840. atomic_int id_{0};
  17841. atomic_int cid_{-1};
  17842. string message_;
  17843. };
  17844. TEST(ClientInThreadTest, Issue2068) {
  17845. EventDispatcher ed;
  17846. Server svr;
  17847. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17848. res.set_chunked_content_provider("text/event-stream",
  17849. [&](size_t /*offset*/, DataSink &sink) {
  17850. return ed.wait_event(&sink);
  17851. });
  17852. });
  17853. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17854. svr.wait_until_ready();
  17855. thread event_thread([&] {
  17856. int id = 0;
  17857. while (svr.is_running()) {
  17858. this_thread::sleep_for(chrono::milliseconds(500));
  17859. std::stringstream ss;
  17860. ss << "data: " << id << "\n\n";
  17861. ed.send_event(ss.str());
  17862. id++;
  17863. }
  17864. });
  17865. auto se = detail::scope_exit([&] {
  17866. svr.stop();
  17867. listen_thread.join();
  17868. event_thread.join();
  17869. ASSERT_FALSE(svr.is_running());
  17870. });
  17871. {
  17872. auto client = detail::make_unique<Client>(HOST, PORT);
  17873. client->set_read_timeout(std::chrono::minutes(10));
  17874. std::atomic<bool> stop{false};
  17875. std::thread t([&] {
  17876. client->Get("/event1",
  17877. [&](const char *, size_t) -> bool { return !stop; });
  17878. });
  17879. std::this_thread::sleep_for(std::chrono::seconds(2));
  17880. stop = true;
  17881. client->stop();
  17882. t.join();
  17883. // Reset client after thread has finished
  17884. client.reset();
  17885. }
  17886. }
  17887. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17888. auto handled = false;
  17889. Server svr;
  17890. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17891. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17892. auto se = detail::scope_exit([&] {
  17893. svr.stop();
  17894. t.join();
  17895. ASSERT_FALSE(svr.is_running());
  17896. ASSERT_FALSE(handled);
  17897. });
  17898. svr.wait_until_ready();
  17899. // Two Content-Length headers with different values — must be rejected
  17900. auto req = "POST /test HTTP/1.1\r\n"
  17901. "Content-Length: 5\r\n"
  17902. "Content-Length: 10\r\n"
  17903. "\r\n"
  17904. "hello";
  17905. std::string response;
  17906. ASSERT_TRUE(send_request(1, req, &response));
  17907. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17908. response.substr(0, response.find("\r\n")));
  17909. }
  17910. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17911. auto handled = false;
  17912. Server svr;
  17913. svr.Post("/test", [&](const Request &, Response &res) {
  17914. handled = true;
  17915. res.set_content("ok", "text/plain");
  17916. });
  17917. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17918. auto se = detail::scope_exit([&] {
  17919. svr.stop();
  17920. t.join();
  17921. ASSERT_FALSE(svr.is_running());
  17922. ASSERT_TRUE(handled);
  17923. });
  17924. svr.wait_until_ready();
  17925. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17926. auto req = "POST /test HTTP/1.1\r\n"
  17927. "Host: localhost\r\n"
  17928. "Content-Length: 5\r\n"
  17929. "Content-Length: 5\r\n"
  17930. "\r\n"
  17931. "hello";
  17932. std::string response;
  17933. ASSERT_TRUE(send_request(1, req, &response));
  17934. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17935. }
  17936. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17937. Server svr;
  17938. svr.Get("/test", [](const Request &, Response &res) {
  17939. res.set_content("ok", "text/plain");
  17940. });
  17941. auto port = svr.bind_to_any_port(HOST);
  17942. thread t = thread([&] { svr.listen_after_bind(); });
  17943. auto se = detail::scope_exit([&] {
  17944. svr.stop();
  17945. t.join();
  17946. ASSERT_FALSE(svr.is_running());
  17947. });
  17948. svr.wait_until_ready();
  17949. auto status_line = [&](const std::string &host_lines) {
  17950. std::string res;
  17951. send_request(
  17952. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17953. &res, port);
  17954. return res.substr(0, res.find("\r\n"));
  17955. };
  17956. const char *accepted[] = {
  17957. "Host: localhost\r\n",
  17958. "Host: a.example:8080\r\n",
  17959. "Host: my_service\r\n",
  17960. "Host: [::1]:8080\r\n",
  17961. "Host: [fe80::1%25eth0]\r\n",
  17962. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17963. };
  17964. for (auto host_lines : accepted) {
  17965. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17966. }
  17967. const char *rejected[] = {
  17968. "Host: a.example\r\nHost: b.example\r\n",
  17969. "Host: a.example\r\nHost: a.example\r\n",
  17970. "Host: a@b.example\r\n",
  17971. "Host: a.example/b\r\n",
  17972. "Host: a.example\\b\r\n",
  17973. "Host: a.example?b\r\n",
  17974. "Host: a.example#b\r\n",
  17975. "Host: a.example b.example\r\n",
  17976. };
  17977. for (auto host_lines : rejected) {
  17978. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17979. << host_lines;
  17980. }
  17981. }
  17982. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17983. Server svr;
  17984. svr.Get("/", [](const Request &req, Response &res) {
  17985. EXPECT_EQ(2U, req.trailers.size());
  17986. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17987. // Denied
  17988. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17989. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17990. // Accepted
  17991. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17992. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17993. EXPECT_TRUE(req.has_trailer("X-World"));
  17994. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17995. res.set_content("ok", "text/plain");
  17996. });
  17997. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17998. auto se = detail::scope_exit([&] {
  17999. svr.stop();
  18000. t.join();
  18001. ASSERT_FALSE(svr.is_running());
  18002. });
  18003. svr.wait_until_ready();
  18004. const std::string req = "GET / HTTP/1.1\r\n"
  18005. "Transfer-Encoding: chunked\r\n"
  18006. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18007. "\r\n"
  18008. "0\r\n"
  18009. "Content-Length: 10\r\n"
  18010. "Host: internal.local\r\n"
  18011. "Content-Type: malicious/content\r\n"
  18012. "Cookie: any\r\n"
  18013. "Set-Cookie: any\r\n"
  18014. "X-Forwarded-For: attacker.com\r\n"
  18015. "X-Real-Ip: 1.1.1.1\r\n"
  18016. "X-Hello: hello\r\n"
  18017. "X-World: world\r\n"
  18018. "\r\n";
  18019. std::string res;
  18020. ASSERT_TRUE(send_request(1, req, &res));
  18021. }
  18022. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18023. // several field lines, and the combined value is what has to be parsed. A
  18024. // Trailer field split across lines therefore declares every name it lists;
  18025. // reading only the first line silently drops the trailers the later lines
  18026. // declare. The prohibited-trailer filter still applies to every line.
  18027. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18028. Server svr;
  18029. size_t observed_trailer_count = 0;
  18030. std::string observed_hello;
  18031. std::string observed_world;
  18032. bool observed_content_length = true;
  18033. svr.Get("/", [&](const Request &req, Response &res) {
  18034. observed_trailer_count = req.trailers.size();
  18035. observed_hello = req.get_trailer_value("X-Hello");
  18036. observed_world = req.get_trailer_value("X-World");
  18037. observed_content_length = req.has_trailer("Content-Length");
  18038. res.set_content("ok", "text/plain");
  18039. });
  18040. auto port = svr.bind_to_any_port(HOST);
  18041. thread t = thread([&]() { svr.listen_after_bind(); });
  18042. auto se = detail::scope_exit([&] {
  18043. svr.stop();
  18044. t.join();
  18045. ASSERT_FALSE(svr.is_running());
  18046. });
  18047. svr.wait_until_ready();
  18048. const std::string req = "GET / HTTP/1.1\r\n"
  18049. "Host: localhost\r\n"
  18050. "Transfer-Encoding: chunked\r\n"
  18051. "Trailer: X-Hello\r\n"
  18052. "Trailer: X-World, Content-Length\r\n"
  18053. "\r\n"
  18054. "0\r\n"
  18055. "X-Hello: hello\r\n"
  18056. "X-World: world\r\n"
  18057. "Content-Length: 10\r\n"
  18058. "\r\n";
  18059. std::string res;
  18060. ASSERT_TRUE(send_request(1, req, &res, port));
  18061. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18062. // Accepted: both field lines contribute to the declared set
  18063. EXPECT_EQ(2U, observed_trailer_count);
  18064. EXPECT_EQ(observed_hello, "hello");
  18065. EXPECT_EQ(observed_world, "world");
  18066. // Denied: a prohibited name stays prohibited on a later field line
  18067. EXPECT_FALSE(observed_content_length);
  18068. }
  18069. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18070. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18071. // unbounded run of fields that are never declared, because the counter would
  18072. // only advance for declared fields.
  18073. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18074. Server svr;
  18075. bool handler_called = false;
  18076. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18077. handler_called = true;
  18078. res.set_content("ok", "text/plain");
  18079. });
  18080. auto port = svr.bind_to_any_port(HOST);
  18081. thread t = thread([&]() { svr.listen_after_bind(); });
  18082. auto se = detail::scope_exit([&] {
  18083. svr.stop();
  18084. t.join();
  18085. ASSERT_FALSE(svr.is_running());
  18086. });
  18087. svr.wait_until_ready();
  18088. // Declare nothing, then send far more undeclared trailer fields than the
  18089. // header-count limit. Parsing must stop and reject the request rather than
  18090. // read every line.
  18091. std::string req = "GET / HTTP/1.1\r\n"
  18092. "Transfer-Encoding: chunked\r\n"
  18093. "\r\n"
  18094. "0\r\n";
  18095. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18096. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18097. }
  18098. req += "\r\n";
  18099. std::string res;
  18100. ASSERT_TRUE(send_request(1, req, &res, port));
  18101. // The request is rejected before the handler runs.
  18102. EXPECT_FALSE(handler_called);
  18103. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18104. }
  18105. // The set of declared trailer names is capped so a peer cannot grow it without
  18106. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18107. // declared past the cap is not honored, even if the field is actually sent.
  18108. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18109. Server svr;
  18110. // One name inside the cap and one past it, so the test tracks the cap rather
  18111. // than a fixed count.
  18112. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18113. const std::string within_cap_name = "X-T-0";
  18114. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18115. bool observed_within_cap = false;
  18116. bool observed_past_cap = false;
  18117. svr.Get("/", [&](const Request &req, Response &res) {
  18118. observed_within_cap = req.has_trailer(within_cap_name);
  18119. observed_past_cap = req.has_trailer(past_cap_name);
  18120. res.set_content("ok", "text/plain");
  18121. });
  18122. auto port = svr.bind_to_any_port(HOST);
  18123. thread t = thread([&]() { svr.listen_after_bind(); });
  18124. auto se = detail::scope_exit([&] {
  18125. svr.stop();
  18126. t.join();
  18127. ASSERT_FALSE(svr.is_running());
  18128. });
  18129. svr.wait_until_ready();
  18130. // Declare more trailer names than the cap in a single Trailer field, then
  18131. // actually send the first (within the cap) and the last (past it).
  18132. std::string trailer_decl = "Trailer: ";
  18133. for (int i = 0; i < declared_count; i++) {
  18134. if (i != 0) { trailer_decl += ", "; }
  18135. trailer_decl += "X-T-" + std::to_string(i);
  18136. }
  18137. trailer_decl += "\r\n";
  18138. const std::string req = "GET / HTTP/1.1\r\n"
  18139. "Host: localhost\r\n"
  18140. "Transfer-Encoding: chunked\r\n" +
  18141. trailer_decl +
  18142. "\r\n"
  18143. "0\r\n" +
  18144. within_cap_name + ": a\r\n" + past_cap_name +
  18145. ": b\r\n"
  18146. "\r\n";
  18147. std::string res;
  18148. ASSERT_TRUE(send_request(1, req, &res, port));
  18149. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18150. // A name within the cap is honored; one declared past the cap is dropped.
  18151. EXPECT_TRUE(observed_within_cap);
  18152. EXPECT_FALSE(observed_past_cap);
  18153. }
  18154. // A direct client that is not listed in trusted_proxies must not be able to
  18155. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18156. // the peer address on the actual TCP connection determines whether the
  18157. // header is honored.
  18158. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18159. Server svr;
  18160. // Deliberately does NOT include the loopback address the test client
  18161. // actually connects from, so the direct connection is not a trusted proxy.
  18162. svr.set_trusted_proxies({"203.0.113.66"});
  18163. std::string observed_remote_addr;
  18164. svr.Get("/ip", [&](const Request &req, Response &res) {
  18165. observed_remote_addr = req.remote_addr;
  18166. res.set_content("ok", "text/plain");
  18167. });
  18168. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18169. auto se = detail::scope_exit([&] {
  18170. svr.stop();
  18171. t.join();
  18172. ASSERT_FALSE(svr.is_running());
  18173. });
  18174. svr.wait_until_ready();
  18175. Client cli(HOST, PORT);
  18176. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18178. EXPECT_EQ(StatusCode::OK_200, res->status);
  18179. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18180. // ignored entirely and the real connection-level address retained.
  18181. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18182. observed_remote_addr == "127.0.0.1");
  18183. }
  18184. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18185. Server svr;
  18186. std::string observed_remote_addr;
  18187. std::string observed_xff;
  18188. svr.Get("/ip", [&](const Request &req, Response &res) {
  18189. observed_remote_addr = req.remote_addr;
  18190. observed_xff = req.get_header_value("X-Forwarded-For");
  18191. res.set_content("ok", "text/plain");
  18192. });
  18193. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18194. auto se = detail::scope_exit([&] {
  18195. svr.stop();
  18196. t.join();
  18197. ASSERT_FALSE(svr.is_running());
  18198. });
  18199. svr.wait_until_ready();
  18200. Client cli(HOST, PORT);
  18201. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18203. EXPECT_EQ(StatusCode::OK_200, res->status);
  18204. EXPECT_EQ(observed_xff, "203.0.113.66");
  18205. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18206. observed_remote_addr == "127.0.0.1");
  18207. }
  18208. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18209. Server svr;
  18210. svr.set_trusted_proxies({"203.0.113.66"});
  18211. std::string observed_remote_addr;
  18212. std::string observed_xff;
  18213. svr.Get("/ip", [&](const Request &req, Response &res) {
  18214. observed_remote_addr = req.remote_addr;
  18215. observed_xff = req.get_header_value("X-Forwarded-For");
  18216. res.set_content("ok", "text/plain");
  18217. });
  18218. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18219. auto se = detail::scope_exit([&] {
  18220. svr.stop();
  18221. t.join();
  18222. ASSERT_FALSE(svr.is_running());
  18223. });
  18224. svr.wait_until_ready();
  18225. Client cli(HOST, PORT);
  18226. auto res = cli.Get("/ip");
  18227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18228. EXPECT_EQ(StatusCode::OK_200, res->status);
  18229. EXPECT_EQ(observed_xff, "");
  18230. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18231. observed_remote_addr == "127.0.0.1");
  18232. }
  18233. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18234. Server svr;
  18235. // Include the loopback address the test client actually connects from, so
  18236. // the direct connection itself is recognized as the trusted proxy hop.
  18237. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18238. std::string observed_remote_addr;
  18239. std::string observed_xff;
  18240. svr.Get("/ip", [&](const Request &req, Response &res) {
  18241. observed_remote_addr = req.remote_addr;
  18242. observed_xff = req.get_header_value("X-Forwarded-For");
  18243. res.set_content("ok", "text/plain");
  18244. });
  18245. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18246. auto se = detail::scope_exit([&] {
  18247. svr.stop();
  18248. t.join();
  18249. ASSERT_FALSE(svr.is_running());
  18250. });
  18251. svr.wait_until_ready();
  18252. Client cli(HOST, PORT);
  18253. auto res = cli.Get(
  18254. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18256. EXPECT_EQ(StatusCode::OK_200, res->status);
  18257. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18258. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18259. }
  18260. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18261. Server svr;
  18262. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  18263. std::string observed_remote_addr;
  18264. std::string observed_xff;
  18265. svr.Get("/ip", [&](const Request &req, Response &res) {
  18266. observed_remote_addr = req.remote_addr;
  18267. observed_xff = req.get_header_value("X-Forwarded-For");
  18268. res.set_content("ok", "text/plain");
  18269. });
  18270. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18271. auto se = detail::scope_exit([&] {
  18272. svr.stop();
  18273. t.join();
  18274. ASSERT_FALSE(svr.is_running());
  18275. });
  18276. svr.wait_until_ready();
  18277. Client cli(HOST, PORT);
  18278. auto res = cli.Get(
  18279. "/ip",
  18280. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18282. EXPECT_EQ(StatusCode::OK_200, res->status);
  18283. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18284. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18285. }
  18286. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18287. Server svr;
  18288. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18289. std::string observed_remote_addr;
  18290. std::string observed_xff;
  18291. svr.Get("/ip", [&](const Request &req, Response &res) {
  18292. observed_remote_addr = req.remote_addr;
  18293. observed_xff = req.get_header_value("X-Forwarded-For");
  18294. res.set_content("ok", "text/plain");
  18295. });
  18296. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18297. auto se = detail::scope_exit([&] {
  18298. svr.stop();
  18299. t.join();
  18300. ASSERT_FALSE(svr.is_running());
  18301. });
  18302. svr.wait_until_ready();
  18303. Client cli(HOST, PORT);
  18304. auto res = cli.Get(
  18305. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18307. EXPECT_EQ(StatusCode::OK_200, res->status);
  18308. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18309. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18310. // and must not be selected.
  18311. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18312. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18313. }
  18314. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18315. Server svr;
  18316. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18317. std::string observed_remote_addr;
  18318. svr.Get("/ip", [&](const Request &req, Response &res) {
  18319. observed_remote_addr = req.remote_addr;
  18320. res.set_content("ok", "text/plain");
  18321. });
  18322. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18323. auto se = detail::scope_exit([&] {
  18324. svr.stop();
  18325. t.join();
  18326. ASSERT_FALSE(svr.is_running());
  18327. });
  18328. svr.wait_until_ready();
  18329. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  18330. // a forged address and the trusted proxy's own address; the forged value must
  18331. // not win over the address the trusted proxy actually recorded.
  18332. Client cli(HOST, PORT);
  18333. auto res = cli.Get(
  18334. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  18335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18336. EXPECT_EQ(StatusCode::OK_200, res->status);
  18337. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  18338. }
  18339. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  18340. Server svr;
  18341. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18342. std::string observed_remote_addr;
  18343. std::string observed_xff;
  18344. svr.Get("/ip", [&](const Request &req, Response &res) {
  18345. observed_remote_addr = req.remote_addr;
  18346. observed_xff = req.get_header_value("X-Forwarded-For");
  18347. res.set_content("ok", "text/plain");
  18348. });
  18349. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18350. auto se = detail::scope_exit([&] {
  18351. svr.stop();
  18352. t.join();
  18353. ASSERT_FALSE(svr.is_running());
  18354. });
  18355. svr.wait_until_ready();
  18356. Client cli(HOST, PORT);
  18357. auto res = cli.Get(
  18358. "/ip",
  18359. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18361. EXPECT_EQ(StatusCode::OK_200, res->status);
  18362. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18363. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18364. }
  18365. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  18366. Server svr;
  18367. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18368. std::string observed_remote_addr;
  18369. std::string observed_xff;
  18370. svr.Get("/ip", [&](const Request &req, Response &res) {
  18371. observed_remote_addr = req.remote_addr;
  18372. observed_xff = req.get_header_value("X-Forwarded-For");
  18373. res.set_content("ok", "text/plain");
  18374. });
  18375. thread t = thread([&]() { svr.listen(HOST, PORT); });
  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. std::string raw_req =
  18383. "GET /ip HTTP/1.1\r\n"
  18384. "Host: localhost\r\n"
  18385. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  18386. "Connection: close\r\n"
  18387. "\r\n";
  18388. std::string out;
  18389. ASSERT_TRUE(send_request(5, raw_req, &out));
  18390. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18391. // Header parser trims surrounding whitespace of the header value
  18392. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  18393. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18394. }
  18395. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  18396. // one comma-joined value, in the order received. Proxies such as HAProxy append
  18397. // their own X-Forwarded-For as a separate field line rather than extending the
  18398. // one the client sent, so every occurrence has to be taken into account.
  18399. // Reading only the first one hands back the address the client chose.
  18400. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  18401. Server svr;
  18402. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18403. std::string observed_remote_addr;
  18404. size_t observed_xff_count = 0;
  18405. svr.Get("/ip", [&](const Request &req, Response &res) {
  18406. observed_remote_addr = req.remote_addr;
  18407. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  18408. res.set_content("ok", "text/plain");
  18409. });
  18410. auto port = svr.bind_to_any_port(HOST);
  18411. thread t = thread([&]() { svr.listen_after_bind(); });
  18412. auto se = detail::scope_exit([&] {
  18413. svr.stop();
  18414. t.join();
  18415. ASSERT_FALSE(svr.is_running());
  18416. });
  18417. svr.wait_until_ready();
  18418. // The client supplies the first field line; the trusted proxy appends the
  18419. // address it observed as a second one.
  18420. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  18421. "Host: localhost\r\n"
  18422. "X-Forwarded-For: 1.2.3.4\r\n"
  18423. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  18424. "Connection: close\r\n"
  18425. "\r\n";
  18426. std::string out;
  18427. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18428. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18429. EXPECT_EQ(observed_xff_count, 2U);
  18430. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18431. // The same chain spread over one field line per hop derives the same client
  18432. // address, i.e. the split and the comma-joined representations agree.
  18433. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  18434. "Host: localhost\r\n"
  18435. "X-Forwarded-For: 1.2.3.4\r\n"
  18436. "X-Forwarded-For: 198.51.100.23\r\n"
  18437. "X-Forwarded-For: 192.0.2.45\r\n"
  18438. "Connection: close\r\n"
  18439. "\r\n";
  18440. out.clear();
  18441. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  18442. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18443. EXPECT_EQ(observed_xff_count, 3U);
  18444. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18445. }
  18446. // An X-Forwarded-For header whose value parses to zero IP segments must not
  18447. // crash the server (it used to call front() on an empty vector inside
  18448. // get_client_ip). The connection-level remote address must be retained instead.
  18449. static void run_malformed_xff_test(const std::string &xff_value) {
  18450. Server svr;
  18451. svr.set_trusted_proxies({"192.0.2.45"});
  18452. std::string observed_remote_addr;
  18453. svr.Get("/ip", [&](const Request &req, Response &res) {
  18454. observed_remote_addr = req.remote_addr;
  18455. res.set_content("ok", "text/plain");
  18456. });
  18457. int port = 0;
  18458. thread t = thread([&]() {
  18459. port = svr.bind_to_any_port(HOST);
  18460. svr.listen_after_bind();
  18461. });
  18462. auto se = detail::scope_exit([&] {
  18463. svr.stop();
  18464. t.join();
  18465. ASSERT_FALSE(svr.is_running());
  18466. });
  18467. svr.wait_until_ready();
  18468. Client cli(HOST, port);
  18469. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  18470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18471. EXPECT_EQ(StatusCode::OK_200, res->status);
  18472. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18473. observed_remote_addr == "127.0.0.1");
  18474. }
  18475. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  18476. run_malformed_xff_test("");
  18477. }
  18478. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  18479. run_malformed_xff_test(",");
  18480. }
  18481. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  18482. run_malformed_xff_test(", , ,");
  18483. }
  18484. // The same rule applies to Accept: a request whose acceptable types are spread
  18485. // over several field lines must be negotiated against all of them.
  18486. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  18487. // case-insensitive connection options. Comparing the whole field value against
  18488. // one option misses a client that sends several of them, and misses every
  18489. // casing but the one written in the comparison.
  18490. //
  18491. // Sends req, reads the response, then reuses the same socket for a second
  18492. // request to find out whether the server kept the connection.
  18493. static void probe_connection_reuse(int port, const std::string &req,
  18494. bool *announced_close, bool *reusable) {
  18495. auto error = Error::Success;
  18496. auto sock = detail::create_client_socket(
  18497. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18498. /*connection_timeout_sec=*/5, 0,
  18499. /*read_timeout_sec=*/1, 0,
  18500. /*write_timeout_sec=*/5, 0, std::string(), error);
  18501. ASSERT_NE(sock, INVALID_SOCKET);
  18502. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  18503. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  18504. "Host: localhost\r\n"
  18505. "Connection: close\r\n"
  18506. "\r\n";
  18507. std::string first_response;
  18508. std::string second_response;
  18509. detail::process_client_socket(
  18510. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  18511. [&](Stream &strm) {
  18512. if (strm.write(req.data(), req.size()) !=
  18513. static_cast<ssize_t>(req.size())) {
  18514. return false;
  18515. }
  18516. char buf[512];
  18517. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  18518. // Headers plus the two-byte body of the handler below
  18519. while (reader.getline()) {
  18520. first_response += reader.ptr();
  18521. if (first_response.find("ok") != std::string::npos) { break; }
  18522. }
  18523. if (strm.write(second.data(), second.size()) !=
  18524. static_cast<ssize_t>(second.size())) {
  18525. return true;
  18526. }
  18527. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  18528. while (reader2.getline()) {
  18529. second_response += reader2.ptr();
  18530. if (second_response.find("ok") != std::string::npos) { break; }
  18531. }
  18532. return true;
  18533. });
  18534. *announced_close =
  18535. first_response.find("Connection: close") != std::string::npos;
  18536. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18537. }
  18538. class ConnectionTokenTest : public ::testing::Test {
  18539. protected:
  18540. void SetUp() override {
  18541. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18542. res.set_content("ok", "text/plain");
  18543. });
  18544. port_ = svr_.bind_to_any_port(HOST);
  18545. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18546. svr_.wait_until_ready();
  18547. }
  18548. void TearDown() override {
  18549. svr_.stop();
  18550. if (thread_.joinable()) { thread_.join(); }
  18551. }
  18552. Server svr_;
  18553. int port_ = 0;
  18554. thread thread_;
  18555. };
  18556. // "close" alongside another option still closes the connection, and the
  18557. // response says so rather than leaving the peer to discover it.
  18558. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18559. bool announced_close = false;
  18560. bool reusable = true;
  18561. probe_connection_reuse(port_,
  18562. "GET /keepalive HTTP/1.1\r\n"
  18563. "Host: localhost\r\n"
  18564. "Connection: keep-alive, close\r\n"
  18565. "\r\n",
  18566. &announced_close, &reusable);
  18567. EXPECT_TRUE(announced_close);
  18568. EXPECT_FALSE(reusable);
  18569. }
  18570. // "close" split over two field lines is the same list, so it is honored too.
  18571. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18572. bool announced_close = false;
  18573. bool reusable = true;
  18574. probe_connection_reuse(port_,
  18575. "GET /keepalive HTTP/1.1\r\n"
  18576. "Host: localhost\r\n"
  18577. "Connection: keep-alive\r\n"
  18578. "Connection: close\r\n"
  18579. "\r\n",
  18580. &announced_close, &reusable);
  18581. EXPECT_TRUE(announced_close);
  18582. EXPECT_FALSE(reusable);
  18583. }
  18584. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18585. // keep-alive in the spelling everyone actually sends keeps its connection.
  18586. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18587. bool announced_close = false;
  18588. bool reusable = false;
  18589. probe_connection_reuse(port_,
  18590. "GET /keepalive HTTP/1.0\r\n"
  18591. "Host: localhost\r\n"
  18592. "Connection: keep-alive\r\n"
  18593. "\r\n",
  18594. &announced_close, &reusable);
  18595. EXPECT_FALSE(announced_close);
  18596. EXPECT_TRUE(reusable);
  18597. }
  18598. // A token the value merely contains is not the token itself.
  18599. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  18600. bool announced_close = false;
  18601. bool reusable = false;
  18602. probe_connection_reuse(port_,
  18603. "GET /keepalive HTTP/1.1\r\n"
  18604. "Host: localhost\r\n"
  18605. "Connection: notclose\r\n"
  18606. "\r\n",
  18607. &announced_close, &reusable);
  18608. EXPECT_FALSE(announced_close);
  18609. EXPECT_TRUE(reusable);
  18610. }
  18611. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  18612. Server svr;
  18613. std::vector<std::string> observed_types;
  18614. svr.Get("/", [&](const Request &req, Response &res) {
  18615. observed_types = req.accept_content_types;
  18616. res.set_content("ok", "text/plain");
  18617. });
  18618. auto port = svr.bind_to_any_port(HOST);
  18619. thread t = thread([&]() { svr.listen_after_bind(); });
  18620. auto se = detail::scope_exit([&] {
  18621. svr.stop();
  18622. t.join();
  18623. ASSERT_FALSE(svr.is_running());
  18624. });
  18625. svr.wait_until_ready();
  18626. Client cli(HOST, port);
  18627. Headers headers;
  18628. headers.emplace("Accept", "text/plain;q=0.5");
  18629. headers.emplace("Accept", "application/json");
  18630. auto res = cli.Get("/", headers);
  18631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18632. EXPECT_EQ(StatusCode::OK_200, res->status);
  18633. // Sorted by q-value, so the second field line's type comes first
  18634. ASSERT_EQ(2U, observed_types.size());
  18635. EXPECT_EQ("application/json", observed_types[0]);
  18636. EXPECT_EQ("text/plain", observed_types[1]);
  18637. }
  18638. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  18639. // empty field line must not contribute a bare comma to the combined value.
  18640. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  18641. Server svr;
  18642. std::vector<std::string> observed_types;
  18643. svr.Get("/", [&](const Request &req, Response &res) {
  18644. observed_types = req.accept_content_types;
  18645. res.set_content("ok", "text/plain");
  18646. });
  18647. auto port = svr.bind_to_any_port(HOST);
  18648. thread t = thread([&]() { svr.listen_after_bind(); });
  18649. auto se = detail::scope_exit([&] {
  18650. svr.stop();
  18651. t.join();
  18652. ASSERT_FALSE(svr.is_running());
  18653. });
  18654. svr.wait_until_ready();
  18655. // Empty first field line, then a real one
  18656. std::string raw_req = "GET / HTTP/1.1\r\n"
  18657. "Host: localhost\r\n"
  18658. "Accept:\r\n"
  18659. "Accept: application/json\r\n"
  18660. "Connection: close\r\n"
  18661. "\r\n";
  18662. std::string out;
  18663. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18664. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18665. ASSERT_EQ(1U, observed_types.size());
  18666. EXPECT_EQ("application/json", observed_types[0]);
  18667. }
  18668. // The skip in get_combined_header_value() is what keeps an empty field line
  18669. // from contributing a bare comma. Only a trailing empty field line exercises
  18670. // it: a leading one is already covered by the "combined is still empty" check,
  18671. // and parse_accept_header() now ignores the empty element either way, so the
  18672. // request-level test above can no longer tell the two apart.
  18673. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  18674. Headers headers;
  18675. headers.emplace("Accept", "text/html");
  18676. headers.emplace("Accept", "");
  18677. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  18678. headers.clear();
  18679. headers.emplace("Accept", "");
  18680. headers.emplace("Accept", "application/json");
  18681. EXPECT_EQ("application/json",
  18682. detail::get_combined_header_value(headers, "Accept"));
  18683. }
  18684. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18685. // An encoding offered on a later Accept-Encoding field line is still offered.
  18686. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  18687. Server svr;
  18688. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18689. res.set_content(std::string(1024, 'x'), "text/plain");
  18690. });
  18691. auto port = svr.bind_to_any_port(HOST);
  18692. thread t = thread([&]() { svr.listen_after_bind(); });
  18693. auto se = detail::scope_exit([&] {
  18694. svr.stop();
  18695. t.join();
  18696. ASSERT_FALSE(svr.is_running());
  18697. });
  18698. svr.wait_until_ready();
  18699. Client cli(HOST, port);
  18700. cli.set_decompress(false);
  18701. Headers headers;
  18702. headers.emplace("Accept-Encoding", "identity");
  18703. headers.emplace("Accept-Encoding", "gzip");
  18704. auto res = cli.Get("/", headers);
  18705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18706. EXPECT_EQ(StatusCode::OK_200, res->status);
  18707. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  18708. }
  18709. #endif
  18710. #ifndef _WIN32
  18711. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  18712. Server svr;
  18713. svr.Post("/post", [&](const Request &req, Response &res) {
  18714. res.set_content(req.body, "text/plain");
  18715. });
  18716. svr.Put("/put", [&](const Request &req, Response &res) {
  18717. res.set_content(req.body, "text/plain");
  18718. });
  18719. svr.Patch("/patch", [&](const Request &req, Response &res) {
  18720. res.set_content(req.body, "text/plain");
  18721. });
  18722. svr.Delete("/delete", [&](const Request &req, Response &res) {
  18723. res.set_content(req.body, "text/plain");
  18724. });
  18725. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18726. auto se = detail::scope_exit([&] {
  18727. svr.stop();
  18728. t.join();
  18729. ASSERT_FALSE(svr.is_running());
  18730. });
  18731. svr.wait_until_ready();
  18732. std::string resp;
  18733. // POST without Content-Length
  18734. ASSERT_TRUE(send_request(5,
  18735. "POST /post HTTP/1.1\r\n"
  18736. "Host: localhost\r\n"
  18737. "Connection: close\r\n"
  18738. "\r\n",
  18739. &resp));
  18740. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18741. // PUT without Content-Length
  18742. resp.clear();
  18743. ASSERT_TRUE(send_request(5,
  18744. "PUT /put HTTP/1.1\r\n"
  18745. "Host: localhost\r\n"
  18746. "Connection: close\r\n"
  18747. "\r\n",
  18748. &resp));
  18749. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18750. // PATCH without Content-Length
  18751. resp.clear();
  18752. ASSERT_TRUE(send_request(5,
  18753. "PATCH /patch HTTP/1.1\r\n"
  18754. "Host: localhost\r\n"
  18755. "Connection: close\r\n"
  18756. "\r\n",
  18757. &resp));
  18758. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18759. // DELETE without Content-Length
  18760. resp.clear();
  18761. ASSERT_TRUE(send_request(5,
  18762. "DELETE /delete HTTP/1.1\r\n"
  18763. "Host: localhost\r\n"
  18764. "Connection: close\r\n"
  18765. "\r\n",
  18766. &resp));
  18767. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18768. }
  18769. #endif
  18770. //==============================================================================
  18771. // open_stream() Tests
  18772. //==============================================================================
  18773. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  18774. std::string result;
  18775. char buf[8192];
  18776. ssize_t n;
  18777. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18778. result.append(buf, static_cast<size_t>(n));
  18779. }
  18780. return result;
  18781. }
  18782. // Mock stream for unit tests
  18783. class MockStream : public Stream {
  18784. public:
  18785. std::string data;
  18786. size_t pos = 0;
  18787. ssize_t error_after = -1; // -1 = no error
  18788. explicit MockStream(const std::string &d, ssize_t err = -1)
  18789. : data(d), error_after(err) {}
  18790. bool is_readable() const override { return true; }
  18791. bool wait_readable() const override { return true; }
  18792. bool wait_writable() const override { return true; }
  18793. ssize_t read(char *ptr, size_t size) override {
  18794. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  18795. if (pos >= data.size()) return 0;
  18796. size_t limit =
  18797. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  18798. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  18799. std::memcpy(ptr, data.data() + pos, to_read);
  18800. pos += to_read;
  18801. return static_cast<ssize_t>(to_read);
  18802. }
  18803. ssize_t write(const char *, size_t) override { return -1; }
  18804. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  18805. ip = "127.0.0.1";
  18806. port = 0;
  18807. }
  18808. void get_local_ip_and_port(std::string &ip, int &port) const override {
  18809. ip = "127.0.0.1";
  18810. port = 0;
  18811. }
  18812. socket_t socket() const override { return INVALID_SOCKET; }
  18813. time_t duration() const override { return 0; }
  18814. };
  18815. TEST(StreamHandleTest, Basic) {
  18816. ClientImpl::StreamHandle handle;
  18817. EXPECT_FALSE(handle.is_valid());
  18818. handle.response = detail::make_unique<Response>();
  18819. handle.error = Error::Connection;
  18820. EXPECT_FALSE(handle.is_valid());
  18821. handle.error = Error::Success;
  18822. EXPECT_TRUE(handle.is_valid());
  18823. }
  18824. TEST(BodyReaderTest, Basic) {
  18825. MockStream stream("Hello, World!");
  18826. detail::BodyReader reader;
  18827. reader.stream = &stream;
  18828. reader.content_length = 13;
  18829. char buf[32];
  18830. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18831. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18832. EXPECT_TRUE(reader.eof);
  18833. }
  18834. TEST(BodyReaderTest, NoStream) {
  18835. detail::BodyReader reader;
  18836. char buf[32];
  18837. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18838. EXPECT_EQ(Error::Connection, reader.last_error);
  18839. }
  18840. TEST(BodyReaderTest, Error) {
  18841. MockStream stream("Hello, World!", 5);
  18842. detail::BodyReader reader;
  18843. reader.stream = &stream;
  18844. reader.content_length = 13;
  18845. char buf[32];
  18846. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18847. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18848. EXPECT_EQ(Error::Read, reader.last_error);
  18849. }
  18850. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18851. // Mock-based StreamHandle tests relying on private internals are removed.
  18852. class OpenStreamTest : public ::testing::Test {
  18853. protected:
  18854. void SetUp() override {
  18855. svr_.Get("/hello", [](const Request &, Response &res) {
  18856. res.set_content("Hello World!", "text/plain");
  18857. });
  18858. svr_.Get("/large", [](const Request &, Response &res) {
  18859. res.set_content(std::string(10000, 'X'), "text/plain");
  18860. });
  18861. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18862. res.set_content("Hello World!", "image/jpeg");
  18863. res.set_header("Content-Encoding", "UTF-8");
  18864. });
  18865. svr_.Get("/chunked", [](const Request &, Response &res) {
  18866. res.set_chunked_content_provider("text/plain",
  18867. [](size_t offset, DataSink &sink) {
  18868. if (offset < 15) {
  18869. sink.write("chunk", 5);
  18870. return true;
  18871. }
  18872. sink.done();
  18873. return true;
  18874. });
  18875. });
  18876. svr_.Get("/compressible", [](const Request &, Response &res) {
  18877. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18878. DataSink &sink) {
  18879. if (offset < 100 * 1024) {
  18880. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18881. sink.write(chunk.data(), chunk.size());
  18882. return true;
  18883. }
  18884. sink.done();
  18885. return true;
  18886. });
  18887. });
  18888. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18889. [](const Request & /*req*/, Response &res) {
  18890. auto i = new int(0);
  18891. res.set_header("Trailer", "Content-Length, X-Allowed");
  18892. res.set_chunked_content_provider(
  18893. "text/plain",
  18894. [i](size_t /*offset*/, DataSink &sink) {
  18895. switch (*i) {
  18896. case 0: sink.os << "123"; break;
  18897. case 1: sink.os << "456"; break;
  18898. case 2: sink.os << "789"; break;
  18899. case 3: {
  18900. sink.done_with_trailer(
  18901. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18902. } break;
  18903. }
  18904. (*i)++;
  18905. return true;
  18906. },
  18907. [i](bool success) {
  18908. EXPECT_TRUE(success);
  18909. delete i;
  18910. });
  18911. });
  18912. // Echo headers endpoint for header-related tests
  18913. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18914. std::string body;
  18915. for (const auto &h : req.headers) {
  18916. body.append(h.first);
  18917. body.push_back(':');
  18918. body.append(h.second);
  18919. body.push_back('\n');
  18920. }
  18921. res.set_content(body, "text/plain");
  18922. });
  18923. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18924. std::string body;
  18925. for (const auto &h : req.headers) {
  18926. body.append(h.first);
  18927. body.push_back(':');
  18928. body.append(h.second);
  18929. body.push_back('\n');
  18930. }
  18931. res.set_content(body, "text/plain");
  18932. });
  18933. port_ = svr_.bind_to_any_port("127.0.0.1");
  18934. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18935. svr_.wait_until_ready();
  18936. }
  18937. void TearDown() override {
  18938. svr_.stop();
  18939. if (thread_.joinable()) thread_.join();
  18940. }
  18941. Server svr_;
  18942. std::thread thread_;
  18943. int port_ = 0;
  18944. };
  18945. TEST_F(OpenStreamTest, Basic) {
  18946. Client cli("127.0.0.1", port_);
  18947. auto handle = cli.open_stream("GET", "/hello");
  18948. EXPECT_TRUE(handle.is_valid());
  18949. EXPECT_EQ("Hello World!", read_all(handle));
  18950. }
  18951. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18952. Client cli("127.0.0.1", port_);
  18953. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18954. ASSERT_TRUE(handle.is_valid());
  18955. EXPECT_EQ("Hello World!", read_all(handle));
  18956. }
  18957. TEST_F(OpenStreamTest, SmallBuffer) {
  18958. Client cli("127.0.0.1", port_);
  18959. auto handle = cli.open_stream("GET", "/hello");
  18960. std::string result;
  18961. char buf[4];
  18962. ssize_t n;
  18963. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18964. result.append(buf, static_cast<size_t>(n));
  18965. EXPECT_EQ("Hello World!", result);
  18966. }
  18967. TEST_F(OpenStreamTest, DefaultHeaders) {
  18968. Client cli("127.0.0.1", port_);
  18969. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18970. {
  18971. auto handle = cli.open_stream("GET", "/echo-headers");
  18972. ASSERT_TRUE(handle.is_valid());
  18973. auto body = read_all(handle);
  18974. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18975. std::string::npos);
  18976. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18977. std::string::npos);
  18978. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18979. }
  18980. // open_stream POST with body and no explicit content_type should NOT add
  18981. // text/plain Content-Type (behavior differs from non-streaming path), but
  18982. // should include Content-Length
  18983. {
  18984. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18985. ASSERT_TRUE(handle.is_valid());
  18986. auto body = read_all(handle);
  18987. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18988. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18989. }
  18990. // open_stream POST with explicit Content-Type should preserve it
  18991. {
  18992. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18993. {{"Content-Type", "application/custom"}},
  18994. "{}", "application/custom");
  18995. ASSERT_TRUE(handle.is_valid());
  18996. auto body = read_all(handle);
  18997. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18998. }
  18999. // User-specified User-Agent must not be overwritten for stream API
  19000. {
  19001. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19002. {{"User-Agent", "MyAgent/1.2"}});
  19003. ASSERT_TRUE(handle.is_valid());
  19004. auto body = read_all(handle);
  19005. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19006. }
  19007. }
  19008. TEST_F(OpenStreamTest, Large) {
  19009. Client cli("127.0.0.1", port_);
  19010. auto handle = cli.open_stream("GET", "/large");
  19011. EXPECT_EQ(10000u, read_all(handle).size());
  19012. }
  19013. TEST_F(OpenStreamTest, ConnectionError) {
  19014. Client cli("127.0.0.1", 9999);
  19015. auto handle = cli.open_stream("GET", "/hello");
  19016. EXPECT_FALSE(handle.is_valid());
  19017. }
  19018. TEST_F(OpenStreamTest, Chunked) {
  19019. Client cli("127.0.0.1", port_);
  19020. auto handle = cli.open_stream("GET", "/chunked");
  19021. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19022. "Transfer-Encoding") == "chunked");
  19023. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19024. }
  19025. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19026. Client cli("127.0.0.1", port_);
  19027. auto handle =
  19028. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19029. ASSERT_TRUE(handle.is_valid());
  19030. // Consume body to allow trailers to be received/parsed
  19031. auto body = read_all(handle);
  19032. // Explicitly parse trailers (ensure trailers are available for assertion)
  19033. handle.parse_trailers_if_needed();
  19034. EXPECT_EQ(std::string("123456789"), body);
  19035. // The response should include a Trailer header declaring both names
  19036. ASSERT_TRUE(handle.response);
  19037. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19038. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19039. handle.response->get_header_value("Trailer"));
  19040. // Prohibited trailer must not be present
  19041. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19042. // Allowed trailer should be present
  19043. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19044. EXPECT_EQ(std::string("yes"),
  19045. handle.response->get_trailer_value("X-Allowed"));
  19046. // Verify trailers are NOT present as regular headers
  19047. EXPECT_EQ(std::string(""),
  19048. handle.response->get_header_value("Content-Length"));
  19049. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19050. }
  19051. // Accepts one connection on an OS-assigned port, which it hands over through
  19052. // port_promise, reads the request head and sends back response. after_send,
  19053. // if given, runs on the connection before it is closed.
  19054. static std::thread
  19055. serve_single_response(std::promise<int> &port_promise,
  19056. const std::string &response,
  19057. std::function<void(socket_t)> after_send = nullptr) {
  19058. return std::thread([&port_promise, response, after_send] {
  19059. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19060. default_socket_options(srv);
  19061. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19062. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19063. sockaddr_in addr{};
  19064. addr.sin_family = AF_INET;
  19065. addr.sin_port = htons(0); // Let OS assign a free port
  19066. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19067. int opt = 1;
  19068. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19069. #ifdef _WIN32
  19070. reinterpret_cast<const char *>(&opt),
  19071. #else
  19072. &opt,
  19073. #endif
  19074. sizeof(opt));
  19075. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19076. ::listen(srv, 1) != 0) {
  19077. port_promise.set_value(-1);
  19078. detail::close_socket(srv);
  19079. return;
  19080. }
  19081. socklen_t addr_len = sizeof(addr);
  19082. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19083. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19084. sockaddr_in cli_addr{};
  19085. socklen_t cli_len = sizeof(cli_addr);
  19086. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19087. if (cli != INVALID_SOCKET) {
  19088. // Read the complete HTTP request (until the blank line that terminates
  19089. // headers) before sending the response. If the server closes the socket
  19090. // while the client's request data is still unread in the kernel receive
  19091. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19092. // connection on both sides: it discards the client's receive buffer
  19093. // (which already holds our response) and causes any in-progress write on
  19094. // the client to fail with ECONNRESET. Reading all request data first
  19095. // ensures close() emits a graceful FIN.
  19096. {
  19097. char rbuf[256];
  19098. std::string req;
  19099. while (req.find("\r\n\r\n") == std::string::npos) {
  19100. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19101. if (n <= 0) { break; }
  19102. req.append(rbuf, static_cast<size_t>(n));
  19103. }
  19104. }
  19105. ::send(cli,
  19106. #ifdef _WIN32
  19107. static_cast<const char *>(response.c_str()),
  19108. static_cast<int>(response.size()),
  19109. #else
  19110. response.c_str(), response.size(),
  19111. #endif
  19112. 0);
  19113. if (after_send) { after_send(cli); }
  19114. detail::close_socket(cli);
  19115. }
  19116. detail::close_socket(srv);
  19117. });
  19118. }
  19119. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19120. #ifndef _WIN32
  19121. signal(SIGPIPE, SIG_IGN);
  19122. #endif
  19123. std::promise<int> port_promise;
  19124. auto port_future = port_promise.get_future();
  19125. auto server_thread =
  19126. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19127. "Content-Type: text/plain\r\n"
  19128. "Content-Length: not-a-number\r\n"
  19129. "Connection: close\r\n"
  19130. "\r\n"
  19131. "hello");
  19132. auto port = port_future.get();
  19133. ASSERT_GT(port, 0);
  19134. Client cli("127.0.0.1", port);
  19135. auto handle = cli.open_stream("GET", "/");
  19136. EXPECT_FALSE(handle.is_valid());
  19137. server_thread.join();
  19138. }
  19139. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19140. #ifndef _WIN32
  19141. signal(SIGPIPE, SIG_IGN);
  19142. #endif
  19143. std::promise<int> port_promise;
  19144. auto port_future = port_promise.get_future();
  19145. auto server_thread = serve_single_response(
  19146. port_promise, "HTTP/1.1 200 OK\r\n"
  19147. "Content-Type: text/plain\r\n"
  19148. "Content-Length: 99999999999999999999999999\r\n"
  19149. "Connection: close\r\n"
  19150. "\r\n"
  19151. "hello");
  19152. auto port = port_future.get();
  19153. ASSERT_GT(port, 0);
  19154. // Historically std::stoull would throw std::out_of_range here and crash
  19155. // the process, then parsing silently clamped to a bogus framing length and
  19156. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19157. // so the stream fails to open, matching the not-a-number case above. The
  19158. // process still must NOT terminate.
  19159. Client cli("127.0.0.1", port);
  19160. auto handle = cli.open_stream("GET", "/");
  19161. EXPECT_FALSE(handle.is_valid());
  19162. server_thread.join();
  19163. }
  19164. // Serves `response` to the single request `fn` makes with a fresh client.
  19165. template <typename Fn>
  19166. static void with_single_response(const std::string &response, Fn fn) {
  19167. #ifndef _WIN32
  19168. signal(SIGPIPE, SIG_IGN);
  19169. #endif
  19170. std::promise<int> port_promise;
  19171. auto port_future = port_promise.get_future();
  19172. auto server_thread = serve_single_response(port_promise, response);
  19173. auto se = detail::scope_exit([&] { server_thread.join(); });
  19174. auto port = port_future.get();
  19175. ASSERT_GT(port, 0);
  19176. Client cli("127.0.0.1", port);
  19177. fn(cli);
  19178. }
  19179. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19180. const char *responses[] = {
  19181. "HTTP/1.1 103 Early Hints\r\n"
  19182. "Link: </style.css>; rel=preload\r\n"
  19183. "\r\n"
  19184. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19185. "HTTP/1.1 100 Continue\r\n"
  19186. "X-Note: interim\r\n"
  19187. "\r\n"
  19188. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19189. };
  19190. for (auto response : responses) {
  19191. with_single_response(response, [](Client &cli) {
  19192. auto res = cli.Get("/");
  19193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19194. EXPECT_EQ(StatusCode::OK_200, res->status);
  19195. EXPECT_EQ("ok", res->body);
  19196. });
  19197. }
  19198. }
  19199. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19200. #ifndef _WIN32
  19201. signal(SIGPIPE, SIG_IGN);
  19202. #endif
  19203. // The server answers the head without asking for the body. Bytes it then
  19204. // reads on the connection would be taken for the body the request declared.
  19205. auto closed_by_client = false;
  19206. std::promise<int> port_promise;
  19207. auto server_thread = serve_single_response(
  19208. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  19209. [&](socket_t sock) {
  19210. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19211. char buf[256];
  19212. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  19213. });
  19214. Client cli("127.0.0.1", port_promise.get_future().get());
  19215. cli.set_keep_alive(true);
  19216. cli.set_read_timeout(1, 0);
  19217. // Long enough for the client to send Expect: 100-continue.
  19218. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19220. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19221. cli.Get("/second");
  19222. server_thread.join();
  19223. EXPECT_TRUE(closed_by_client);
  19224. }
  19225. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  19226. // Long enough for the client to send Expect: 100-continue
  19227. with_single_response(
  19228. "HTTP/1.1 103 Early Hints\r\n"
  19229. "Link: </style.css>; rel=preload\r\n"
  19230. "\r\n"
  19231. "HTTP/1.1 401 Unauthorized\r\n"
  19232. "Content-Length: 0\r\n\r\n",
  19233. [](Client &cli) {
  19234. cli.set_read_timeout(2, 0);
  19235. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19237. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19238. });
  19239. }
  19240. #ifdef CPPHTTPLIB_SSL_ENABLED
  19241. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  19242. #ifndef _WIN32
  19243. signal(SIGPIPE, SIG_IGN);
  19244. #endif
  19245. auto reused = false;
  19246. std::promise<int> port_promise;
  19247. auto server_thread = serve_single_response(
  19248. port_promise,
  19249. "HTTP/1.1 401 Unauthorized\r\n"
  19250. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  19251. "Content-Length: 0\r\n\r\n",
  19252. [&](socket_t sock) {
  19253. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19254. char buf[256];
  19255. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  19256. });
  19257. Client cli("127.0.0.1", port_promise.get_future().get());
  19258. cli.set_keep_alive(true);
  19259. cli.set_digest_auth("user", "pass");
  19260. cli.set_read_timeout(1, 0);
  19261. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19262. server_thread.join();
  19263. EXPECT_FALSE(reused);
  19264. }
  19265. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  19266. // Any other answer to CONNECT would read as the origin's response.
  19267. struct {
  19268. const char *response;
  19269. bool passed_on;
  19270. } cases[] = {
  19271. {"HTTP/1.1 201 Created\r\n"
  19272. "Set-Cookie: session=from-proxy\r\n"
  19273. "Content-Length: 0\r\n\r\n",
  19274. false},
  19275. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  19276. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  19277. "Content-Length: 0\r\n\r\n",
  19278. true},
  19279. };
  19280. for (const auto &c : cases) {
  19281. std::promise<int> port_promise;
  19282. auto server_thread = serve_single_response(port_promise, c.response);
  19283. SSLClient cli("example.com", 443);
  19284. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  19285. auto res = cli.Get("/");
  19286. server_thread.join();
  19287. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  19288. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  19289. if (res) {
  19290. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19291. }
  19292. }
  19293. }
  19294. #endif
  19295. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  19296. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  19297. // the chunked coding and drop Content-Length, so a front-end that trusts
  19298. // Content-Length would disagree about where the body ends (response
  19299. // smuggling). The client must reject such a response.
  19300. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19301. for (const char *te : {"chunked", "gzip, chunked"}) {
  19302. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  19303. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  19304. "\r\n" + "Connection: close\r\n" + "\r\n" +
  19305. "5\r\nhello\r\n0\r\n\r\n";
  19306. with_single_response(response, [&](Client &cli) {
  19307. auto res = cli.Get("/");
  19308. EXPECT_FALSE(static_cast<bool>(res)) << te;
  19309. EXPECT_EQ(Error::Read, res.error()) << te;
  19310. });
  19311. with_single_response(response, [&](Client &cli) {
  19312. auto handle = cli.open_stream("GET", "/");
  19313. EXPECT_FALSE(handle.is_valid()) << te;
  19314. EXPECT_EQ(Error::Read, handle.error) << te;
  19315. });
  19316. }
  19317. }
  19318. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  19319. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  19320. // closing the connection (unlike a request, which must be rejected).
  19321. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  19322. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19323. "Transfer-Encoding: chunked\r\n"
  19324. "Connection: close\r\n"
  19325. "\r\n"
  19326. "5\r\nhello\r\n0\r\n\r\n",
  19327. "HTTP/1.1 200 OK\r\n"
  19328. "Transfer-Encoding: gzip\r\n"
  19329. "Connection: close\r\n"
  19330. "\r\n"
  19331. "hello"}) {
  19332. with_single_response(response, [&](Client &cli) {
  19333. auto res = cli.Get("/");
  19334. ASSERT_TRUE(static_cast<bool>(res)) << response;
  19335. EXPECT_EQ("hello", res->body);
  19336. });
  19337. with_single_response(response, [&](Client &cli) {
  19338. auto handle = cli.open_stream("GET", "/");
  19339. ASSERT_TRUE(handle.is_valid()) << response;
  19340. EXPECT_EQ("hello", read_all(handle));
  19341. });
  19342. }
  19343. }
  19344. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  19345. // framing headers describe nothing to read and must not be rejected.
  19346. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  19347. const std::string framing = "Content-Length: 5\r\n"
  19348. "Transfer-Encoding: chunked\r\n"
  19349. "Connection: close\r\n"
  19350. "\r\n";
  19351. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19352. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  19353. });
  19354. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19355. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  19356. });
  19357. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  19358. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  19359. with_single_response(response, [&](Client &cli) {
  19360. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  19361. });
  19362. with_single_response(response, [&](Client &cli) {
  19363. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  19364. });
  19365. }
  19366. }
  19367. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  19368. // response, is faulty framing, so the connection is not reused after it.
  19369. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  19370. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19371. "Content-Length: 0\r\n"
  19372. "Transfer-Encoding: chunked\r\n"
  19373. "\r\n"
  19374. "5\r\nhello\r\n0\r\n\r\n",
  19375. "HTTP/1.0 200 Connection established\r\n"
  19376. "Connection: keep-alive\r\n"
  19377. "Transfer-Encoding: chunked\r\n"
  19378. "\r\n"
  19379. "5\r\nhello\r\n0\r\n\r\n"}) {
  19380. with_single_response(response, [&](Client &cli) {
  19381. cli.set_keep_alive(true);
  19382. auto res = cli.Get("/");
  19383. ASSERT_TRUE(res) << response;
  19384. EXPECT_EQ("hello", res->body);
  19385. EXPECT_FALSE(cli.is_socket_open()) << response;
  19386. });
  19387. }
  19388. }
  19389. // A payload max length of 0 means no limit, however the body is framed.
  19390. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  19391. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19392. "Transfer-Encoding: chunked\r\n"
  19393. "\r\n"
  19394. "5\r\nhello\r\n0\r\n\r\n",
  19395. "HTTP/1.1 200 OK\r\n"
  19396. "Connection: close\r\n"
  19397. "\r\n"
  19398. "hello"}) {
  19399. with_single_response(response, [&](Client &cli) {
  19400. cli.set_payload_max_length(0);
  19401. auto res = cli.Get("/");
  19402. ASSERT_TRUE(res) << response;
  19403. EXPECT_EQ("hello", res->body) << response;
  19404. });
  19405. }
  19406. }
  19407. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  19408. Server svr;
  19409. svr.set_payload_max_length(0);
  19410. svr.Post("/echo", [](const Request &req, Response &res) {
  19411. res.set_content(req.body, "text/plain");
  19412. });
  19413. auto port = svr.bind_to_any_port(HOST);
  19414. thread t = thread([&] { svr.listen_after_bind(); });
  19415. auto se = detail::scope_exit([&] {
  19416. svr.stop();
  19417. t.join();
  19418. ASSERT_FALSE(svr.is_running());
  19419. });
  19420. svr.wait_until_ready();
  19421. Client cli(HOST, port);
  19422. auto res = cli.Post(
  19423. "/echo",
  19424. [](size_t /*offset*/, DataSink &sink) {
  19425. sink.write("hello", 5);
  19426. sink.done();
  19427. return true;
  19428. },
  19429. "text/plain");
  19430. ASSERT_TRUE(res);
  19431. EXPECT_EQ(StatusCode::OK_200, res->status);
  19432. EXPECT_EQ("hello", res->body);
  19433. }
  19434. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19435. TEST_F(OpenStreamTest, Gzip) {
  19436. Client cli("127.0.0.1", port_);
  19437. auto handle = cli.open_stream("GET", "/compressible", {},
  19438. {{"Accept-Encoding", "gzip"}});
  19439. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  19440. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19441. }
  19442. #endif
  19443. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19444. TEST_F(OpenStreamTest, Brotli) {
  19445. Client cli("127.0.0.1", port_);
  19446. auto handle =
  19447. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  19448. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  19449. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19450. }
  19451. #endif
  19452. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19453. TEST_F(OpenStreamTest, Zstd) {
  19454. Client cli("127.0.0.1", port_);
  19455. auto handle = cli.open_stream("GET", "/compressible", {},
  19456. {{"Accept-Encoding", "zstd"}});
  19457. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  19458. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19459. }
  19460. #endif
  19461. #ifdef CPPHTTPLIB_SSL_ENABLED
  19462. class SSLOpenStreamTest : public ::testing::Test {
  19463. protected:
  19464. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  19465. void SetUp() override {
  19466. svr_.Get("/hello", [](const Request &, Response &res) {
  19467. res.set_content("Hello SSL World!", "text/plain");
  19468. });
  19469. svr_.Get("/chunked", [](const Request &, Response &res) {
  19470. res.set_chunked_content_provider("text/plain",
  19471. [](size_t offset, DataSink &sink) {
  19472. if (offset < 15) {
  19473. sink.write("chunk", 5);
  19474. return true;
  19475. }
  19476. sink.done();
  19477. return true;
  19478. });
  19479. });
  19480. svr_.Post("/echo", [](const Request &req, Response &res) {
  19481. res.set_content(req.body, req.get_header_value("Content-Type"));
  19482. });
  19483. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  19484. std::string body = req.body;
  19485. res.set_chunked_content_provider(
  19486. "text/plain", [body](size_t offset, DataSink &sink) {
  19487. if (offset < body.size()) {
  19488. sink.write(body.data() + offset, body.size() - offset);
  19489. }
  19490. sink.done();
  19491. return true;
  19492. });
  19493. });
  19494. port_ = svr_.bind_to_any_port("127.0.0.1");
  19495. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19496. svr_.wait_until_ready();
  19497. }
  19498. void TearDown() override {
  19499. svr_.stop();
  19500. if (thread_.joinable()) thread_.join();
  19501. }
  19502. SSLServer svr_;
  19503. std::thread thread_;
  19504. int port_ = 0;
  19505. };
  19506. TEST_F(SSLOpenStreamTest, Basic) {
  19507. SSLClient cli("127.0.0.1", port_);
  19508. cli.enable_server_certificate_verification(false);
  19509. auto handle = cli.open_stream("GET", "/hello");
  19510. ASSERT_TRUE(handle.is_valid());
  19511. EXPECT_EQ("Hello SSL World!", read_all(handle));
  19512. }
  19513. TEST_F(SSLOpenStreamTest, Chunked) {
  19514. SSLClient cli("127.0.0.1", port_);
  19515. cli.enable_server_certificate_verification(false);
  19516. auto handle = cli.open_stream("GET", "/chunked");
  19517. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19518. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19519. "Transfer-Encoding") == "chunked");
  19520. auto body = read_all(handle);
  19521. EXPECT_EQ("chunkchunkchunk", body);
  19522. }
  19523. TEST_F(SSLOpenStreamTest, Post) {
  19524. SSLClient cli("127.0.0.1", port_);
  19525. cli.enable_server_certificate_verification(false);
  19526. auto handle =
  19527. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  19528. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19529. EXPECT_EQ(200, handle.response->status);
  19530. auto body = read_all(handle);
  19531. EXPECT_EQ("Hello SSL POST", body);
  19532. }
  19533. TEST_F(SSLOpenStreamTest, PostChunked) {
  19534. SSLClient cli("127.0.0.1", port_);
  19535. cli.enable_server_certificate_verification(false);
  19536. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  19537. "Chunked SSL Data", "text/plain");
  19538. ASSERT_TRUE(handle.is_valid());
  19539. EXPECT_EQ(200, handle.response->status);
  19540. auto body = read_all(handle);
  19541. EXPECT_EQ("Chunked SSL Data", body);
  19542. }
  19543. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  19544. // Content-Length is terminated by the server closing the connection. When the
  19545. // SSL peer sends a close_notify after the body, the client must treat it as a
  19546. // clean EOF and return a successful response rather than an error.
  19547. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  19548. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19549. ASSERT_TRUE(svr.is_valid());
  19550. svr.set_keep_alive_max_count(1);
  19551. const std::string expected_body = "Hello from connection-close response!";
  19552. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  19553. res.set_content_provider("text/plain",
  19554. [&](size_t offset, DataSink &sink) -> bool {
  19555. if (offset < expected_body.size()) {
  19556. sink.write(expected_body.data() + offset,
  19557. expected_body.size() - offset);
  19558. }
  19559. sink.done();
  19560. return true;
  19561. });
  19562. });
  19563. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  19564. auto se = detail::scope_exit([&] {
  19565. svr.stop();
  19566. listen_thread.join();
  19567. ASSERT_FALSE(svr.is_running());
  19568. });
  19569. svr.wait_until_ready();
  19570. SSLClient cli(HOST, PORT);
  19571. cli.enable_server_certificate_verification(false);
  19572. auto res = cli.Get("/no-content-length");
  19573. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  19574. EXPECT_EQ(StatusCode::OK_200, res->status);
  19575. EXPECT_EQ(expected_body, res->body);
  19576. }
  19577. #endif // CPPHTTPLIB_SSL_ENABLED
  19578. //==============================================================================
  19579. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  19580. // results for various scenarios.
  19581. //==============================================================================
  19582. TEST(ParityTest, GetVsOpenStream) {
  19583. Server svr;
  19584. const std::string path = "/parity";
  19585. const std::string content = "Parity test content: hello world";
  19586. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19587. res.set_content(content, "text/plain");
  19588. });
  19589. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19590. auto se = detail::scope_exit([&] {
  19591. svr.stop();
  19592. t.join();
  19593. ASSERT_FALSE(svr.is_running());
  19594. });
  19595. svr.wait_until_ready();
  19596. Client cli(HOST, PORT);
  19597. // Non-stream path
  19598. auto r1 = cli.Get(path);
  19599. ASSERT_TRUE(r1);
  19600. EXPECT_EQ(StatusCode::OK_200, r1->status);
  19601. // Stream path
  19602. auto h = cli.open_stream("GET", path);
  19603. ASSERT_TRUE(h.is_valid());
  19604. EXPECT_EQ(r1->body, read_all(h));
  19605. }
  19606. // Helper to compress data with provided compressor type T
  19607. template <typename Compressor>
  19608. static std::string compress_payload_for_parity(const std::string &in) {
  19609. std::string out;
  19610. Compressor compressor;
  19611. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  19612. [&](const char *data, size_t n) {
  19613. out.append(data, n);
  19614. return true;
  19615. });
  19616. EXPECT_TRUE(ok);
  19617. return out;
  19618. }
  19619. // Helper function for compression parity tests
  19620. template <typename Compressor>
  19621. static void test_compression_parity(const std::string &original,
  19622. const std::string &path,
  19623. const std::string &encoding) {
  19624. const std::string compressed =
  19625. compress_payload_for_parity<Compressor>(original);
  19626. Server svr;
  19627. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19628. res.set_content(compressed, "application/octet-stream");
  19629. res.set_header("Content-Encoding", encoding);
  19630. });
  19631. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  19632. auto se = detail::scope_exit([&] {
  19633. svr.stop();
  19634. t.join();
  19635. ASSERT_FALSE(svr.is_running());
  19636. });
  19637. svr.wait_until_ready();
  19638. Client cli(HOST, PORT);
  19639. // Non-streaming
  19640. {
  19641. auto res = cli.Get(path);
  19642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19643. EXPECT_EQ(StatusCode::OK_200, res->status);
  19644. EXPECT_EQ(original, res->body);
  19645. }
  19646. // Streaming
  19647. {
  19648. auto h = cli.open_stream("GET", path);
  19649. ASSERT_TRUE(h.is_valid());
  19650. EXPECT_EQ(original, read_all(h));
  19651. }
  19652. }
  19653. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19654. TEST(ParityTest, Gzip) {
  19655. test_compression_parity<detail::gzip_compressor>(
  19656. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  19657. }
  19658. #endif
  19659. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19660. TEST(ParityTest, Brotli) {
  19661. test_compression_parity<detail::brotli_compressor>(
  19662. "Hello, brotli parity test payload", "/parity-br", "br");
  19663. }
  19664. #endif
  19665. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19666. TEST(ParityTest, Zstd) {
  19667. test_compression_parity<detail::zstd_compressor>(
  19668. "Zstandard parity test payload", "/parity-zstd", "zstd");
  19669. }
  19670. #endif
  19671. //==============================================================================
  19672. // New Stream API Tests
  19673. //==============================================================================
  19674. inline std::string read_body(httplib::stream::Result &result) {
  19675. std::string body;
  19676. while (result.next()) {
  19677. body.append(result.data(), result.size());
  19678. }
  19679. return body;
  19680. }
  19681. TEST(ClientConnectionTest, Basic) {
  19682. httplib::ClientConnection conn;
  19683. EXPECT_FALSE(conn.is_open());
  19684. conn.sock = 1;
  19685. EXPECT_TRUE(conn.is_open());
  19686. httplib::ClientConnection conn2(std::move(conn));
  19687. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  19688. conn2.sock = INVALID_SOCKET;
  19689. }
  19690. // Unified test server for all stream::* tests
  19691. class StreamApiTest : public ::testing::Test {
  19692. protected:
  19693. void SetUp() override {
  19694. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19695. res.set_content("Hello World!", "text/plain");
  19696. });
  19697. svr_.Get("/echo-params",
  19698. [](const httplib::Request &req, httplib::Response &res) {
  19699. std::string r;
  19700. for (const auto &p : req.params) {
  19701. if (!r.empty()) r += "&";
  19702. r += p.first + "=" + p.second;
  19703. }
  19704. res.set_content(r, "text/plain");
  19705. });
  19706. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19707. res.set_content(req.body, req.get_header_value("Content-Type"));
  19708. });
  19709. svr_.Post("/echo-headers",
  19710. [](const httplib::Request &req, httplib::Response &res) {
  19711. std::string r;
  19712. for (const auto &h : req.headers)
  19713. r += h.first + ": " + h.second + "\n";
  19714. res.set_content(r, "text/plain");
  19715. });
  19716. svr_.Post("/echo-params",
  19717. [](const httplib::Request &req, httplib::Response &res) {
  19718. std::string r = "params:";
  19719. for (const auto &p : req.params)
  19720. r += p.first + "=" + p.second + ";";
  19721. res.set_content(r + " body:" + req.body, "text/plain");
  19722. });
  19723. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  19724. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  19725. });
  19726. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19727. res.set_content("PUT:" + req.body, "text/plain");
  19728. });
  19729. svr_.Patch("/echo",
  19730. [](const httplib::Request &req, httplib::Response &res) {
  19731. res.set_content("PATCH:" + req.body, "text/plain");
  19732. });
  19733. svr_.Delete(
  19734. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  19735. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  19736. "text/plain");
  19737. });
  19738. svr_.Get("/head-test",
  19739. [](const httplib::Request &, httplib::Response &res) {
  19740. res.set_content("body for HEAD", "text/plain");
  19741. });
  19742. svr_.Options("/options",
  19743. [](const httplib::Request &, httplib::Response &res) {
  19744. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  19745. });
  19746. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  19747. svr_.wait_until_ready();
  19748. }
  19749. void TearDown() override {
  19750. svr_.stop();
  19751. if (thread_.joinable()) thread_.join();
  19752. }
  19753. httplib::Server svr_;
  19754. std::thread thread_;
  19755. };
  19756. // stream::Get tests
  19757. TEST_F(StreamApiTest, GetBasic) {
  19758. httplib::Client cli(HOST, PORT);
  19759. auto result = httplib::stream::Get(cli, "/hello");
  19760. ASSERT_TRUE(result.is_valid());
  19761. EXPECT_EQ(200, result.status());
  19762. EXPECT_EQ("Hello World!", read_body(result));
  19763. }
  19764. TEST_F(StreamApiTest, GetWithParams) {
  19765. httplib::Client cli(HOST, PORT);
  19766. httplib::Params params{{"foo", "bar"}};
  19767. auto result = httplib::stream::Get(cli, "/echo-params", params);
  19768. ASSERT_TRUE(result.is_valid());
  19769. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  19770. }
  19771. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19772. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  19773. httplib::Client cli(HOST, PORT);
  19774. cli.set_payload_max_length(0);
  19775. auto result = httplib::stream::Get(cli, "/hello");
  19776. ASSERT_TRUE(result.is_valid());
  19777. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  19778. EXPECT_EQ("Hello World!", read_body(result));
  19779. }
  19780. #endif
  19781. TEST_F(StreamApiTest, GetConnectionError) {
  19782. httplib::Client cli(HOST, 9999);
  19783. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  19784. }
  19785. TEST_F(StreamApiTest, Get404) {
  19786. httplib::Client cli(HOST, PORT);
  19787. auto result = httplib::stream::Get(cli, "/nonexistent");
  19788. EXPECT_TRUE(result.is_valid());
  19789. EXPECT_EQ(404, result.status());
  19790. }
  19791. // stream::Post tests
  19792. TEST_F(StreamApiTest, PostBasic) {
  19793. httplib::Client cli(HOST, PORT);
  19794. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  19795. "application/json");
  19796. ASSERT_TRUE(result.is_valid());
  19797. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  19798. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  19799. }
  19800. TEST_F(StreamApiTest, PostWithHeaders) {
  19801. httplib::Client cli(HOST, PORT);
  19802. httplib::Headers headers{{"X-Custom", "value"}};
  19803. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  19804. "text/plain");
  19805. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  19806. }
  19807. TEST_F(StreamApiTest, PostWithParams) {
  19808. httplib::Client cli(HOST, PORT);
  19809. httplib::Params params{{"k", "v"}};
  19810. auto result =
  19811. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  19812. auto body = read_body(result);
  19813. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  19814. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  19815. }
  19816. TEST_F(StreamApiTest, PostLarge) {
  19817. httplib::Client cli(HOST, PORT);
  19818. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  19819. size_t total = 0;
  19820. while (result.next()) {
  19821. total += result.size();
  19822. }
  19823. EXPECT_EQ(100u * 1024u, total);
  19824. }
  19825. // stream::Put/Patch tests
  19826. TEST_F(StreamApiTest, PutAndPatch) {
  19827. httplib::Client cli(HOST, PORT);
  19828. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  19829. EXPECT_EQ("PUT:test", read_body(put));
  19830. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  19831. EXPECT_EQ("PATCH:test", read_body(patch));
  19832. }
  19833. // stream::Delete tests
  19834. TEST_F(StreamApiTest, Delete) {
  19835. httplib::Client cli(HOST, PORT);
  19836. auto del1 = httplib::stream::Delete(cli, "/resource");
  19837. EXPECT_EQ("Deleted", read_body(del1));
  19838. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  19839. EXPECT_EQ("Deleted:data", read_body(del2));
  19840. }
  19841. // stream::Head/Options tests
  19842. TEST_F(StreamApiTest, HeadAndOptions) {
  19843. httplib::Client cli(HOST, PORT);
  19844. auto head = httplib::stream::Head(cli, "/head-test");
  19845. EXPECT_TRUE(head.is_valid());
  19846. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  19847. auto opts = httplib::stream::Options(cli, "/options");
  19848. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  19849. }
  19850. // SSL stream::* tests
  19851. #ifdef CPPHTTPLIB_SSL_ENABLED
  19852. class SSLStreamApiTest : public ::testing::Test {
  19853. protected:
  19854. void SetUp() override {
  19855. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19856. res.set_content("Hello SSL!", "text/plain");
  19857. });
  19858. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19859. res.set_content(req.body, "text/plain");
  19860. });
  19861. port_ = svr_.bind_to_any_port("127.0.0.1");
  19862. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19863. svr_.wait_until_ready();
  19864. }
  19865. void TearDown() override {
  19866. svr_.stop();
  19867. if (thread_.joinable()) thread_.join();
  19868. }
  19869. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  19870. std::thread thread_;
  19871. int port_ = 0;
  19872. };
  19873. TEST_F(SSLStreamApiTest, GetAndPost) {
  19874. httplib::SSLClient cli("127.0.0.1", port_);
  19875. cli.enable_server_certificate_verification(false);
  19876. auto get = httplib::stream::Get(cli, "/hello");
  19877. EXPECT_EQ("Hello SSL!", read_body(get));
  19878. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  19879. EXPECT_EQ("test", read_body(post));
  19880. }
  19881. #endif
  19882. // Tests for Error::Timeout and Error::ConnectionClosed error types
  19883. // These errors are set in SocketStream/SSLSocketStream and propagated through
  19884. // BodyReader
  19885. TEST(ErrorHandlingTest, StreamReadTimeout) {
  19886. // Test that read timeout during streaming is detected
  19887. // Use a large content-length response where server delays mid-stream
  19888. Server svr;
  19889. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19890. // Send a large response with delay in the middle
  19891. res.set_content_provider(
  19892. 1000, // content_length
  19893. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  19894. if (offset < 100) {
  19895. // Send first 100 bytes immediately
  19896. std::string data(100, 'A');
  19897. sink.write(data.c_str(), data.size());
  19898. return true;
  19899. }
  19900. // Then delay longer than client timeout
  19901. std::this_thread::sleep_for(std::chrono::seconds(3));
  19902. std::string data(900, 'B');
  19903. sink.write(data.c_str(), data.size());
  19904. return true;
  19905. });
  19906. });
  19907. auto port = 8091;
  19908. std::thread t([&]() { svr.listen("localhost", port); });
  19909. svr.wait_until_ready();
  19910. Client cli("localhost", port);
  19911. cli.set_read_timeout(1, 0); // 1 second timeout
  19912. auto handle = cli.open_stream("GET", "/slow-stream");
  19913. ASSERT_TRUE(handle.is_valid());
  19914. char buf[256];
  19915. ssize_t total = 0;
  19916. ssize_t n;
  19917. bool got_error = false;
  19918. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19919. total += n;
  19920. }
  19921. if (n < 0) {
  19922. got_error = true;
  19923. // Should be timeout or read error
  19924. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19925. handle.get_read_error() == Error::Read)
  19926. << "Actual error: " << to_string(handle.get_read_error());
  19927. }
  19928. // Either we got an error, or we got less data than expected
  19929. EXPECT_TRUE(got_error || total < 1000)
  19930. << "Expected timeout but got all " << total << " bytes";
  19931. svr.stop();
  19932. t.join();
  19933. }
  19934. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  19935. // Test connection closed detection via BodyReader
  19936. Server svr;
  19937. std::atomic<bool> close_now{false};
  19938. svr.Get("/will-close", [&](const Request &, Response &res) {
  19939. res.set_content_provider(
  19940. 10000, // Large content_length that we won't fully send
  19941. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19942. if (offset < 100) {
  19943. std::string data(100, 'X');
  19944. sink.write(data.c_str(), data.size());
  19945. return true;
  19946. }
  19947. // Wait for signal then abort
  19948. while (!close_now) {
  19949. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19950. }
  19951. return false; // Abort - server will close connection
  19952. });
  19953. });
  19954. auto port = 8092;
  19955. std::thread t([&]() { svr.listen("localhost", port); });
  19956. svr.wait_until_ready();
  19957. Client cli("localhost", port);
  19958. auto handle = cli.open_stream("GET", "/will-close");
  19959. ASSERT_TRUE(handle.is_valid());
  19960. char buf[256];
  19961. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19962. EXPECT_GT(n, 0) << "First read should succeed";
  19963. // Signal server to close
  19964. close_now = true;
  19965. // Keep reading until error or EOF
  19966. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19967. // Keep reading
  19968. }
  19969. // Should get an error since content_length wasn't satisfied
  19970. if (n < 0) {
  19971. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19972. handle.get_read_error() == Error::Read)
  19973. << "Actual error: " << to_string(handle.get_read_error());
  19974. }
  19975. svr.stop();
  19976. t.join();
  19977. }
  19978. #ifdef CPPHTTPLIB_SSL_ENABLED
  19979. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  19980. // Test that read timeout during SSL streaming is detected
  19981. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19982. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19983. res.set_content_provider(
  19984. 1000, "text/plain",
  19985. [](size_t offset, size_t /*length*/, DataSink &sink) {
  19986. if (offset < 100) {
  19987. std::string data(100, 'A');
  19988. sink.write(data.c_str(), data.size());
  19989. return true;
  19990. }
  19991. std::this_thread::sleep_for(std::chrono::seconds(3));
  19992. std::string data(900, 'B');
  19993. sink.write(data.c_str(), data.size());
  19994. return true;
  19995. });
  19996. });
  19997. auto port = 8093;
  19998. std::thread t([&]() { svr.listen("localhost", port); });
  19999. svr.wait_until_ready();
  20000. SSLClient cli("localhost", port);
  20001. cli.enable_server_certificate_verification(false);
  20002. cli.set_read_timeout(1, 0); // 1 second timeout
  20003. auto handle = cli.open_stream("GET", "/slow-stream");
  20004. ASSERT_TRUE(handle.is_valid());
  20005. char buf[256];
  20006. ssize_t total = 0;
  20007. ssize_t n;
  20008. bool got_error = false;
  20009. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20010. total += n;
  20011. }
  20012. if (n < 0) {
  20013. got_error = true;
  20014. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20015. handle.get_read_error() == Error::Read)
  20016. << "Actual error: " << to_string(handle.get_read_error());
  20017. }
  20018. EXPECT_TRUE(got_error || total < 1000)
  20019. << "Expected timeout but got all " << total << " bytes";
  20020. svr.stop();
  20021. t.join();
  20022. }
  20023. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  20024. // Test SSL connection closed detection
  20025. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20026. std::atomic<bool> close_now{false};
  20027. svr.Get("/will-close", [&](const Request &, Response &res) {
  20028. res.set_content_provider(
  20029. 10000, "text/plain",
  20030. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20031. if (offset < 100) {
  20032. std::string data(100, 'X');
  20033. sink.write(data.c_str(), data.size());
  20034. return true;
  20035. }
  20036. while (!close_now) {
  20037. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20038. }
  20039. return false;
  20040. });
  20041. });
  20042. auto port = 8094;
  20043. std::thread t([&]() { svr.listen("localhost", port); });
  20044. svr.wait_until_ready();
  20045. SSLClient cli("localhost", port);
  20046. cli.enable_server_certificate_verification(false);
  20047. auto handle = cli.open_stream("GET", "/will-close");
  20048. ASSERT_TRUE(handle.is_valid());
  20049. char buf[256];
  20050. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20051. EXPECT_GT(n, 0);
  20052. // Signal server to close
  20053. close_now = true;
  20054. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20055. // Keep reading
  20056. }
  20057. if (n < 0) {
  20058. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20059. handle.get_read_error() == Error::Read)
  20060. << "Actual error: " << to_string(handle.get_read_error());
  20061. }
  20062. svr.stop();
  20063. t.join();
  20064. }
  20065. #endif
  20066. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  20067. using namespace httplib;
  20068. // Create a test file
  20069. const char *fname = "etag_testfile.txt";
  20070. const char *content = "etag-content";
  20071. {
  20072. std::ofstream ofs(fname);
  20073. ofs << content;
  20074. ASSERT_TRUE(ofs.good());
  20075. }
  20076. Server svr;
  20077. svr.set_mount_point("/static", ".");
  20078. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20079. svr.wait_until_ready();
  20080. Client cli(HOST, PORT);
  20081. // First request: should get 200 with ETag header
  20082. auto res1 = cli.Get("/static/etag_testfile.txt");
  20083. ASSERT_TRUE(res1);
  20084. ASSERT_EQ(200, res1->status);
  20085. ASSERT_TRUE(res1->has_header("ETag"));
  20086. std::string etag = res1->get_header_value("ETag");
  20087. EXPECT_FALSE(etag.empty());
  20088. // Verify ETag format: W/"hex-hex"
  20089. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  20090. EXPECT_EQ('W', etag[0]);
  20091. EXPECT_EQ('/', etag[1]);
  20092. EXPECT_EQ('"', etag[2]);
  20093. EXPECT_EQ('"', etag.back());
  20094. // Exact match: expect 304 Not Modified
  20095. Headers h2 = {{"If-None-Match", etag}};
  20096. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  20097. ASSERT_TRUE(res2);
  20098. EXPECT_EQ(304, res2->status);
  20099. // Wildcard match: expect 304 Not Modified
  20100. Headers h3 = {{"If-None-Match", "*"}};
  20101. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  20102. ASSERT_TRUE(res3);
  20103. EXPECT_EQ(304, res3->status);
  20104. // Non-matching ETag: expect 200
  20105. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  20106. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  20107. ASSERT_TRUE(res4);
  20108. EXPECT_EQ(200, res4->status);
  20109. // Multiple ETags with one matching: expect 304
  20110. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  20111. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  20112. ASSERT_TRUE(res5);
  20113. EXPECT_EQ(304, res5->status);
  20114. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  20115. // that equivalent to the single comma-separated list above, so the match on
  20116. // the second line must still be found.
  20117. Headers h6;
  20118. h6.emplace("If-None-Match", "W/\"other\"");
  20119. h6.emplace("If-None-Match", etag);
  20120. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  20121. ASSERT_TRUE(res6);
  20122. EXPECT_EQ(304, res6->status);
  20123. svr.stop();
  20124. t.join();
  20125. std::remove(fname);
  20126. }
  20127. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  20128. using namespace httplib;
  20129. Server svr;
  20130. svr.set_mount_point("/static", ".");
  20131. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20132. svr.wait_until_ready();
  20133. Client cli(HOST, PORT);
  20134. // Send If-None-Match: * to a non-existent file
  20135. Headers h = {{"If-None-Match", "*"}};
  20136. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  20137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20138. EXPECT_EQ(404, res->status);
  20139. svr.stop();
  20140. t.join();
  20141. }
  20142. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  20143. using namespace httplib;
  20144. // Create a test file
  20145. const char *fname = "etag_boundary_testfile.txt";
  20146. const char *content = "boundary-test";
  20147. {
  20148. std::ofstream ofs(fname);
  20149. ofs << content;
  20150. ASSERT_TRUE(ofs.good());
  20151. }
  20152. Server svr;
  20153. svr.set_mount_point("/static", ".");
  20154. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20155. svr.wait_until_ready();
  20156. Client cli(HOST, PORT);
  20157. // Get the actual ETag
  20158. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  20159. ASSERT_TRUE(res1);
  20160. ASSERT_EQ(200, res1->status);
  20161. ASSERT_TRUE(res1->has_header("ETag"));
  20162. std::string etag = res1->get_header_value("ETag");
  20163. // Test 1: Very long ETag value (longer than actual ETag)
  20164. // Should NOT match and return 200 (not trigger out-of-bounds read)
  20165. Headers h1 = {{"If-None-Match", "W/"
  20166. "\"very-long-etag-value-that-is-much-longer-"
  20167. "than-the-actual-etag-value\""}};
  20168. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  20169. ASSERT_TRUE(res2);
  20170. EXPECT_EQ(200, res2->status); // Should not match
  20171. // Test 2: Long string followed by wildcard
  20172. // Should match on "*" and return 304 (without out-of-bounds read on the long
  20173. // string)
  20174. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  20175. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  20176. ASSERT_TRUE(res3);
  20177. EXPECT_EQ(304, res3->status); // Should match on "*"
  20178. // Test 3: Wildcard followed by long string
  20179. // Should match on "*" immediately and return 304
  20180. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  20181. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  20182. ASSERT_TRUE(res4);
  20183. EXPECT_EQ(304, res4->status); // Should match on "*"
  20184. // Test 4: Multiple long non-matching values
  20185. // Should NOT match and return 200 (test that all comparisons are safe)
  20186. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  20187. "W/\"second-long-non-matching-value\", "
  20188. "W/\"third-long-non-matching-value\""}};
  20189. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  20190. ASSERT_TRUE(res5);
  20191. EXPECT_EQ(200, res5->status); // Should not match
  20192. // Test 5: Single character that is not "*" (edge case)
  20193. Headers h5 = {{"If-None-Match", "X"}};
  20194. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  20195. ASSERT_TRUE(res6);
  20196. EXPECT_EQ(200, res6->status); // Should not match
  20197. svr.stop();
  20198. t.join();
  20199. std::remove(fname);
  20200. }
  20201. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  20202. using namespace httplib;
  20203. // Create a test file
  20204. const char *fname = "ims_testfile.txt";
  20205. const char *content = "if-modified-since-test";
  20206. {
  20207. std::ofstream ofs(fname);
  20208. ofs << content;
  20209. ASSERT_TRUE(ofs.good());
  20210. }
  20211. Server svr;
  20212. svr.set_mount_point("/static", ".");
  20213. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20214. svr.wait_until_ready();
  20215. Client cli(HOST, PORT);
  20216. // First request: should get 200 with Last-Modified header
  20217. auto res1 = cli.Get("/static/ims_testfile.txt");
  20218. ASSERT_TRUE(res1);
  20219. ASSERT_EQ(200, res1->status);
  20220. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20221. std::string last_modified = res1->get_header_value("Last-Modified");
  20222. EXPECT_FALSE(last_modified.empty());
  20223. // If-Modified-Since with same time: expect 304
  20224. Headers h2 = {{"If-Modified-Since", last_modified}};
  20225. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  20226. ASSERT_TRUE(res2);
  20227. EXPECT_EQ(304, res2->status);
  20228. // If-Modified-Since with future time: expect 304
  20229. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20230. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  20231. ASSERT_TRUE(res3);
  20232. EXPECT_EQ(304, res3->status);
  20233. // If-Modified-Since with past time: expect 200
  20234. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20235. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  20236. ASSERT_TRUE(res4);
  20237. EXPECT_EQ(200, res4->status);
  20238. // If-None-Match takes precedence over If-Modified-Since
  20239. // (send matching ETag with old If-Modified-Since -> should still be 304)
  20240. ASSERT_TRUE(res1->has_header("ETag"));
  20241. std::string etag = res1->get_header_value("ETag");
  20242. Headers h5 = {{"If-None-Match", etag},
  20243. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20244. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  20245. ASSERT_TRUE(res5);
  20246. EXPECT_EQ(304, res5->status);
  20247. svr.stop();
  20248. t.join();
  20249. std::remove(fname);
  20250. }
  20251. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  20252. using namespace httplib;
  20253. Server svr;
  20254. // Endpoint that returns compressible content
  20255. svr.Get("/compressible", [](const Request &, Response &res) {
  20256. // Return a large enough body to trigger compression
  20257. std::string body(1000, 'a');
  20258. res.set_content(body, "text/plain");
  20259. });
  20260. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20261. svr.wait_until_ready();
  20262. Client cli(HOST, PORT);
  20263. // Request with gzip support: should get Vary header when compressed
  20264. cli.set_compress(true);
  20265. auto res1 = cli.Get("/compressible");
  20266. ASSERT_TRUE(res1);
  20267. EXPECT_EQ(200, res1->status);
  20268. // If Content-Encoding is set, Vary should also be set
  20269. if (res1->has_header("Content-Encoding")) {
  20270. EXPECT_TRUE(res1->has_header("Vary"));
  20271. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  20272. }
  20273. // Request without Accept-Encoding header: should not have compression
  20274. Headers h_no_compress;
  20275. auto res2 = cli.Get("/compressible", h_no_compress);
  20276. ASSERT_TRUE(res2);
  20277. EXPECT_EQ(200, res2->status);
  20278. // Verify Vary header is present when compression is applied
  20279. // (the exact behavior depends on server configuration)
  20280. svr.stop();
  20281. t.join();
  20282. }
  20283. TEST(ETagTest, IfRangeWithETag) {
  20284. using namespace httplib;
  20285. // Create a test file with known content
  20286. const char *fname = "if_range_testfile.txt";
  20287. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  20288. {
  20289. std::ofstream ofs(fname);
  20290. ofs << content;
  20291. ASSERT_TRUE(ofs.good());
  20292. }
  20293. Server svr;
  20294. svr.set_mount_point("/static", ".");
  20295. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20296. svr.wait_until_ready();
  20297. Client cli(HOST, PORT);
  20298. // First request: get ETag
  20299. auto res1 = cli.Get("/static/if_range_testfile.txt");
  20300. ASSERT_TRUE(res1);
  20301. ASSERT_EQ(200, res1->status);
  20302. ASSERT_TRUE(res1->has_header("ETag"));
  20303. std::string etag = res1->get_header_value("ETag");
  20304. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  20305. // Since our server generates weak ETags (W/"..."), If-Range with our
  20306. // ETag should NOT result in partial content - it should return full content.
  20307. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  20308. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  20309. ASSERT_TRUE(res2);
  20310. // Weak ETag in If-Range -> full content (200), not partial (206)
  20311. EXPECT_EQ(200, res2->status);
  20312. EXPECT_EQ(content, res2->body);
  20313. EXPECT_FALSE(res2->has_header("Content-Range"));
  20314. // Range request with non-matching If-Range (ETag): should get 200 (full
  20315. // content)
  20316. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  20317. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  20318. ASSERT_TRUE(res3);
  20319. EXPECT_EQ(200, res3->status);
  20320. EXPECT_EQ(content, res3->body);
  20321. EXPECT_FALSE(res3->has_header("Content-Range"));
  20322. // Range request with strong ETag (hypothetical - our server doesn't generate
  20323. // strong ETags, but if client sends a strong ETag that doesn't match, it
  20324. // should return full content)
  20325. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  20326. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  20327. ASSERT_TRUE(res4);
  20328. EXPECT_EQ(200, res4->status);
  20329. EXPECT_EQ(content, res4->body);
  20330. EXPECT_FALSE(res4->has_header("Content-Range"));
  20331. svr.stop();
  20332. t.join();
  20333. std::remove(fname);
  20334. }
  20335. TEST(ETagTest, IfRangeWithDate) {
  20336. using namespace httplib;
  20337. // Create a test file
  20338. const char *fname = "if_range_date_testfile.txt";
  20339. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  20340. {
  20341. std::ofstream ofs(fname);
  20342. ofs << content;
  20343. ASSERT_TRUE(ofs.good());
  20344. }
  20345. Server svr;
  20346. svr.set_mount_point("/static", ".");
  20347. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20348. svr.wait_until_ready();
  20349. Client cli(HOST, PORT);
  20350. // First request: get Last-Modified
  20351. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  20352. ASSERT_TRUE(res1);
  20353. ASSERT_EQ(200, res1->status);
  20354. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20355. std::string last_modified = res1->get_header_value("Last-Modified");
  20356. // Range request with matching If-Range (date): should get 206
  20357. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  20358. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  20359. ASSERT_TRUE(res2);
  20360. EXPECT_EQ(206, res2->status);
  20361. EXPECT_EQ("FGHIJ", res2->body);
  20362. // Range request with old If-Range date: should get 200 (full content)
  20363. Headers h3 = {{"Range", "bytes=5-9"},
  20364. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20365. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  20366. ASSERT_TRUE(res3);
  20367. EXPECT_EQ(200, res3->status);
  20368. EXPECT_EQ(content, res3->body);
  20369. // Range request with future If-Range date: should get 206
  20370. Headers h4 = {{"Range", "bytes=0-4"},
  20371. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20372. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  20373. ASSERT_TRUE(res4);
  20374. EXPECT_EQ(206, res4->status);
  20375. EXPECT_EQ("ABCDE", res4->body);
  20376. svr.stop();
  20377. t.join();
  20378. std::remove(fname);
  20379. }
  20380. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  20381. using namespace httplib;
  20382. const char *fname = "etag_malformed.txt";
  20383. const char *content = "malformed-etag";
  20384. {
  20385. std::ofstream ofs(fname);
  20386. ofs << content;
  20387. ASSERT_TRUE(ofs.good());
  20388. }
  20389. Server svr;
  20390. svr.set_mount_point("/static", ".");
  20391. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20392. svr.wait_until_ready();
  20393. Client cli(HOST, PORT);
  20394. // baseline: should get 200 and an ETag
  20395. auto res1 = cli.Get("/static/etag_malformed.txt");
  20396. ASSERT_TRUE(res1);
  20397. ASSERT_EQ(200, res1->status);
  20398. ASSERT_TRUE(res1->has_header("ETag"));
  20399. // Malformed ETag value (missing quotes) should be treated as non-matching
  20400. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  20401. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  20402. ASSERT_TRUE(res_bad);
  20403. EXPECT_EQ(200, res_bad->status);
  20404. // Whitespace-only header value should be considered invalid / non-matching
  20405. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  20406. "Host: localhost\r\n"
  20407. "If-None-Match: \r\n"
  20408. "Connection: close\r\n"
  20409. "\r\n";
  20410. std::string out;
  20411. ASSERT_TRUE(send_request(5, raw_req, &out));
  20412. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20413. svr.stop();
  20414. t.join();
  20415. std::remove(fname);
  20416. }
  20417. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  20418. using namespace httplib;
  20419. const char *fname = "ims_invalid_format.txt";
  20420. const char *content = "ims-bad-format";
  20421. {
  20422. std::ofstream ofs(fname);
  20423. ofs << content;
  20424. ASSERT_TRUE(ofs.good());
  20425. }
  20426. Server svr;
  20427. svr.set_mount_point("/static", ".");
  20428. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20429. svr.wait_until_ready();
  20430. Client cli(HOST, PORT);
  20431. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  20432. ASSERT_TRUE(res1);
  20433. ASSERT_EQ(200, res1->status);
  20434. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20435. // If-Modified-Since with invalid format should not result in 304
  20436. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  20437. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  20438. ASSERT_TRUE(res_bad);
  20439. EXPECT_EQ(200, res_bad->status);
  20440. // If-Range with invalid date format should be treated as mismatch -> full
  20441. // content (200)
  20442. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  20443. {"If-Range", "invalid-date"}};
  20444. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  20445. ASSERT_TRUE(res_ifrange);
  20446. EXPECT_EQ(200, res_ifrange->status);
  20447. svr.stop();
  20448. t.join();
  20449. std::remove(fname);
  20450. }
  20451. TEST(ETagTest, IfRangeWithMalformedETag) {
  20452. using namespace httplib;
  20453. const char *fname = "ifrange_malformed.txt";
  20454. const std::string content = "0123456789";
  20455. {
  20456. std::ofstream ofs(fname);
  20457. ofs << content;
  20458. ASSERT_TRUE(ofs.good());
  20459. }
  20460. Server svr;
  20461. svr.set_mount_point("/static", ".");
  20462. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20463. svr.wait_until_ready();
  20464. Client cli(HOST, PORT);
  20465. // First request: get ETag
  20466. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  20467. ASSERT_TRUE(res1);
  20468. ASSERT_EQ(200, res1->status);
  20469. ASSERT_TRUE(res1->has_header("ETag"));
  20470. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  20471. // full content (200)
  20472. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  20473. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  20474. ASSERT_TRUE(res2);
  20475. EXPECT_EQ(200, res2->status);
  20476. EXPECT_EQ(content, res2->body);
  20477. svr.stop();
  20478. t.join();
  20479. std::remove(fname);
  20480. }
  20481. TEST(ETagTest, ExtremeLargeDateValues) {
  20482. using namespace httplib;
  20483. const char *fname = "ims_extreme_date.txt";
  20484. const char *content = "ims-extreme-date";
  20485. {
  20486. std::ofstream ofs(fname);
  20487. ofs << content;
  20488. ASSERT_TRUE(ofs.good());
  20489. }
  20490. Server svr;
  20491. svr.set_mount_point("/static", ".");
  20492. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20493. svr.wait_until_ready();
  20494. Client cli(HOST, PORT);
  20495. auto res1 = cli.Get(std::string("/static/") + fname);
  20496. ASSERT_TRUE(res1);
  20497. ASSERT_EQ(200, res1->status);
  20498. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20499. // Extremely large year that may overflow date parsing routines.
  20500. Headers h_large_date = {
  20501. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20502. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  20503. ASSERT_TRUE(res_bad);
  20504. // Expect server to treat this as invalid/mismatch and return full content
  20505. EXPECT_EQ(200, res_bad->status);
  20506. // If-Range with extremely large date should be treated as mismatch -> full
  20507. // content (200)
  20508. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  20509. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20510. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  20511. ASSERT_TRUE(res_ifrange);
  20512. EXPECT_EQ(200, res_ifrange->status);
  20513. svr.stop();
  20514. t.join();
  20515. std::remove(fname);
  20516. }
  20517. TEST(ETagTest, NegativeFileModificationTime) {
  20518. using namespace httplib;
  20519. const char *fname = "ims_negative_mtime.txt";
  20520. const std::string content = "negative-mtime";
  20521. {
  20522. std::ofstream ofs(fname);
  20523. ofs << content;
  20524. ASSERT_TRUE(ofs.good());
  20525. }
  20526. // Try to set file mtime to a negative value. This may fail on some
  20527. // platforms/filesystems; if it fails, the test will still verify server
  20528. // behaves safely by performing a regular conditional request.
  20529. #if defined(__APPLE__) || defined(__linux__)
  20530. bool set_negative = false;
  20531. do {
  20532. struct timeval times[2];
  20533. // access time: now
  20534. times[0].tv_sec = time(nullptr);
  20535. times[0].tv_usec = 0;
  20536. // modification time: negative (e.g., -1)
  20537. times[1].tv_sec = -1;
  20538. times[1].tv_usec = 0;
  20539. if (utimes(fname, times) == 0) { set_negative = true; }
  20540. } while (0);
  20541. #else
  20542. bool set_negative = false;
  20543. #endif
  20544. Server svr;
  20545. svr.set_mount_point("/static", ".");
  20546. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20547. svr.wait_until_ready();
  20548. Client cli(HOST, PORT);
  20549. auto res1 = cli.Get(std::string("/static/") + fname);
  20550. ASSERT_TRUE(res1);
  20551. ASSERT_EQ(200, res1->status);
  20552. bool has_last_modified = res1->has_header("Last-Modified");
  20553. std::string last_modified;
  20554. if (has_last_modified) {
  20555. last_modified = res1->get_header_value("Last-Modified");
  20556. }
  20557. if (set_negative) {
  20558. // If we successfully set a negative mtime, ensure server returns a
  20559. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  20560. // with an old date and ensure server handles it without crash.
  20561. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  20562. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  20563. ASSERT_TRUE(res2);
  20564. // Behavior may vary; at minimum ensure server responds (200 or 304).
  20565. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  20566. } else {
  20567. // Could not set negative mtime on this platform; fall back to verifying
  20568. // that normal invalid/malformed dates are treated safely (non-304).
  20569. Headers h_bad_date = {
  20570. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20571. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  20572. ASSERT_TRUE(res_bad);
  20573. EXPECT_EQ(200, res_bad->status);
  20574. }
  20575. svr.stop();
  20576. t.join();
  20577. std::remove(fname);
  20578. }
  20579. //==============================================================================
  20580. // Integration Tests with Server
  20581. //==============================================================================
  20582. class SSEIntegrationTest : public ::testing::Test {
  20583. protected:
  20584. void SetUp() override {
  20585. stop_server_.store(false);
  20586. events_.clear();
  20587. server_ = httplib::detail::make_unique<Server>();
  20588. setup_server();
  20589. start_server();
  20590. }
  20591. void TearDown() override {
  20592. stop_server_.store(true);
  20593. event_cv_.notify_all();
  20594. server_->stop();
  20595. if (server_thread_.joinable()) { server_thread_.join(); }
  20596. }
  20597. void setup_server() {
  20598. // Simple SSE endpoint
  20599. server_->Get("/events", [this](const Request &req, Response &res) {
  20600. auto last_id = req.get_header_value("Last-Event-ID");
  20601. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  20602. res.set_chunked_content_provider(
  20603. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  20604. std::unique_lock<std::mutex> lock(event_mutex_);
  20605. if (event_cv_.wait_for(
  20606. lock, std::chrono::milliseconds(200), [this] {
  20607. return !events_.empty() || stop_server_.load();
  20608. })) {
  20609. if (stop_server_.load()) { return false; }
  20610. if (!events_.empty()) {
  20611. std::string event = events_.front();
  20612. events_.erase(events_.begin());
  20613. sink.write(event.data(), event.size());
  20614. return true;
  20615. }
  20616. }
  20617. return !stop_server_.load();
  20618. });
  20619. });
  20620. // Endpoint that returns error
  20621. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  20622. res.status = 500;
  20623. res.set_content("Internal Server Error", "text/plain");
  20624. });
  20625. // Endpoint for custom event types
  20626. server_->Get("/custom-events", [](const Request &, Response &res) {
  20627. res.set_chunked_content_provider(
  20628. "text/event-stream", [](size_t offset, DataSink &sink) {
  20629. if (offset == 0) {
  20630. std::string event = "event: update\ndata: updated\n\n"
  20631. "event: delete\ndata: deleted\n\n";
  20632. sink.write(event.data(), event.size());
  20633. }
  20634. return false; // End stream after sending
  20635. });
  20636. });
  20637. }
  20638. void start_server() {
  20639. port_ = server_->bind_to_any_port(HOST);
  20640. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20641. // Wait for server to start
  20642. while (!server_->is_running()) {
  20643. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20644. }
  20645. }
  20646. int get_port() const { return port_; }
  20647. void send_event(const std::string &event) {
  20648. std::lock_guard<std::mutex> lock(event_mutex_);
  20649. events_.push_back(event);
  20650. event_cv_.notify_all();
  20651. }
  20652. std::unique_ptr<Server> server_;
  20653. std::thread server_thread_;
  20654. std::mutex event_mutex_;
  20655. std::condition_variable event_cv_;
  20656. std::vector<std::string> events_;
  20657. std::atomic<bool> stop_server_{false};
  20658. std::string last_received_event_id_;
  20659. int port_ = 0;
  20660. };
  20661. //==============================================================================
  20662. // SSE Parsing Tests
  20663. //==============================================================================
  20664. class SSEParsingTest : public SSEIntegrationTest {
  20665. protected:
  20666. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  20667. // A trailing sentinel event tells when the whole stream has been parsed.
  20668. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  20669. auto body = stream + "event: end\ndata: end\n\n";
  20670. server_->Get("/parse", [body](const Request &, Response &res) {
  20671. res.set_content(body, "text/event-stream");
  20672. });
  20673. return collect("/parse");
  20674. }
  20675. // Runs SSEClient against path until an "end" event arrives and returns the
  20676. // messages dispatched before it
  20677. std::vector<sse::SSEMessage> collect(const std::string &path) {
  20678. Client client(HOST, get_port());
  20679. sse::SSEClient sse(client, path);
  20680. std::mutex mutex;
  20681. std::condition_variable cv;
  20682. std::vector<sse::SSEMessage> messages;
  20683. auto done = false;
  20684. sse.on_message([&](const sse::SSEMessage &msg) {
  20685. std::lock_guard<std::mutex> lock(mutex);
  20686. // Ignore a replay from a reconnect that races with stop()
  20687. if (!done) { messages.push_back(msg); }
  20688. });
  20689. sse.on_event("end", [&](const sse::SSEMessage &) {
  20690. std::lock_guard<std::mutex> lock(mutex);
  20691. done = true;
  20692. cv.notify_all();
  20693. });
  20694. sse.set_reconnect_interval(100);
  20695. sse.start_async();
  20696. {
  20697. std::unique_lock<std::mutex> lock(mutex);
  20698. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  20699. }
  20700. sse.stop();
  20701. EXPECT_TRUE(done);
  20702. return messages;
  20703. }
  20704. };
  20705. TEST_F(SSEParsingTest, SingleLineData) {
  20706. auto msgs = parse("data: hello\n\n");
  20707. ASSERT_EQ(msgs.size(), 1u);
  20708. EXPECT_EQ(msgs[0].data, "hello");
  20709. EXPECT_EQ(msgs[0].event, "message");
  20710. }
  20711. TEST_F(SSEParsingTest, MultiLineData) {
  20712. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  20713. ASSERT_EQ(msgs.size(), 1u);
  20714. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  20715. }
  20716. TEST_F(SSEParsingTest, CustomEventType) {
  20717. auto msgs = parse("event: update\ndata: payload\n\n");
  20718. ASSERT_EQ(msgs.size(), 1u);
  20719. EXPECT_EQ(msgs[0].event, "update");
  20720. EXPECT_EQ(msgs[0].data, "payload");
  20721. }
  20722. TEST_F(SSEParsingTest, EventIdHandling) {
  20723. auto msgs = parse("id: 12345\ndata: test\n\n");
  20724. ASSERT_EQ(msgs.size(), 1u);
  20725. EXPECT_EQ(msgs[0].id, "12345");
  20726. }
  20727. TEST_F(SSEParsingTest, EmptyEventId) {
  20728. auto msgs = parse("id:\ndata: test\n\n");
  20729. ASSERT_EQ(msgs.size(), 1u);
  20730. EXPECT_EQ(msgs[0].id, "");
  20731. }
  20732. TEST_F(SSEParsingTest, CommentsIgnored) {
  20733. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  20734. ASSERT_EQ(msgs.size(), 1u);
  20735. EXPECT_EQ(msgs[0].data, "hello");
  20736. EXPECT_EQ(msgs[0].event, "message");
  20737. }
  20738. TEST_F(SSEParsingTest, ColonInValue) {
  20739. auto msgs = parse("data: hello:world:test\n\n");
  20740. ASSERT_EQ(msgs.size(), 1u);
  20741. EXPECT_EQ(msgs[0].data, "hello:world:test");
  20742. }
  20743. TEST_F(SSEParsingTest, FieldNameOnly) {
  20744. // A line without a colon is a field name with an empty value
  20745. auto msgs = parse("data\n\n");
  20746. ASSERT_EQ(msgs.size(), 1u);
  20747. EXPECT_EQ(msgs[0].data, "");
  20748. }
  20749. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  20750. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  20751. ASSERT_EQ(msgs.size(), 1u);
  20752. EXPECT_EQ(msgs[0].event, "update");
  20753. EXPECT_EQ(msgs[0].data, "hello");
  20754. }
  20755. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  20756. auto msgs = parse("data\r\n\r\n");
  20757. ASSERT_EQ(msgs.size(), 1u);
  20758. EXPECT_EQ(msgs[0].data, "");
  20759. }
  20760. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  20761. auto msgs = parse("event: update\rdata: hello\r\r");
  20762. ASSERT_EQ(msgs.size(), 1u);
  20763. EXPECT_EQ(msgs[0].event, "update");
  20764. EXPECT_EQ(msgs[0].data, "hello");
  20765. }
  20766. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  20767. // Chunk boundaries fall inside every \r\n and right before the first one
  20768. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  20769. "\n\r", "\nevent: end\ndata: end\n\n"};
  20770. server_->Get("/split", [chunks](const Request &, Response &res) {
  20771. auto i = std::make_shared<size_t>(0);
  20772. res.set_chunked_content_provider(
  20773. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  20774. if (*i == chunks.size()) {
  20775. sink.done();
  20776. } else {
  20777. sink.write(chunks[*i].data(), chunks[*i].size());
  20778. (*i)++;
  20779. }
  20780. return true;
  20781. });
  20782. });
  20783. auto msgs = collect("/split");
  20784. ASSERT_EQ(msgs.size(), 1u);
  20785. EXPECT_EQ(msgs[0].event, "update");
  20786. EXPECT_EQ(msgs[0].data, "hello");
  20787. }
  20788. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  20789. // Only a BOM at the start of the stream is ignored
  20790. auto msgs = parse("\xEF\xBB\xBF"
  20791. "data: first\n\n"
  20792. "\xEF\xBB\xBF"
  20793. "data: second\n\n");
  20794. ASSERT_EQ(msgs.size(), 1u);
  20795. EXPECT_EQ(msgs[0].data, "first");
  20796. }
  20797. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  20798. auto msgs = parse("unknown: value\ndata: hello\n\n");
  20799. ASSERT_EQ(msgs.size(), 1u);
  20800. EXPECT_EQ(msgs[0].data, "hello");
  20801. EXPECT_EQ(msgs[0].event, "message");
  20802. }
  20803. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  20804. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  20805. ASSERT_EQ(msgs.size(), 2u);
  20806. EXPECT_EQ(msgs[0].data, "hello");
  20807. EXPECT_EQ(msgs[1].data, "hello");
  20808. }
  20809. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  20810. // An event without data is not dispatched, and its type must not leak
  20811. // into the next event
  20812. auto msgs = parse("event: update\n\ndata: hello\n\n");
  20813. ASSERT_EQ(msgs.size(), 1u);
  20814. EXPECT_EQ(msgs[0].event, "message");
  20815. EXPECT_EQ(msgs[0].data, "hello");
  20816. }
  20817. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  20818. // The first connection sends only an id; the second echoes back the
  20819. // Last-Event-ID it was reconnected with
  20820. std::atomic<int> connection_count{0};
  20821. server_->Get("/id-only", [&](const Request &req, Response &res) {
  20822. if (connection_count++ == 0) {
  20823. res.set_content("id: 42\n\n", "text/event-stream");
  20824. } else {
  20825. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20826. "\n\nevent: end\ndata: end\n\n",
  20827. "text/event-stream");
  20828. }
  20829. });
  20830. auto msgs = collect("/id-only");
  20831. ASSERT_EQ(msgs.size(), 1u);
  20832. EXPECT_EQ(msgs[0].data, "42");
  20833. }
  20834. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  20835. // The first connection sets an id and then clears it with an empty one; the
  20836. // second reports whether it was reconnected with a Last-Event-ID
  20837. std::atomic<int> connection_count{0};
  20838. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  20839. if (connection_count++ == 0) {
  20840. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  20841. "text/event-stream");
  20842. } else {
  20843. res.set_content(
  20844. std::string("data: ") +
  20845. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  20846. "\n\nevent: end\ndata: end\n\n",
  20847. "text/event-stream");
  20848. }
  20849. });
  20850. auto msgs = collect("/id-clear");
  20851. ASSERT_EQ(msgs.size(), 3u);
  20852. EXPECT_EQ(msgs[0].id, "1");
  20853. EXPECT_EQ(msgs[1].id, "");
  20854. EXPECT_EQ(msgs[2].data, "not sent");
  20855. }
  20856. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  20857. // The first connection sets an id and then sends ids that cannot be carried
  20858. // in a header; the second echoes back the Last-Event-ID it was reconnected
  20859. // with
  20860. std::atomic<int> connection_count{0};
  20861. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  20862. if (connection_count++ == 0) {
  20863. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  20864. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  20865. "text/event-stream");
  20866. } else {
  20867. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20868. "\n\nevent: end\ndata: end\n\n",
  20869. "text/event-stream");
  20870. }
  20871. });
  20872. auto msgs = collect("/id-unsendable");
  20873. ASSERT_EQ(msgs.size(), 1u);
  20874. EXPECT_EQ(msgs[0].data, "42");
  20875. }
  20876. TEST_F(SSEParsingTest, CompleteEventParsing) {
  20877. auto msgs = parse("event: notification\nid: evt-42\n"
  20878. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  20879. ASSERT_EQ(msgs.size(), 1u);
  20880. EXPECT_EQ(msgs[0].event, "notification");
  20881. EXPECT_EQ(msgs[0].id, "evt-42");
  20882. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  20883. }
  20884. TEST(SSEMessageTest, Clear) {
  20885. sse::SSEMessage msg;
  20886. msg.event = "custom";
  20887. msg.data = "some data";
  20888. msg.id = "123";
  20889. msg.clear();
  20890. EXPECT_EQ(msg.event, "message");
  20891. EXPECT_EQ(msg.data, "");
  20892. EXPECT_EQ(msg.id, "");
  20893. }
  20894. //==============================================================================
  20895. // SSE Integration Tests
  20896. //==============================================================================
  20897. // Test: Successful connection and on_open callback
  20898. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  20899. // Add a simple endpoint that sends one event and closes
  20900. server_->Get("/simple-event", [](const Request &, Response &res) {
  20901. res.set_chunked_content_provider(
  20902. "text/event-stream", [](size_t offset, DataSink &sink) {
  20903. if (offset == 0) {
  20904. std::string event = "data: hello\n\n";
  20905. sink.write(event.data(), event.size());
  20906. }
  20907. return false; // Close stream after sending
  20908. });
  20909. });
  20910. Client client("localhost", get_port());
  20911. sse::SSEClient sse(client, "/simple-event");
  20912. std::atomic<bool> open_called{false};
  20913. std::atomic<bool> message_received{false};
  20914. sse.on_open([&open_called]() { open_called.store(true); });
  20915. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  20916. if (msg.data == "hello") { message_received.store(true); }
  20917. });
  20918. sse.set_reconnect_interval(100);
  20919. sse.set_max_reconnect_attempts(1);
  20920. // Start async
  20921. sse.start_async();
  20922. // Wait for message to be processed
  20923. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20924. sse.stop();
  20925. EXPECT_TRUE(open_called.load());
  20926. EXPECT_TRUE(message_received.load());
  20927. }
  20928. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  20929. // A data line that never ends.
  20930. server_->Get("/endless-line", [](const Request &, Response &res) {
  20931. res.set_chunked_content_provider(
  20932. "text/event-stream", [](size_t offset, DataSink &sink) {
  20933. if (offset == 0) { sink.write("data: ", 6); }
  20934. std::string chunk(64 * 1024, 'A');
  20935. return sink.write(chunk.data(), chunk.size());
  20936. });
  20937. });
  20938. Client client("localhost", get_port());
  20939. sse::SSEClient sse(client, "/endless-line");
  20940. std::atomic<bool> too_long{false};
  20941. sse.on_error([&](Error err) {
  20942. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  20943. });
  20944. sse.set_max_reconnect_attempts(1);
  20945. sse.start_async();
  20946. for (int i = 0; i < 500 && !too_long; i++) {
  20947. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20948. }
  20949. sse.stop();
  20950. EXPECT_TRUE(too_long);
  20951. }
  20952. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  20953. // Far more in all than the client's payload limit below.
  20954. server_->Get("/many-events", [](const Request &, Response &res) {
  20955. res.set_chunked_content_provider(
  20956. "text/event-stream", [](size_t offset, DataSink &sink) {
  20957. if (offset == 0) {
  20958. std::string events;
  20959. for (int i = 0; i < 1000; i++) {
  20960. events += "data: message\n\n";
  20961. }
  20962. sink.write(events.data(), events.size());
  20963. }
  20964. return false;
  20965. });
  20966. });
  20967. Client client("localhost", get_port());
  20968. client.set_payload_max_length(1024);
  20969. sse::SSEClient sse(client, "/many-events");
  20970. std::atomic<int> messages{0};
  20971. std::atomic<bool> too_large{false};
  20972. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  20973. sse.on_error([&](Error err) {
  20974. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  20975. });
  20976. sse.set_max_reconnect_attempts(1);
  20977. sse.start_async();
  20978. for (int i = 0; i < 500 && messages < 1000; i++) {
  20979. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20980. }
  20981. sse.stop();
  20982. EXPECT_GE(messages.load(), 1000);
  20983. EXPECT_FALSE(too_large);
  20984. }
  20985. // Test: on_message callback
  20986. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  20987. // Endpoint that sends multiple events then closes
  20988. server_->Get("/multi-event", [](const Request &, Response &res) {
  20989. res.set_chunked_content_provider(
  20990. "text/event-stream", [](size_t offset, DataSink &sink) {
  20991. if (offset == 0) {
  20992. std::string events = "data: message1\n\ndata: message2\n\n";
  20993. sink.write(events.data(), events.size());
  20994. }
  20995. return false;
  20996. });
  20997. });
  20998. Client client("localhost", get_port());
  20999. sse::SSEClient sse(client, "/multi-event");
  21000. std::vector<std::string> received_messages;
  21001. std::mutex messages_mutex;
  21002. sse.on_message([&](const sse::SSEMessage &msg) {
  21003. std::lock_guard<std::mutex> lock(messages_mutex);
  21004. received_messages.push_back(msg.data);
  21005. });
  21006. sse.set_reconnect_interval(100);
  21007. sse.set_max_reconnect_attempts(1);
  21008. sse.start_async();
  21009. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21010. sse.stop();
  21011. std::lock_guard<std::mutex> lock(messages_mutex);
  21012. EXPECT_GE(received_messages.size(), 2u);
  21013. if (received_messages.size() >= 2) {
  21014. EXPECT_EQ(received_messages[0], "message1");
  21015. EXPECT_EQ(received_messages[1], "message2");
  21016. }
  21017. }
  21018. // Test: on_event for specific types
  21019. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  21020. Client client("localhost", get_port());
  21021. sse::SSEClient sse(client, "/custom-events");
  21022. std::atomic<bool> update_received{false};
  21023. std::atomic<bool> delete_received{false};
  21024. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  21025. if (msg.data == "updated") { update_received.store(true); }
  21026. });
  21027. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  21028. if (msg.data == "deleted") { delete_received.store(true); }
  21029. });
  21030. sse.set_max_reconnect_attempts(1);
  21031. sse.start_async();
  21032. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  21033. sse.stop();
  21034. EXPECT_TRUE(update_received.load());
  21035. EXPECT_TRUE(delete_received.load());
  21036. }
  21037. // Test: on_error callback on connection failure
  21038. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  21039. // Connect to a non-existent port
  21040. Client client("localhost", 59999);
  21041. sse::SSEClient sse(client, "/events");
  21042. std::atomic<bool> error_called{false};
  21043. Error received_error = Error::Success;
  21044. sse.on_error([&](Error err) {
  21045. error_called.store(true);
  21046. received_error = err;
  21047. });
  21048. sse.set_reconnect_interval(50);
  21049. sse.set_max_reconnect_attempts(1);
  21050. sse.start_async();
  21051. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21052. sse.stop();
  21053. EXPECT_TRUE(error_called.load());
  21054. EXPECT_NE(received_error, Error::Success);
  21055. }
  21056. // Test: Last-Event-ID header sent on reconnect
  21057. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  21058. // Endpoint that sends event with ID
  21059. server_->Get("/event-with-id", [](const Request &, Response &res) {
  21060. res.set_chunked_content_provider(
  21061. "text/event-stream", [](size_t offset, DataSink &sink) {
  21062. if (offset == 0) {
  21063. std::string event = "id: evt-123\ndata: test\n\n";
  21064. sink.write(event.data(), event.size());
  21065. }
  21066. return false;
  21067. });
  21068. });
  21069. Client client("localhost", get_port());
  21070. sse::SSEClient sse(client, "/event-with-id");
  21071. std::atomic<bool> id_received{false};
  21072. sse.on_message([&](const sse::SSEMessage &msg) {
  21073. if (!msg.id.empty()) { id_received.store(true); }
  21074. });
  21075. sse.set_reconnect_interval(100);
  21076. sse.set_max_reconnect_attempts(1);
  21077. sse.start_async();
  21078. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21079. sse.stop();
  21080. EXPECT_TRUE(id_received.load());
  21081. EXPECT_EQ(sse.last_event_id(), "evt-123");
  21082. }
  21083. // Test: Manual stop
  21084. TEST_F(SSEIntegrationTest, ManualStop) {
  21085. // Endpoint that sends one event and stays open briefly
  21086. std::atomic<bool> handler_running{true};
  21087. server_->Get("/stay-open", [&handler_running](const Request &,
  21088. Response &res) {
  21089. res.set_chunked_content_provider(
  21090. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  21091. if (offset == 0) {
  21092. std::string event = "data: connected\n\n";
  21093. sink.write(event.data(), event.size());
  21094. }
  21095. // Keep connection open while handler_running is true
  21096. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  21097. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21098. }
  21099. return false;
  21100. });
  21101. });
  21102. Client client("localhost", get_port());
  21103. sse::SSEClient sse(client, "/stay-open");
  21104. std::atomic<bool> connected{false};
  21105. sse.on_open([&connected]() { connected.store(true); });
  21106. sse.set_reconnect_interval(100);
  21107. sse.set_max_reconnect_attempts(1);
  21108. sse.start_async();
  21109. // Wait for connection to establish
  21110. for (int i = 0; i < 20 && !connected.load(); ++i) {
  21111. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21112. }
  21113. EXPECT_TRUE(connected.load());
  21114. EXPECT_TRUE(sse.is_connected());
  21115. // Signal handler to stop
  21116. handler_running.store(false);
  21117. // Stop SSE client
  21118. sse.stop();
  21119. EXPECT_FALSE(sse.is_connected());
  21120. }
  21121. // Test: SSEClient with custom headers
  21122. TEST_F(SSEIntegrationTest, CustomHeaders) {
  21123. // Setup a server endpoint that checks for custom header
  21124. std::atomic<bool> header_received{false};
  21125. server_->Get("/header-check", [&](const Request &req, Response &res) {
  21126. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  21127. header_received.store(true);
  21128. }
  21129. res.set_chunked_content_provider("text/event-stream",
  21130. [](size_t, DataSink &) { return false; });
  21131. });
  21132. Client client("localhost", get_port());
  21133. Headers headers = {{"X-Custom-Header", "custom-value"}};
  21134. sse::SSEClient sse(client, "/header-check", headers);
  21135. sse.set_max_reconnect_attempts(1);
  21136. sse.start_async();
  21137. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21138. sse.stop();
  21139. EXPECT_TRUE(header_received.load());
  21140. }
  21141. // Test: Reconnect interval configuration
  21142. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  21143. Client client("localhost", get_port());
  21144. sse::SSEClient sse(client, "/events");
  21145. auto &result = sse.set_reconnect_interval(500);
  21146. // Builder pattern should return reference to self
  21147. EXPECT_EQ(&result, &sse);
  21148. }
  21149. // Test: Max reconnect attempts
  21150. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  21151. // Connect to non-existent port to force reconnects
  21152. Client client("localhost", 59998);
  21153. sse::SSEClient sse(client, "/events");
  21154. std::atomic<int> error_count{0};
  21155. sse.on_error([&](Error) { error_count.fetch_add(1); });
  21156. sse.set_reconnect_interval(50);
  21157. sse.set_max_reconnect_attempts(2);
  21158. auto start = std::chrono::steady_clock::now();
  21159. sse.start(); // Blocking call
  21160. auto end = std::chrono::steady_clock::now();
  21161. // Should have stopped after 2 failed attempts
  21162. EXPECT_GE(error_count.load(), 2);
  21163. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  21164. auto duration =
  21165. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  21166. #ifdef _WIN32
  21167. // Windows is much slower for socket connection failures
  21168. EXPECT_LT(duration.count(), 7000);
  21169. #else
  21170. EXPECT_LT(duration.count(), 1000);
  21171. #endif
  21172. }
  21173. // Test: Multi-line data in integration
  21174. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  21175. // Endpoint with multi-line data
  21176. server_->Get("/multiline-data", [](const Request &, Response &res) {
  21177. res.set_chunked_content_provider(
  21178. "text/event-stream", [](size_t offset, DataSink &sink) {
  21179. if (offset == 0) {
  21180. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  21181. sink.write(event.data(), event.size());
  21182. }
  21183. return false;
  21184. });
  21185. });
  21186. Client client("localhost", get_port());
  21187. sse::SSEClient sse(client, "/multiline-data");
  21188. std::string received_data;
  21189. std::mutex data_mutex;
  21190. sse.on_message([&](const sse::SSEMessage &msg) {
  21191. std::lock_guard<std::mutex> lock(data_mutex);
  21192. received_data = msg.data;
  21193. });
  21194. sse.set_reconnect_interval(100);
  21195. sse.set_max_reconnect_attempts(1);
  21196. sse.start_async();
  21197. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21198. sse.stop();
  21199. std::lock_guard<std::mutex> lock(data_mutex);
  21200. EXPECT_EQ(received_data, "line1\nline2\nline3");
  21201. }
  21202. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  21203. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  21204. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  21205. DataSink &sink) {
  21206. if (offset == 0) {
  21207. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  21208. sink.write(events.data(), events.size());
  21209. }
  21210. return false;
  21211. });
  21212. });
  21213. Client client("localhost", get_port());
  21214. sse::SSEClient sse(client, "/empty-data-lines");
  21215. std::mutex mutex;
  21216. std::condition_variable cv;
  21217. std::vector<std::string> received;
  21218. sse.on_message([&](const sse::SSEMessage &msg) {
  21219. std::lock_guard<std::mutex> lock(mutex);
  21220. received.push_back(msg.data);
  21221. cv.notify_all();
  21222. });
  21223. sse.set_max_reconnect_attempts(1);
  21224. sse.start_async();
  21225. {
  21226. std::unique_lock<std::mutex> lock(mutex);
  21227. cv.wait_for(lock, std::chrono::seconds(2),
  21228. [&] { return received.size() >= 3; });
  21229. }
  21230. sse.stop();
  21231. ASSERT_GE(received.size(), 3u);
  21232. EXPECT_EQ(received[0], "");
  21233. EXPECT_EQ(received[1], "\nhello");
  21234. EXPECT_EQ(received[2], "");
  21235. }
  21236. // Test: Auto-reconnect after server disconnection
  21237. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  21238. std::atomic<int> connection_count{0};
  21239. std::atomic<int> message_count{0};
  21240. // Endpoint that sends one event and closes, forcing reconnect
  21241. server_->Get("/reconnect-test",
  21242. [&connection_count](const Request &, Response &res) {
  21243. connection_count.fetch_add(1);
  21244. res.set_chunked_content_provider(
  21245. "text/event-stream", [](size_t offset, DataSink &sink) {
  21246. if (offset == 0) {
  21247. std::string event = "data: hello\n\n";
  21248. sink.write(event.data(), event.size());
  21249. }
  21250. return false; // Close connection after sending
  21251. });
  21252. });
  21253. Client client("localhost", get_port());
  21254. sse::SSEClient sse(client, "/reconnect-test");
  21255. sse.on_message([&message_count](const sse::SSEMessage &) {
  21256. message_count.fetch_add(1);
  21257. });
  21258. sse.set_reconnect_interval(100);
  21259. sse.set_max_reconnect_attempts(3);
  21260. sse.start_async();
  21261. // Wait long enough for multiple reconnects
  21262. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21263. sse.stop();
  21264. // Should have connected multiple times (initial + reconnects)
  21265. EXPECT_GE(connection_count.load(), 2);
  21266. // Should have received messages from multiple connections
  21267. EXPECT_GE(message_count.load(), 2);
  21268. }
  21269. // Test: A retry field that is not all ASCII digits is ignored
  21270. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  21271. std::atomic<int> connection_count{0};
  21272. server_->Get("/bad-retry",
  21273. [&connection_count](const Request &, Response &res) {
  21274. connection_count.fetch_add(1);
  21275. res.set_chunked_content_provider(
  21276. "text/event-stream", [](size_t offset, DataSink &sink) {
  21277. if (offset == 0) {
  21278. std::string event = "retry: -1\ndata: hello\n\n";
  21279. sink.write(event.data(), event.size());
  21280. }
  21281. return false;
  21282. });
  21283. });
  21284. Client client("localhost", get_port());
  21285. sse::SSEClient sse(client, "/bad-retry");
  21286. sse.set_reconnect_interval(10000);
  21287. sse.start_async();
  21288. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21289. sse.stop();
  21290. EXPECT_EQ(connection_count.load(), 1);
  21291. }
  21292. // Test: A retry field of all ASCII digits sets the reconnection time
  21293. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  21294. std::mutex mutex;
  21295. std::condition_variable cv;
  21296. std::vector<std::chrono::steady_clock::time_point> connected_at;
  21297. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  21298. {
  21299. std::lock_guard<std::mutex> lock(mutex);
  21300. connected_at.push_back(std::chrono::steady_clock::now());
  21301. cv.notify_all();
  21302. }
  21303. res.set_chunked_content_provider(
  21304. "text/event-stream", [](size_t offset, DataSink &sink) {
  21305. if (offset == 0) {
  21306. std::string event = "retry: 0\ndata: hello\n\n";
  21307. sink.write(event.data(), event.size());
  21308. }
  21309. return false;
  21310. });
  21311. });
  21312. Client client("localhost", get_port());
  21313. sse::SSEClient sse(client, "/zero-retry");
  21314. sse.set_reconnect_interval(10000);
  21315. sse.start_async();
  21316. {
  21317. std::unique_lock<std::mutex> lock(mutex);
  21318. cv.wait_for(lock, std::chrono::seconds(5),
  21319. [&] { return connected_at.size() >= 2; });
  21320. }
  21321. sse.stop();
  21322. // The server-supplied interval is applied, but never below 100ms, so
  21323. // "retry: 0" does not cause a busy reconnect loop
  21324. std::lock_guard<std::mutex> lock(mutex);
  21325. ASSERT_GE(connected_at.size(), 2u);
  21326. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  21327. connected_at[1] - connected_at[0])
  21328. .count();
  21329. EXPECT_GE(interval_ms, 100);
  21330. }
  21331. // Test: Last-Event-ID sent on reconnect
  21332. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  21333. std::atomic<int> connection_count{0};
  21334. std::vector<std::string> received_last_event_ids;
  21335. std::mutex id_mutex;
  21336. // Endpoint that checks Last-Event-ID header and sends event with ID
  21337. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  21338. int conn = connection_count.fetch_add(1);
  21339. // Capture the Last-Event-ID header from each connection
  21340. {
  21341. std::lock_guard<std::mutex> lock(id_mutex);
  21342. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  21343. }
  21344. res.set_chunked_content_provider(
  21345. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  21346. if (offset == 0) {
  21347. std::string event =
  21348. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  21349. sink.write(event.data(), event.size());
  21350. }
  21351. return false;
  21352. });
  21353. });
  21354. Client client("localhost", get_port());
  21355. sse::SSEClient sse(client, "/reconnect-with-id");
  21356. sse.set_reconnect_interval(100);
  21357. sse.set_max_reconnect_attempts(3);
  21358. sse.start_async();
  21359. // Wait for at least 2 connections
  21360. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21361. sse.stop();
  21362. // Verify behavior
  21363. std::lock_guard<std::mutex> lock(id_mutex);
  21364. EXPECT_GE(received_last_event_ids.size(), 2u);
  21365. // First connection should have no Last-Event-ID
  21366. if (!received_last_event_ids.empty()) {
  21367. EXPECT_EQ(received_last_event_ids[0], "");
  21368. }
  21369. // Second connection should have Last-Event-ID from first connection
  21370. if (received_last_event_ids.size() >= 2) {
  21371. EXPECT_EQ(received_last_event_ids[1], "event-0");
  21372. }
  21373. }
  21374. // Test: set_headers updates headers used on reconnect
  21375. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  21376. std::vector<std::string> received_tokens;
  21377. std::mutex token_mutex;
  21378. // Endpoint that captures Authorization header
  21379. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  21380. {
  21381. std::lock_guard<std::mutex> lock(token_mutex);
  21382. received_tokens.push_back(req.get_header_value("Authorization"));
  21383. }
  21384. res.set_chunked_content_provider(
  21385. "text/event-stream", [](size_t offset, DataSink &sink) {
  21386. if (offset == 0) {
  21387. std::string event = "data: hello\n\n";
  21388. sink.write(event.data(), event.size());
  21389. }
  21390. return false; // Close connection to trigger reconnect
  21391. });
  21392. });
  21393. Client client("localhost", get_port());
  21394. Headers headers = {{"Authorization", "Bearer old-token"}};
  21395. sse::SSEClient sse(client, "/auth-check", headers);
  21396. // Update headers on each successful connection
  21397. sse.on_open(
  21398. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  21399. sse.set_reconnect_interval(100);
  21400. sse.set_max_reconnect_attempts(3);
  21401. sse.start_async();
  21402. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21403. sse.stop();
  21404. std::lock_guard<std::mutex> lock(token_mutex);
  21405. ASSERT_GE(received_tokens.size(), 2u);
  21406. // First connection uses original header
  21407. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  21408. // Second connection uses updated header from set_headers
  21409. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  21410. }
  21411. // Test: 401 allows reconnection (so on_error can refresh headers)
  21412. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  21413. std::atomic<int> connection_count{0};
  21414. // Endpoint: returns 401 on first attempt, 200 on second
  21415. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  21416. int conn = connection_count.fetch_add(1);
  21417. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  21418. res.status = StatusCode::Unauthorized_401;
  21419. res.set_content("Unauthorized", "text/plain");
  21420. return;
  21421. }
  21422. res.set_chunked_content_provider(
  21423. "text/event-stream", [](size_t offset, DataSink &sink) {
  21424. if (offset == 0) {
  21425. std::string event = "data: authenticated\n\n";
  21426. sink.write(event.data(), event.size());
  21427. }
  21428. return false;
  21429. });
  21430. });
  21431. Client client("localhost", get_port());
  21432. Headers headers = {{"Authorization", "Bearer expired"}};
  21433. sse::SSEClient sse(client, "/auth-retry", headers);
  21434. std::atomic<bool> message_received{false};
  21435. // Refresh token on error
  21436. sse.on_error(
  21437. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  21438. sse.on_message([&](const sse::SSEMessage &msg) {
  21439. if (msg.data == "authenticated") { message_received.store(true); }
  21440. });
  21441. sse.set_reconnect_interval(100);
  21442. sse.set_max_reconnect_attempts(3);
  21443. sse.start_async();
  21444. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21445. sse.stop();
  21446. // Should have reconnected after 401 and succeeded with new token
  21447. EXPECT_GE(connection_count.load(), 2);
  21448. EXPECT_TRUE(message_received.load());
  21449. }
  21450. TEST(Issue2318Test, EmptyHostString) {
  21451. {
  21452. httplib::Client cli_empty("", PORT);
  21453. auto res = cli_empty.Get("/");
  21454. ASSERT_FALSE(res);
  21455. EXPECT_EQ(httplib::Error::Connection, res.error());
  21456. }
  21457. {
  21458. httplib::Client cli(" ", PORT);
  21459. auto res = cli.Get("/");
  21460. ASSERT_FALSE(res);
  21461. EXPECT_EQ(httplib::Error::Connection, res.error());
  21462. }
  21463. }
  21464. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21465. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  21466. Server svr;
  21467. // Set a small payload limit (1KB)
  21468. svr.set_payload_max_length(1024);
  21469. svr.Post("/test", [&](const Request &req, Response &res) {
  21470. res.set_content("Body size: " + std::to_string(req.body.size()),
  21471. "text/plain");
  21472. });
  21473. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  21474. auto se = detail::scope_exit([&] {
  21475. svr.stop();
  21476. listen_thread.join();
  21477. });
  21478. svr.wait_until_ready();
  21479. // Create data that compresses well but exceeds limit when decompressed
  21480. // 8KB of repeated null bytes compresses to a very small size
  21481. std::string original_data(8 * 1024, '\0');
  21482. // Compress the data using gzip
  21483. std::string compressed_data;
  21484. detail::gzip_compressor compressor;
  21485. compressor.compress(original_data.data(), original_data.size(), true,
  21486. [&](const char *data, size_t size) {
  21487. compressed_data.append(data, size);
  21488. return true;
  21489. });
  21490. // Verify compression worked (compressed should be much smaller)
  21491. ASSERT_LT(compressed_data.size(), original_data.size());
  21492. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  21493. // Send compressed data with Content-Encoding: gzip
  21494. Client cli(HOST, PORT);
  21495. Headers headers = {{"Content-Encoding", "gzip"}};
  21496. auto res =
  21497. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  21498. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  21499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21500. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  21501. }
  21502. #endif
  21503. // ============================================================================
  21504. // OpenSSL-Specific Tests
  21505. // ============================================================================
  21506. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21507. X509 *readCertificate(const std::string &strFileName) {
  21508. std::ifstream inStream(strFileName);
  21509. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  21510. std::istreambuf_iterator<char>());
  21511. if (strCertPEM.empty()) return (nullptr);
  21512. BIO *pbCert = BIO_new(BIO_s_mem());
  21513. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  21514. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  21515. BIO_free(pbCert);
  21516. return (pCert);
  21517. }
  21518. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  21519. std::ifstream inStream(strFileName);
  21520. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  21521. std::istreambuf_iterator<char>());
  21522. if (strPrivateKeyPEM.empty()) return (nullptr);
  21523. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  21524. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  21525. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  21526. BIO_free(pbPrivKey);
  21527. return (pPrivateKey);
  21528. }
  21529. TEST(BindServerTest, UpdateCerts) {
  21530. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21531. int port = svr.bind_to_any_port("0.0.0.0");
  21532. ASSERT_TRUE(svr.is_valid());
  21533. ASSERT_TRUE(port > 0);
  21534. X509 *cert = readCertificate(SERVER_CERT_FILE);
  21535. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  21536. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  21537. ASSERT_TRUE(cert != nullptr);
  21538. ASSERT_TRUE(ca_cert != nullptr);
  21539. ASSERT_TRUE(key != nullptr);
  21540. X509_STORE *cert_store = X509_STORE_new();
  21541. X509_STORE_add_cert(cert_store, ca_cert);
  21542. // svr.update_certs(cert, key, cert_store); // deprecated
  21543. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21544. CLIENT_CA_CERT_FILE);
  21545. ASSERT_TRUE(svr.is_valid());
  21546. svr.stop();
  21547. X509_STORE_free(cert_store);
  21548. X509_free(cert);
  21549. X509_free(ca_cert);
  21550. EVP_PKEY_free(key);
  21551. }
  21552. // Test that update_certs() updates client CA list correctly
  21553. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  21554. // Start with file-based constructor
  21555. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21556. ASSERT_TRUE(svr.is_valid());
  21557. // Initially no client CA list should be set
  21558. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21559. ASSERT_TRUE(ssl_ctx != nullptr);
  21560. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  21561. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  21562. EXPECT_EQ(0, count_before);
  21563. // Now update with client CA (PEM string)
  21564. std::string cert_pem, key_pem, ca_pem;
  21565. read_file(SERVER_CERT_FILE, cert_pem);
  21566. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  21567. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  21568. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  21569. ASSERT_TRUE(svr.is_valid());
  21570. // Now client CA list should be set
  21571. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  21572. ASSERT_TRUE(ca_list_after != nullptr);
  21573. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  21574. }
  21575. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  21576. // Test that the file-path SSLServer constructor properly sets the client CA
  21577. // list that is sent to clients during the TLS handshake (CertificateRequest)
  21578. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21579. ASSERT_TRUE(svr.is_valid());
  21580. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21581. ASSERT_TRUE(ssl_ctx != nullptr);
  21582. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  21583. ASSERT_TRUE(ca_list != nullptr);
  21584. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  21585. }
  21586. #endif
  21587. // ============================================================================
  21588. // MbedTLS-Specific Tests
  21589. // ============================================================================
  21590. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  21591. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  21592. using namespace httplib::tls;
  21593. // Track if callback was invoked
  21594. bool callback_invoked = false;
  21595. // The callback receives void* ctx which is actually MbedTlsContext*
  21596. // We can access the mbedtls_ssl_config via the context
  21597. auto setup_callback = [&callback_invoked](void *ctx) {
  21598. callback_invoked = true;
  21599. // Cast to MbedTlsContext* to access the ssl config
  21600. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  21601. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  21602. // Use static variables to hold certificate data (simplified for test)
  21603. static mbedtls_x509_crt own_cert;
  21604. static mbedtls_pk_context own_key;
  21605. static mbedtls_x509_crt ca_chain;
  21606. static bool initialized = false;
  21607. if (!initialized) {
  21608. mbedtls_x509_crt_init(&own_cert);
  21609. mbedtls_pk_init(&own_key);
  21610. mbedtls_x509_crt_init(&ca_chain);
  21611. // Load server certificate
  21612. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  21613. return false;
  21614. }
  21615. // Load server private key.
  21616. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  21617. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  21618. #if MBEDTLS_VERSION_MAJOR == 3
  21619. ,
  21620. mbedtls_ctr_drbg_random, nullptr
  21621. #endif
  21622. ) != 0) {
  21623. return false;
  21624. }
  21625. // Load CA chain for client verification
  21626. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  21627. return false;
  21628. }
  21629. initialized = true;
  21630. }
  21631. // Configure the SSL config
  21632. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  21633. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  21634. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  21635. // Set minimum TLS version using mbedTLS native API
  21636. #if MBEDTLS_VERSION_MAJOR >= 3
  21637. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  21638. #else
  21639. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  21640. MBEDTLS_SSL_MINOR_VERSION_3);
  21641. #endif
  21642. return true;
  21643. };
  21644. SSLServer svr(setup_callback);
  21645. ASSERT_TRUE(svr.is_valid());
  21646. ASSERT_TRUE(callback_invoked);
  21647. svr.Get("/test", [&](const Request &req, Response &res) {
  21648. res.set_content("test", "text/plain");
  21649. auto cert = req.peer_cert();
  21650. ASSERT_TRUE(static_cast<bool>(cert));
  21651. auto common_name = cert.subject_cn();
  21652. EXPECT_EQ("Common Name", common_name);
  21653. });
  21654. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21655. auto se = detail::scope_exit([&] {
  21656. svr.stop();
  21657. t.join();
  21658. ASSERT_FALSE(svr.is_running());
  21659. });
  21660. svr.wait_until_ready();
  21661. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  21662. cli.enable_server_certificate_verification(false);
  21663. cli.set_connection_timeout(30);
  21664. auto res = cli.Get("/test");
  21665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21666. ASSERT_EQ(StatusCode::OK_200, res->status);
  21667. }
  21668. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  21669. // context (owning mbedtls_ssl_config) before shutting down a still-open
  21670. // keep-alive SSL session, which reads through that config in
  21671. // mbedtls_ssl_close_notify.
  21672. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  21673. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21674. ASSERT_TRUE(svr.is_valid());
  21675. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  21676. res.set_content("test", "text/plain");
  21677. });
  21678. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21679. auto se = detail::scope_exit([&] {
  21680. svr.stop();
  21681. t.join();
  21682. ASSERT_FALSE(svr.is_running());
  21683. });
  21684. svr.wait_until_ready();
  21685. {
  21686. SSLClient cli(HOST, PORT);
  21687. cli.enable_server_certificate_verification(false);
  21688. cli.set_keep_alive(true);
  21689. auto res = cli.Get("/test");
  21690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21691. ASSERT_EQ(StatusCode::OK_200, res->status);
  21692. // cli is destructed here with the keep-alive SSL session still open.
  21693. }
  21694. }
  21695. #endif
  21696. // WebSocket Tests
  21697. TEST(WebSocketTest, RSVBitsMustBeZero) {
  21698. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  21699. // defining the meaning of these bits has been negotiated.
  21700. auto make_frame = [](uint8_t first_byte) {
  21701. std::string frame;
  21702. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  21703. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  21704. frame += "Hello";
  21705. return frame;
  21706. };
  21707. // RSV1 set (0x40)
  21708. {
  21709. detail::BufferStream strm;
  21710. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  21711. ws::Opcode opcode;
  21712. std::string payload;
  21713. bool fin;
  21714. EXPECT_EQ(
  21715. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21716. ws::impl::FrameRead::Fail);
  21717. }
  21718. // RSV2 set (0x20)
  21719. {
  21720. detail::BufferStream strm;
  21721. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  21722. ws::Opcode opcode;
  21723. std::string payload;
  21724. bool fin;
  21725. EXPECT_EQ(
  21726. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21727. ws::impl::FrameRead::Fail);
  21728. }
  21729. // RSV3 set (0x10)
  21730. {
  21731. detail::BufferStream strm;
  21732. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  21733. ws::Opcode opcode;
  21734. std::string payload;
  21735. bool fin;
  21736. EXPECT_EQ(
  21737. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21738. ws::impl::FrameRead::Fail);
  21739. }
  21740. // No RSV bits set - should succeed
  21741. {
  21742. detail::BufferStream strm;
  21743. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  21744. ws::Opcode opcode;
  21745. std::string payload;
  21746. bool fin;
  21747. EXPECT_EQ(
  21748. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21749. ws::impl::FrameRead::Ok);
  21750. EXPECT_EQ(ws::Opcode::Text, opcode);
  21751. EXPECT_EQ("Hello", payload);
  21752. EXPECT_TRUE(fin);
  21753. }
  21754. }
  21755. TEST(WebSocketTest, ControlFrameValidation) {
  21756. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  21757. // payload length <= 125.
  21758. // Ping with FIN=0 - must be rejected
  21759. {
  21760. detail::BufferStream strm;
  21761. std::string frame;
  21762. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  21763. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21764. strm.write(frame.data(), frame.size());
  21765. ws::Opcode opcode;
  21766. std::string payload;
  21767. bool fin;
  21768. EXPECT_EQ(
  21769. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21770. ws::impl::FrameRead::Fail);
  21771. }
  21772. // Close with FIN=0 - must be rejected
  21773. {
  21774. detail::BufferStream strm;
  21775. std::string frame;
  21776. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  21777. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21778. strm.write(frame.data(), frame.size());
  21779. ws::Opcode opcode;
  21780. std::string payload;
  21781. bool fin;
  21782. EXPECT_EQ(
  21783. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21784. ws::impl::FrameRead::Fail);
  21785. }
  21786. // Ping with payload_len=126 (extended length) - must be rejected
  21787. {
  21788. detail::BufferStream strm;
  21789. std::string frame;
  21790. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21791. frame += static_cast<char>(126); // payload_len=126 (>125)
  21792. frame += static_cast<char>(0x00); // extended length high byte
  21793. frame += static_cast<char>(126); // extended length low byte
  21794. frame += std::string(126, 'x');
  21795. strm.write(frame.data(), frame.size());
  21796. ws::Opcode opcode;
  21797. std::string payload;
  21798. bool fin;
  21799. EXPECT_EQ(
  21800. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21801. ws::impl::FrameRead::Fail);
  21802. }
  21803. // Ping with FIN=1 and payload_len=125 - should succeed
  21804. {
  21805. detail::BufferStream strm;
  21806. std::string frame;
  21807. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21808. frame += static_cast<char>(125); // payload_len=125
  21809. frame += std::string(125, 'x');
  21810. strm.write(frame.data(), frame.size());
  21811. ws::Opcode opcode;
  21812. std::string payload;
  21813. bool fin;
  21814. EXPECT_EQ(
  21815. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21816. ws::impl::FrameRead::Ok);
  21817. EXPECT_EQ(ws::Opcode::Ping, opcode);
  21818. EXPECT_EQ(125u, payload.size());
  21819. EXPECT_TRUE(fin);
  21820. }
  21821. }
  21822. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  21823. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  21824. // length MUST be 0.
  21825. // MSB set - must be rejected
  21826. {
  21827. detail::BufferStream strm;
  21828. std::string frame;
  21829. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21830. frame += static_cast<char>(127); // 64-bit extended length
  21831. frame += static_cast<char>(0x80); // MSB set (invalid)
  21832. frame += std::string(7, '\0'); // remaining 7 bytes of length
  21833. strm.write(frame.data(), frame.size());
  21834. ws::Opcode opcode;
  21835. std::string payload;
  21836. bool fin;
  21837. EXPECT_EQ(
  21838. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21839. ws::impl::FrameRead::Fail);
  21840. }
  21841. // MSB clear - should pass length parsing (will be rejected by max_len,
  21842. // but that's a different check; use a small length to verify)
  21843. {
  21844. detail::BufferStream strm;
  21845. std::string frame;
  21846. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21847. frame += static_cast<char>(127); // 64-bit extended length
  21848. frame += std::string(7, '\0'); // high bytes = 0
  21849. frame += static_cast<char>(0x03); // length = 3
  21850. frame += "abc";
  21851. strm.write(frame.data(), frame.size());
  21852. ws::Opcode opcode;
  21853. std::string payload;
  21854. bool fin;
  21855. EXPECT_EQ(
  21856. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21857. ws::impl::FrameRead::Ok);
  21858. EXPECT_EQ(ws::Opcode::Text, opcode);
  21859. EXPECT_EQ("abc", payload);
  21860. }
  21861. }
  21862. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  21863. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  21864. // Valid UTF-8
  21865. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  21866. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  21867. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  21868. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  21869. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  21870. // Invalid UTF-8
  21871. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  21872. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  21873. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  21874. EXPECT_FALSE(
  21875. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  21876. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  21877. }
  21878. TEST(WebSocketTest, ConnectAndDisconnect) {
  21879. Server svr;
  21880. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21881. std::string msg;
  21882. while (ws.read(msg)) {}
  21883. });
  21884. auto port = svr.bind_to_any_port(HOST);
  21885. std::thread t([&]() { svr.listen_after_bind(); });
  21886. svr.wait_until_ready();
  21887. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21888. auto res = client.connect();
  21889. ASSERT_TRUE(res);
  21890. EXPECT_EQ(Error::Success, res.error());
  21891. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  21892. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  21893. EXPECT_TRUE(client.is_open());
  21894. client.close();
  21895. EXPECT_FALSE(client.is_open());
  21896. svr.stop();
  21897. t.join();
  21898. }
  21899. TEST(WebSocketTest, ValidURL) {
  21900. ws::WebSocketClient ws1("ws://localhost:8080/path");
  21901. EXPECT_TRUE(ws1.is_valid());
  21902. ws::WebSocketClient ws2("ws://example.com/path");
  21903. EXPECT_TRUE(ws2.is_valid());
  21904. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  21905. EXPECT_TRUE(ws3.is_valid());
  21906. #ifdef CPPHTTPLIB_SSL_ENABLED
  21907. ws::WebSocketClient wss1("wss://example.com/path");
  21908. EXPECT_TRUE(wss1.is_valid());
  21909. ws::WebSocketClient wss2("wss://example.com:443/path");
  21910. EXPECT_TRUE(wss2.is_valid());
  21911. #endif
  21912. }
  21913. TEST(WebSocketTest, InvalidURL) {
  21914. // No scheme
  21915. ws::WebSocketClient ws1("localhost:8080/path");
  21916. EXPECT_FALSE(ws1.is_valid());
  21917. // No path
  21918. ws::WebSocketClient ws2("ws://localhost:8080");
  21919. EXPECT_FALSE(ws2.is_valid());
  21920. // Empty string
  21921. ws::WebSocketClient ws3("");
  21922. EXPECT_FALSE(ws3.is_valid());
  21923. // Missing host
  21924. ws::WebSocketClient ws4("ws://:8080/path");
  21925. EXPECT_FALSE(ws4.is_valid());
  21926. // Port number overflow — should not crash
  21927. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  21928. EXPECT_FALSE(ws5.is_valid());
  21929. // Port out of range
  21930. ws::WebSocketClient ws6("ws://localhost:99999/path");
  21931. EXPECT_FALSE(ws6.is_valid());
  21932. }
  21933. TEST(WebSocketTest, UnsupportedScheme) {
  21934. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  21935. ws::WebSocketClient ws1("http://localhost:8080/path");
  21936. EXPECT_FALSE(ws1.is_valid());
  21937. ws::WebSocketClient ws2("https://localhost:8080/path");
  21938. EXPECT_FALSE(ws2.is_valid());
  21939. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  21940. EXPECT_FALSE(ws3.is_valid());
  21941. #else
  21942. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  21943. std::invalid_argument);
  21944. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  21945. std::invalid_argument);
  21946. #endif
  21947. }
  21948. TEST(WebSocketTest, ConnectWhenInvalid) {
  21949. ws::WebSocketClient ws("not a valid url");
  21950. EXPECT_FALSE(ws.is_valid());
  21951. auto res = ws.connect();
  21952. EXPECT_FALSE(res);
  21953. EXPECT_EQ(Error::Connection, res.error());
  21954. EXPECT_EQ(-1, res.status());
  21955. }
  21956. TEST(WebSocketTest, ConnectRefusedReportsError) {
  21957. // Grab a port that is free, then close it again so nothing listens there
  21958. Server svr;
  21959. auto port = svr.bind_to_any_port(HOST);
  21960. svr.stop();
  21961. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21962. auto res = client.connect();
  21963. ASSERT_FALSE(res);
  21964. EXPECT_EQ(Error::Connection, res.error());
  21965. EXPECT_EQ(-1, res.status());
  21966. }
  21967. TEST(WebSocketTest, DefaultPort) {
  21968. ws::WebSocketClient ws1("ws://example.com/path");
  21969. EXPECT_TRUE(ws1.is_valid());
  21970. // ws:// defaults to port 80 (verified by successful parse)
  21971. #ifdef CPPHTTPLIB_SSL_ENABLED
  21972. ws::WebSocketClient ws2("wss://example.com/path");
  21973. EXPECT_TRUE(ws2.is_valid());
  21974. // wss:// defaults to port 443 (verified by successful parse)
  21975. #endif
  21976. }
  21977. TEST(WebSocketTest, IPv6LiteralAddress) {
  21978. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  21979. EXPECT_TRUE(ws1.is_valid());
  21980. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  21981. EXPECT_TRUE(ws2.is_valid());
  21982. }
  21983. TEST(WebSocketTest, ComplexPath) {
  21984. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  21985. EXPECT_TRUE(ws1.is_valid());
  21986. ws::WebSocketClient ws2("ws://localhost:8080/");
  21987. EXPECT_TRUE(ws2.is_valid());
  21988. }
  21989. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  21990. Server svr;
  21991. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21992. std::string msg;
  21993. while (ws.read(msg)) {}
  21994. });
  21995. auto port = svr.bind_to_any_port(HOST);
  21996. std::thread t([&]() { svr.listen_after_bind(); });
  21997. svr.wait_until_ready();
  21998. auto another_host = "example.com";
  21999. auto wrong_ip = "192.0.2.1";
  22000. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22001. client.set_hostname_addr_map({{another_host, wrong_ip}});
  22002. ASSERT_TRUE(client.connect());
  22003. EXPECT_TRUE(client.is_open());
  22004. client.close();
  22005. svr.stop();
  22006. t.join();
  22007. }
  22008. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  22009. Server svr;
  22010. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22011. std::string msg;
  22012. while (ws.read(msg)) {}
  22013. });
  22014. auto port = svr.bind_to_any_port(HOST);
  22015. std::thread t([&]() { svr.listen_after_bind(); });
  22016. svr.wait_until_ready();
  22017. auto wrong_ip = "192.0.2.1";
  22018. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22019. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  22020. client.set_connection_timeout(1);
  22021. client.set_read_timeout(1);
  22022. client.set_write_timeout(1);
  22023. EXPECT_FALSE(client.connect());
  22024. EXPECT_FALSE(client.is_open());
  22025. svr.stop();
  22026. t.join();
  22027. }
  22028. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  22029. // A mapped value that is not an IP literal must be resolved. HOST resolves
  22030. // from the hosts file, so this test needs no external DNS. "target.invalid"
  22031. // (RFC 6761) is only a map key and the Host header value.
  22032. auto host = "target.invalid";
  22033. Server svr;
  22034. std::string received_host;
  22035. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22036. received_host = req.get_header_value("Host");
  22037. std::string msg;
  22038. while (ws.read(msg)) {}
  22039. });
  22040. auto port = svr.bind_to_any_port(HOST);
  22041. std::thread t([&]() { svr.listen_after_bind(); });
  22042. // ASSERT_* below returns from the test body, which would leave t joinable
  22043. // and make ~thread call std::terminate.
  22044. auto se = detail::scope_exit([&] {
  22045. svr.stop();
  22046. if (t.joinable()) { t.join(); }
  22047. });
  22048. svr.wait_until_ready();
  22049. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  22050. std::to_string(port) + "/ws");
  22051. client.set_hostname_addr_map({{host, HOST}});
  22052. ASSERT_TRUE(client.connect());
  22053. EXPECT_TRUE(client.is_open());
  22054. client.close();
  22055. svr.stop();
  22056. t.join();
  22057. // The mapping only redirects the connection; the identity stays host_.
  22058. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  22059. }
  22060. class WebSocketIntegrationTest : public ::testing::Test {
  22061. protected:
  22062. void SetUp() override {
  22063. server_ = httplib::detail::make_unique<Server>();
  22064. setup_server();
  22065. start_server();
  22066. }
  22067. void TearDown() override {
  22068. server_->stop();
  22069. if (server_thread_.joinable()) { server_thread_.join(); }
  22070. }
  22071. void setup_server() {
  22072. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22073. std::string msg;
  22074. ws::ReadResult ret;
  22075. while ((ret = ws.read(msg))) {
  22076. if (ret == ws::Binary) {
  22077. ws.send(msg.data(), msg.size());
  22078. } else {
  22079. ws.send(msg);
  22080. }
  22081. }
  22082. });
  22083. server_->WebSocket("/ws-echo-string",
  22084. [](const Request &, ws::WebSocket &ws) {
  22085. std::string msg;
  22086. while (ws.read(msg)) {
  22087. ws.send("echo: " + msg);
  22088. }
  22089. });
  22090. server_->WebSocket(
  22091. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  22092. // Echo back request metadata
  22093. ws.send("path:" + req.path);
  22094. ws.send("header:" + req.get_header_value("X-Test-Header"));
  22095. std::string msg;
  22096. while (ws.read(msg)) {}
  22097. });
  22098. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  22099. std::string msg;
  22100. ws.read(msg); // wait for a message
  22101. ws.close();
  22102. });
  22103. server_->WebSocket("/ws-close-status",
  22104. [](const Request &, ws::WebSocket &ws) {
  22105. std::string msg;
  22106. ws.read(msg); // wait for a message
  22107. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  22108. });
  22109. server_->WebSocket(
  22110. "/ws-subprotocol",
  22111. [](const Request &, ws::WebSocket &ws) {
  22112. std::string msg;
  22113. while (ws.read(msg)) {
  22114. ws.send(msg);
  22115. }
  22116. },
  22117. [](const std::vector<std::string> &protocols) -> std::string {
  22118. for (const auto &p : protocols) {
  22119. if (p == "graphql-ws") { return p; }
  22120. }
  22121. return "";
  22122. });
  22123. server_->WebSocket(
  22124. "/ws-subprotocol-unoffered",
  22125. [](const Request &, ws::WebSocket &ws) {
  22126. std::string msg;
  22127. while (ws.read(msg)) {
  22128. ws.send(msg);
  22129. }
  22130. },
  22131. [](const std::vector<std::string> &) -> std::string {
  22132. return "admin";
  22133. });
  22134. }
  22135. void start_server() {
  22136. port_ = server_->bind_to_any_port(HOST);
  22137. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22138. server_->wait_until_ready();
  22139. }
  22140. std::unique_ptr<Server> server_;
  22141. std::thread server_thread_;
  22142. int port_ = 0;
  22143. };
  22144. TEST_F(WebSocketIntegrationTest, TextEcho) {
  22145. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22146. "/ws-echo");
  22147. ASSERT_TRUE(client.connect());
  22148. ASSERT_TRUE(client.is_open());
  22149. ASSERT_TRUE(client.send("Hello WebSocket"));
  22150. std::string msg;
  22151. EXPECT_EQ(ws::Text, client.read(msg));
  22152. EXPECT_EQ("Hello WebSocket", msg);
  22153. client.close();
  22154. }
  22155. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  22156. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22157. "/ws-echo");
  22158. ASSERT_TRUE(client.connect());
  22159. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  22160. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  22161. std::string msg;
  22162. EXPECT_EQ(ws::Binary, client.read(msg));
  22163. EXPECT_EQ(binary_data, msg);
  22164. client.close();
  22165. }
  22166. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  22167. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22168. "/ws-echo");
  22169. ASSERT_TRUE(client.connect());
  22170. for (int i = 0; i < 10; i++) {
  22171. auto text = "message " + std::to_string(i);
  22172. ASSERT_TRUE(client.send(text));
  22173. std::string msg;
  22174. ASSERT_TRUE(client.read(msg));
  22175. EXPECT_EQ(text, msg);
  22176. }
  22177. client.close();
  22178. }
  22179. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  22180. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22181. "/ws-close");
  22182. ASSERT_TRUE(client.connect());
  22183. // Send a message to trigger the server to close
  22184. ASSERT_TRUE(client.send("trigger close"));
  22185. // The server will close, so read should return false
  22186. std::string msg;
  22187. EXPECT_FALSE(client.read(msg));
  22188. EXPECT_FALSE(client.is_open());
  22189. }
  22190. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  22191. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22192. "/ws-echo");
  22193. ASSERT_TRUE(client.connect());
  22194. // 128KB message
  22195. std::string large_data(128 * 1024, 'X');
  22196. ASSERT_TRUE(client.send(large_data));
  22197. std::string msg;
  22198. ASSERT_TRUE(client.read(msg));
  22199. EXPECT_EQ(large_data, msg);
  22200. client.close();
  22201. }
  22202. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  22203. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22204. "/ws-echo");
  22205. ASSERT_TRUE(client.connect());
  22206. const int num_threads = 4;
  22207. std::vector<std::thread> threads;
  22208. std::atomic<int> send_count{0};
  22209. for (int t = 0; t < num_threads; t++) {
  22210. threads.emplace_back([&client, &send_count, t]() {
  22211. for (int i = 0; i < 5; i++) {
  22212. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  22213. if (client.send(text)) { send_count++; }
  22214. }
  22215. });
  22216. }
  22217. for (auto &th : threads) {
  22218. th.join();
  22219. }
  22220. int received = 0;
  22221. std::string msg;
  22222. while (received < send_count.load()) {
  22223. if (!client.read(msg)) { break; }
  22224. received++;
  22225. }
  22226. EXPECT_EQ(send_count.load(), received);
  22227. client.close();
  22228. }
  22229. TEST_F(WebSocketIntegrationTest, ReadString) {
  22230. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22231. "/ws-echo-string");
  22232. ASSERT_TRUE(client.connect());
  22233. ASSERT_TRUE(client.send("hello"));
  22234. std::string msg;
  22235. ASSERT_TRUE(client.read(msg));
  22236. EXPECT_EQ("echo: hello", msg);
  22237. ASSERT_TRUE(client.send("world"));
  22238. ASSERT_TRUE(client.read(msg));
  22239. EXPECT_EQ("echo: world", msg);
  22240. client.close();
  22241. }
  22242. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  22243. Headers headers = {{"X-Test-Header", "test-value"}};
  22244. ws::WebSocketClient client(
  22245. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  22246. ASSERT_TRUE(client.connect());
  22247. std::string msg;
  22248. ASSERT_TRUE(client.read(msg));
  22249. EXPECT_EQ("path:/ws-request-info", msg);
  22250. ASSERT_TRUE(client.read(msg));
  22251. EXPECT_EQ("header:test-value", msg);
  22252. client.close();
  22253. }
  22254. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  22255. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22256. "/ws-echo");
  22257. client.set_read_timeout(1, 0); // 1 second
  22258. ASSERT_TRUE(client.connect());
  22259. // Don't send anything — server echo handler waits for a message, so read()
  22260. // should time out. The connection survives it: nothing was consumed.
  22261. std::string msg;
  22262. EXPECT_EQ(client.read(msg), ws::Timeout);
  22263. EXPECT_TRUE(client.is_open());
  22264. // And it is still usable afterwards.
  22265. EXPECT_TRUE(client.send("after timeout"));
  22266. EXPECT_EQ(client.read(msg), ws::Text);
  22267. EXPECT_EQ(msg, "after timeout");
  22268. }
  22269. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  22270. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22271. "/ws-echo");
  22272. client.set_read_timeout(1, 0);
  22273. ASSERT_TRUE(client.connect());
  22274. ASSERT_TRUE(client.send("first"));
  22275. std::string msg;
  22276. ASSERT_EQ(client.read(msg), ws::Text);
  22277. ASSERT_EQ(msg, "first");
  22278. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  22279. // not be used with a read timeout: it would reprocess the previous message.
  22280. EXPECT_EQ(client.read(msg), ws::Timeout);
  22281. EXPECT_EQ(msg, "first");
  22282. }
  22283. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  22284. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22285. "/ws-echo");
  22286. ASSERT_TRUE(client.connect());
  22287. // Setting it once the connection is open reaches the live stream, not just
  22288. // the seed for the next connect().
  22289. client.set_read_timeout(1, 0);
  22290. std::string msg;
  22291. EXPECT_EQ(client.read(msg), ws::Timeout);
  22292. EXPECT_TRUE(client.is_open());
  22293. }
  22294. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  22295. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22296. "/ws-echo");
  22297. client.set_read_timeout(5, 0);
  22298. ASSERT_TRUE(client.connect());
  22299. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22300. // The server should reject it and close the connection.
  22301. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  22302. client.send(oversized);
  22303. // The server's read() should have failed due to payload limit,
  22304. // so our read() should return false (connection closed).
  22305. std::string msg;
  22306. EXPECT_FALSE(client.read(msg));
  22307. }
  22308. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  22309. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22310. "/ws-echo");
  22311. client.set_read_timeout(10, 0);
  22312. ASSERT_TRUE(client.connect());
  22313. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22314. // This should succeed.
  22315. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  22316. ASSERT_TRUE(client.send(at_limit));
  22317. std::string msg;
  22318. ASSERT_TRUE(client.read(msg));
  22319. EXPECT_EQ(at_limit.size(), msg.size());
  22320. client.close();
  22321. }
  22322. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  22323. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22324. "/nonexistent");
  22325. auto res = client.connect();
  22326. EXPECT_FALSE(res);
  22327. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22328. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  22329. EXPECT_FALSE(client.is_open());
  22330. }
  22331. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  22332. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22333. "/ws-echo");
  22334. ASSERT_TRUE(client.connect());
  22335. ASSERT_TRUE(client.send(""));
  22336. std::string msg;
  22337. EXPECT_EQ(ws::Text, client.read(msg));
  22338. EXPECT_EQ("", msg);
  22339. client.close();
  22340. }
  22341. TEST_F(WebSocketIntegrationTest, Reconnect) {
  22342. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22343. "/ws-echo");
  22344. // First connection
  22345. ASSERT_TRUE(client.connect());
  22346. ASSERT_TRUE(client.send("first"));
  22347. std::string msg;
  22348. ASSERT_TRUE(client.read(msg));
  22349. EXPECT_EQ("first", msg);
  22350. client.close();
  22351. EXPECT_FALSE(client.is_open());
  22352. // Reconnect using the same client object
  22353. ASSERT_TRUE(client.connect());
  22354. ASSERT_TRUE(client.is_open());
  22355. ASSERT_TRUE(client.send("second"));
  22356. ASSERT_TRUE(client.read(msg));
  22357. EXPECT_EQ("second", msg);
  22358. client.close();
  22359. }
  22360. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  22361. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22362. "/ws-close-status");
  22363. ASSERT_TRUE(client.connect());
  22364. // Trigger the server to close with GoingAway status
  22365. ASSERT_TRUE(client.send("trigger"));
  22366. // read() should return false after receiving the close frame
  22367. std::string msg;
  22368. EXPECT_FALSE(client.read(msg));
  22369. EXPECT_FALSE(client.is_open());
  22370. }
  22371. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  22372. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22373. "/ws-echo");
  22374. ASSERT_TRUE(client.connect());
  22375. client.close(ws::CloseStatus::GoingAway, "client leaving");
  22376. EXPECT_FALSE(client.is_open());
  22377. }
  22378. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  22379. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  22380. ws::WebSocketClient client(
  22381. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22382. ASSERT_TRUE(client.connect());
  22383. // Server should have selected graphql-ws
  22384. EXPECT_EQ("graphql-ws", client.subprotocol());
  22385. client.close();
  22386. }
  22387. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  22388. Headers headers;
  22389. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  22390. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  22391. ws::WebSocketClient client(
  22392. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22393. ASSERT_TRUE(client.connect());
  22394. // The offer on the second field line counts too, so graphql-ws is selected
  22395. EXPECT_EQ("graphql-ws", client.subprotocol());
  22396. client.close();
  22397. }
  22398. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  22399. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  22400. ws::WebSocketClient client(
  22401. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22402. ASSERT_TRUE(client.connect());
  22403. // Server should not have selected any subprotocol
  22404. EXPECT_TRUE(client.subprotocol().empty());
  22405. client.close();
  22406. }
  22407. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  22408. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22409. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22410. "/ws-subprotocol-unoffered",
  22411. headers);
  22412. ASSERT_TRUE(client.connect());
  22413. EXPECT_TRUE(client.subprotocol().empty());
  22414. client.close();
  22415. }
  22416. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  22417. // Connect without requesting any subprotocol
  22418. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22419. "/ws-subprotocol");
  22420. ASSERT_TRUE(client.connect());
  22421. EXPECT_TRUE(client.subprotocol().empty());
  22422. client.close();
  22423. }
  22424. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  22425. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22426. "/ws-echo");
  22427. client.set_tcp_nodelay(true);
  22428. client.set_connection_timeout(3, 0);
  22429. bool socket_options_called = false;
  22430. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  22431. ASSERT_TRUE(client.connect());
  22432. ASSERT_TRUE(client.is_open());
  22433. EXPECT_TRUE(socket_options_called);
  22434. ASSERT_TRUE(client.send("hello"));
  22435. std::string msg;
  22436. auto result = client.read(msg);
  22437. EXPECT_EQ(result, ws::ReadResult::Text);
  22438. EXPECT_EQ(msg, "hello");
  22439. client.close();
  22440. }
  22441. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  22442. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22443. "/ws-echo");
  22444. client.set_connection_timeout(std::chrono::seconds(3));
  22445. client.set_write_timeout(std::chrono::seconds(3));
  22446. // A sub-second remainder exercises the seconds/microseconds split.
  22447. client.set_read_timeout(std::chrono::milliseconds(1500));
  22448. ASSERT_TRUE(client.connect());
  22449. auto start = std::chrono::steady_clock::now();
  22450. std::string msg;
  22451. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  22452. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  22453. std::chrono::steady_clock::now() - start)
  22454. .count();
  22455. // Above 1s so that dropping the microseconds half of the split fails here.
  22456. // Ignoring the setter altogether would not reach this line at all: a client
  22457. // waits forever by default.
  22458. EXPECT_GE(elapsed, 1400);
  22459. EXPECT_LT(elapsed, 30000);
  22460. }
  22461. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  22462. Server svr;
  22463. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  22464. if (!req.has_header("Authorization")) {
  22465. res.status = StatusCode::Unauthorized_401;
  22466. res.set_content("Unauthorized", "text/plain");
  22467. return Server::HandlerResponse::Handled;
  22468. }
  22469. return Server::HandlerResponse::Unhandled;
  22470. });
  22471. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22472. std::string msg;
  22473. while (ws.read(msg)) {
  22474. ws.send(msg);
  22475. }
  22476. });
  22477. auto port = svr.bind_to_any_port("localhost");
  22478. std::thread t([&]() { svr.listen_after_bind(); });
  22479. svr.wait_until_ready();
  22480. // Without Authorization header - should be rejected before upgrade
  22481. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  22482. EXPECT_FALSE(client1.connect());
  22483. // The rejection is framed like any other HTTP response
  22484. {
  22485. Client cli("localhost", port);
  22486. Headers headers = {{"Upgrade", "websocket"},
  22487. {"Connection", "Upgrade"},
  22488. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22489. {"Sec-WebSocket-Version", "13"}};
  22490. auto res = cli.Get("/ws", headers);
  22491. ASSERT_TRUE(res);
  22492. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22493. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22494. EXPECT_EQ("Unauthorized", res->body);
  22495. }
  22496. // With Authorization header - should succeed
  22497. Headers headers = {{"Authorization", "Bearer token123"}};
  22498. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  22499. headers);
  22500. ASSERT_TRUE(client2.connect());
  22501. ASSERT_TRUE(client2.send("hello"));
  22502. std::string msg;
  22503. ASSERT_TRUE(client2.read(msg));
  22504. EXPECT_EQ("hello", msg);
  22505. client2.close();
  22506. svr.stop();
  22507. t.join();
  22508. }
  22509. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  22510. Server svr;
  22511. std::atomic<int> pre_request_calls{0};
  22512. std::atomic<bool> route_matched{false};
  22513. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  22514. pre_request_calls++;
  22515. if (req.matched_route == "/ws/:id") { route_matched = true; }
  22516. if (req.get_header_value("Authorization") != "Bearer token123") {
  22517. res.status = StatusCode::Unauthorized_401;
  22518. res.set_content("Unauthorized", "text/plain");
  22519. return Server::HandlerResponse::Handled;
  22520. }
  22521. return Server::HandlerResponse::Unhandled;
  22522. });
  22523. std::atomic<bool> handler_called{false};
  22524. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  22525. handler_called = true;
  22526. ws.send(req.matched_route + " " + req.path_params.at("id"));
  22527. });
  22528. auto port = svr.bind_to_any_port("localhost");
  22529. std::thread t([&]() { svr.listen_after_bind(); });
  22530. svr.wait_until_ready();
  22531. // Without Authorization header - should be rejected before upgrade
  22532. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  22533. "/ws/1");
  22534. EXPECT_FALSE(client1.connect());
  22535. EXPECT_FALSE(handler_called);
  22536. EXPECT_EQ(1, pre_request_calls);
  22537. EXPECT_TRUE(route_matched);
  22538. // The rejection is an ordinary HTTP response, not a protocol switch
  22539. {
  22540. Client cli("localhost", port);
  22541. Headers headers = {{"Upgrade", "websocket"},
  22542. {"Connection", "Upgrade"},
  22543. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22544. {"Sec-WebSocket-Version", "13"}};
  22545. auto res = cli.Get("/ws/1", headers);
  22546. ASSERT_TRUE(res);
  22547. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22548. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22549. EXPECT_EQ("Unauthorized", res->body);
  22550. }
  22551. EXPECT_FALSE(handler_called);
  22552. // With Authorization header - should succeed
  22553. Headers headers = {{"Authorization", "Bearer token123"}};
  22554. ws::WebSocketClient client2(
  22555. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  22556. ASSERT_TRUE(client2.connect());
  22557. std::string msg;
  22558. ASSERT_TRUE(client2.read(msg));
  22559. EXPECT_EQ("/ws/:id 2", msg);
  22560. EXPECT_TRUE(handler_called);
  22561. client2.close();
  22562. svr.stop();
  22563. t.join();
  22564. }
  22565. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  22566. Server svr;
  22567. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22568. // A read timeout is how a handler gets control back. Without it, a handler
  22569. // parked in read() can never write on the connection it is reading.
  22570. ws.set_read_timeout(std::chrono::milliseconds(100));
  22571. std::string msg;
  22572. while (ws.is_open()) {
  22573. auto r = ws.read(msg);
  22574. if (r == httplib::ws::Timeout) {
  22575. ws.send("tick");
  22576. continue;
  22577. }
  22578. if (r == httplib::ws::Fail) { break; }
  22579. ws.send(msg);
  22580. }
  22581. });
  22582. auto port = svr.bind_to_any_port("localhost");
  22583. std::thread t([&]() { svr.listen_after_bind(); });
  22584. svr.wait_until_ready();
  22585. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22586. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  22587. ASSERT_TRUE(client.connect());
  22588. // The client sends nothing, so anything it receives came out of the
  22589. // handler's timeout path.
  22590. std::string msg;
  22591. ASSERT_EQ(client.read(msg), ws::Text);
  22592. EXPECT_EQ("tick", msg);
  22593. client.close();
  22594. svr.stop();
  22595. t.join();
  22596. }
  22597. // Stream::read may return fewer bytes than asked for. This is that contract at
  22598. // its worst -- one byte per call -- which is what a frame header straddling a
  22599. // read buffer's boundary looks like to the frame parser.
  22600. class WsByteAtATimeStream : public Stream {
  22601. public:
  22602. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  22603. bool is_readable() const override { return true; }
  22604. bool wait_readable() const override { return true; }
  22605. bool wait_writable() const override { return true; }
  22606. ssize_t read(char *ptr, size_t size) override {
  22607. if (size == 0 || pos_ >= data_.size()) { return 0; }
  22608. *ptr = data_[pos_++];
  22609. return 1;
  22610. }
  22611. ssize_t write(const char *, size_t size) override {
  22612. return static_cast<ssize_t>(size);
  22613. }
  22614. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  22615. ip = "127.0.0.1";
  22616. port = 0;
  22617. }
  22618. void get_local_ip_and_port(std::string &ip, int &port) const override {
  22619. ip = "127.0.0.1";
  22620. port = 0;
  22621. }
  22622. socket_t socket() const override { return INVALID_SOCKET; }
  22623. time_t duration() const override { return 0; }
  22624. private:
  22625. std::string data_;
  22626. size_t pos_ = 0;
  22627. };
  22628. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  22629. // The payload uses the 16-bit extended length, so the header, the length
  22630. // and the mask key are all multi-byte fields here. Each used to be read
  22631. // with a single read() call, which fails as soon as one is split. The
  22632. // payload is also a little over one read chunk, so it is read in two.
  22633. std::string body;
  22634. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  22635. body += static_cast<char>(i % 251);
  22636. }
  22637. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  22638. std::string frame;
  22639. frame += static_cast<char>(0x81); // FIN + Text
  22640. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  22641. frame += static_cast<char>(body.size() >> 8);
  22642. frame += static_cast<char>(body.size() & 0xff);
  22643. for (size_t i = 0; i < 4; i++) {
  22644. frame += static_cast<char>(mask[i]);
  22645. }
  22646. for (size_t i = 0; i < body.size(); i++) {
  22647. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  22648. }
  22649. WsByteAtATimeStream strm(frame);
  22650. ws::Opcode opcode;
  22651. std::string payload;
  22652. bool fin = false;
  22653. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  22654. /*expect_masked=*/true, body.size()),
  22655. ws::impl::FrameRead::Ok);
  22656. EXPECT_TRUE(fin);
  22657. EXPECT_EQ(opcode, ws::Opcode::Text);
  22658. EXPECT_EQ(payload, body);
  22659. }
  22660. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  22661. std::string body(2000, 'x');
  22662. std::string frame;
  22663. frame += static_cast<char>(0x82); // FIN + Binary
  22664. frame += static_cast<char>(126); // 16-bit length follows
  22665. frame += static_cast<char>(body.size() >> 8);
  22666. frame += static_cast<char>(body.size() & 0xff);
  22667. frame += body;
  22668. detail::BufferStream strm;
  22669. strm.write(frame.data(), frame.size());
  22670. ws::Opcode opcode;
  22671. std::string payload;
  22672. bool fin;
  22673. EXPECT_EQ(
  22674. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  22675. ws::impl::FrameRead::Ok);
  22676. EXPECT_EQ(body, payload);
  22677. }
  22678. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  22679. // The header announces the largest payload allowed, and only 3 bytes of it
  22680. // ever arrive.
  22681. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  22682. std::string frame;
  22683. frame += static_cast<char>(0x82); // FIN + Binary
  22684. frame += static_cast<char>(127); // 64-bit length follows
  22685. for (int shift = 56; shift >= 0; shift -= 8) {
  22686. frame += static_cast<char>((len >> shift) & 0xff);
  22687. }
  22688. frame += "abc";
  22689. detail::BufferStream strm;
  22690. strm.write(frame.data(), frame.size());
  22691. ws::Opcode opcode;
  22692. std::string payload;
  22693. bool fin;
  22694. EXPECT_EQ(
  22695. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  22696. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  22697. ws::impl::FrameRead::Fail);
  22698. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  22699. }
  22700. TEST(WebSocketTest, QueryStringInHandshake) {
  22701. Server svr;
  22702. std::mutex mtx;
  22703. std::string received_target;
  22704. std::string received_token;
  22705. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22706. {
  22707. std::lock_guard<std::mutex> lock(mtx);
  22708. received_target = req.target;
  22709. if (req.has_param("token")) {
  22710. received_token = req.get_param_value("token");
  22711. }
  22712. }
  22713. std::string msg;
  22714. while (ws.read(msg)) {
  22715. ws.send(msg);
  22716. }
  22717. });
  22718. auto port = svr.bind_to_any_port("localhost");
  22719. std::thread t([&]() { svr.listen_after_bind(); });
  22720. svr.wait_until_ready();
  22721. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  22722. "/ws?token=ABC&session=123");
  22723. ASSERT_TRUE(client.connect());
  22724. // Round-trip ensures the handler has run and captured the request.
  22725. ASSERT_TRUE(client.send("hello"));
  22726. std::string msg;
  22727. ASSERT_TRUE(client.read(msg));
  22728. EXPECT_EQ("hello", msg);
  22729. client.close();
  22730. {
  22731. std::lock_guard<std::mutex> lock(mtx);
  22732. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  22733. EXPECT_EQ("ABC", received_token);
  22734. }
  22735. svr.stop();
  22736. t.join();
  22737. }
  22738. // Run a handshake against a throwaway server and hand the request the server
  22739. // received back to the caller, so tests can assert on the headers the client
  22740. // actually put on the wire.
  22741. static void capture_websocket_handshake_request(
  22742. const Headers &client_headers,
  22743. std::function<void(const Request &, int port)> verify) {
  22744. Server svr;
  22745. std::mutex mtx;
  22746. Request received;
  22747. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22748. {
  22749. std::lock_guard<std::mutex> lock(mtx);
  22750. received = req;
  22751. }
  22752. std::string msg;
  22753. while (ws.read(msg)) {
  22754. ws.send(msg);
  22755. }
  22756. });
  22757. auto port = svr.bind_to_any_port("localhost");
  22758. std::thread t([&]() { svr.listen_after_bind(); });
  22759. auto se = detail::scope_exit([&] {
  22760. svr.stop();
  22761. t.join();
  22762. });
  22763. svr.wait_until_ready();
  22764. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  22765. client_headers);
  22766. ASSERT_TRUE(client.connect());
  22767. ASSERT_TRUE(client.send("hello"));
  22768. std::string msg;
  22769. ASSERT_TRUE(client.read(msg));
  22770. client.close();
  22771. {
  22772. std::lock_guard<std::mutex> lock(mtx);
  22773. verify(received, port);
  22774. }
  22775. }
  22776. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  22777. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  22778. // Non-default port must be present in the Host header. Default ports
  22779. // (80/443) are omitted; that logic is covered by
  22780. // MakeHostAndPortStringTest.
  22781. EXPECT_EQ("localhost:" + std::to_string(port),
  22782. req.get_header_value("Host"));
  22783. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  22784. req.get_header_value("User-Agent"));
  22785. EXPECT_FALSE(req.has_header("Accept"));
  22786. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  22787. EXPECT_FALSE(req.has_header("Content-Length"));
  22788. });
  22789. }
  22790. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  22791. capture_websocket_handshake_request(
  22792. {{"Host", "example.com"},
  22793. {"User-Agent", "custom-agent"},
  22794. {"X-Custom", "value"}},
  22795. [](const Request &req, int) {
  22796. EXPECT_EQ("example.com", req.get_header_value("Host"));
  22797. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  22798. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  22799. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  22800. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  22801. });
  22802. }
  22803. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  22804. capture_websocket_handshake_request(
  22805. {{"Upgrade", "bogus"},
  22806. {"Connection", "close"},
  22807. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  22808. {"Sec-WebSocket-Version", "8"}},
  22809. [](const Request &req, int) {
  22810. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  22811. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  22812. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  22813. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  22814. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  22815. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  22816. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  22817. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  22818. req.get_header_value("Sec-WebSocket-Key"));
  22819. });
  22820. }
  22821. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  22822. // A header the client refuses to send must abort the handshake before any
  22823. // part of it reaches the wire; a lone request line would otherwise sit in
  22824. // the peer's buffer as a truncated request.
  22825. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  22826. ASSERT_NE(INVALID_SOCKET, srv);
  22827. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  22828. sockaddr_in addr{};
  22829. addr.sin_family = AF_INET;
  22830. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  22831. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22832. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  22833. ASSERT_EQ(0, ::listen(srv, 1));
  22834. sockaddr_in bound{};
  22835. socklen_t bound_len = sizeof(bound);
  22836. ASSERT_EQ(
  22837. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  22838. auto port = ntohs(bound.sin_port);
  22839. ssize_t received = -1;
  22840. std::thread t([&] {
  22841. // Bound every blocking call so a regression fails the test with a bad
  22842. // value instead of hanging the suite.
  22843. fd_set rfds;
  22844. FD_ZERO(&rfds);
  22845. FD_SET(srv, &rfds);
  22846. timeval tv{5, 0};
  22847. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  22848. 0) {
  22849. return;
  22850. }
  22851. sockaddr_in cli_addr{};
  22852. socklen_t cli_len = sizeof(cli_addr);
  22853. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  22854. if (cli == INVALID_SOCKET) { return; }
  22855. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  22856. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22857. char buf[4096];
  22858. received = ::recv(cli, buf, sizeof(buf), 0);
  22859. });
  22860. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  22861. // connect() has already shut the socket down by the time it returns false,
  22862. // so the peer sees EOF without waiting for the client to be destroyed.
  22863. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  22864. {{"X-Bad", "a\r\nInjected: 1"}});
  22865. EXPECT_FALSE(client.connect());
  22866. t.join();
  22867. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  22868. EXPECT_EQ(0, received);
  22869. }
  22870. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  22871. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  22872. // contains "upgrade" as a substring is a different token and must not
  22873. // start a WebSocket handshake.
  22874. auto make_request = [](const std::vector<std::string> &connection_values) {
  22875. Request req;
  22876. req.method = "GET";
  22877. req.headers.emplace("Upgrade", "websocket");
  22878. for (const auto &value : connection_values) {
  22879. req.headers.emplace("Connection", value);
  22880. }
  22881. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22882. req.headers.emplace("Sec-WebSocket-Version", "13");
  22883. return req;
  22884. };
  22885. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  22886. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  22887. EXPECT_TRUE(
  22888. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  22889. EXPECT_TRUE(
  22890. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  22891. EXPECT_TRUE(
  22892. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  22893. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  22894. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  22895. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  22896. EXPECT_FALSE(
  22897. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  22898. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  22899. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22900. }
  22901. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  22902. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  22903. // asks recipients to match each protocol-name case-insensitively, and RFC
  22904. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  22905. // client naming websocket alongside another protocol, or on a second field
  22906. // line, is offering websocket; a value that merely contains "websocket" as a
  22907. // substring is a different protocol name and is not.
  22908. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  22909. Request req;
  22910. req.method = "GET";
  22911. for (const auto &value : upgrade_values) {
  22912. req.headers.emplace("Upgrade", value);
  22913. }
  22914. req.headers.emplace("Connection", "Upgrade");
  22915. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22916. req.headers.emplace("Sec-WebSocket-Version", "13");
  22917. return req;
  22918. };
  22919. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  22920. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  22921. EXPECT_TRUE(
  22922. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  22923. EXPECT_TRUE(
  22924. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  22925. EXPECT_TRUE(
  22926. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  22927. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  22928. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  22929. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  22930. EXPECT_FALSE(
  22931. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  22932. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  22933. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22934. }
  22935. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  22936. Server svr;
  22937. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  22938. auto port = svr.bind_to_any_port("localhost");
  22939. std::thread t([&]() { svr.listen_after_bind(); });
  22940. auto se = detail::scope_exit([&] {
  22941. svr.stop();
  22942. t.join();
  22943. });
  22944. svr.wait_until_ready();
  22945. Headers headers = {{"Upgrade", "websocket"},
  22946. {"Connection", "notupgrade"},
  22947. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22948. {"Sec-WebSocket-Version", "13"}};
  22949. Client cli("localhost", port);
  22950. auto res = cli.Get("/ws", headers);
  22951. // The route exists only as a WebSocket route, so a request that fails the
  22952. // handshake check falls through to ordinary routing.
  22953. ASSERT_TRUE(res);
  22954. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  22955. }
  22956. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  22957. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  22958. // Connection value is the only thing left for the client to reject.
  22959. Server svr;
  22960. svr.Get("/ws", [](const Request &req, Response &res) {
  22961. res.status = StatusCode::SwitchingProtocol_101;
  22962. res.set_header("Upgrade", "websocket");
  22963. res.set_header("Connection", "notupgrade");
  22964. res.set_header("Sec-WebSocket-Accept",
  22965. detail::websocket_accept_key(
  22966. req.get_header_value("Sec-WebSocket-Key")));
  22967. });
  22968. auto port = svr.bind_to_any_port("localhost");
  22969. std::thread t([&]() { svr.listen_after_bind(); });
  22970. auto se = detail::scope_exit([&] {
  22971. svr.stop();
  22972. t.join();
  22973. });
  22974. svr.wait_until_ready();
  22975. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22976. auto res = client.connect();
  22977. EXPECT_FALSE(res);
  22978. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22979. EXPECT_FALSE(client.is_open());
  22980. }
  22981. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  22982. Server svr;
  22983. svr.Get("/ws", [](const Request &req, Response &res) {
  22984. res.status = StatusCode::SwitchingProtocol_101;
  22985. res.set_header("Upgrade", "websocket");
  22986. res.set_header("Connection", "Upgrade");
  22987. res.set_header("Sec-WebSocket-Accept",
  22988. detail::websocket_accept_key(
  22989. req.get_header_value("Sec-WebSocket-Key")));
  22990. res.set_header("Sec-WebSocket-Protocol", "admin");
  22991. });
  22992. auto port = svr.bind_to_any_port("localhost");
  22993. std::thread t([&]() { svr.listen_after_bind(); });
  22994. auto se = detail::scope_exit([&] {
  22995. svr.stop();
  22996. t.join();
  22997. });
  22998. svr.wait_until_ready();
  22999. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  23000. // Server selects a subprotocol the client never offered
  23001. {
  23002. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23003. ws::WebSocketClient client(url, headers);
  23004. auto res = client.connect();
  23005. EXPECT_FALSE(res);
  23006. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23007. EXPECT_FALSE(client.is_open());
  23008. EXPECT_TRUE(client.subprotocol().empty());
  23009. }
  23010. // Client offered none but the server named one anyway
  23011. {
  23012. ws::WebSocketClient client(url);
  23013. auto res = client.connect();
  23014. EXPECT_FALSE(res);
  23015. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23016. EXPECT_FALSE(client.is_open());
  23017. EXPECT_TRUE(client.subprotocol().empty());
  23018. }
  23019. }
  23020. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  23021. // The socket path doubles as the URL host, so it must not contain '/'.
  23022. const char *shard = getenv("GTEST_SHARD_INDEX");
  23023. const std::string sock_path =
  23024. shard ? std::string("httplib-ws-") + shard + ".sock"
  23025. : std::string("httplib-ws.sock");
  23026. std::remove(sock_path.c_str());
  23027. Server svr;
  23028. std::mutex mtx;
  23029. std::string received_host;
  23030. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23031. {
  23032. std::lock_guard<std::mutex> lock(mtx);
  23033. received_host = req.get_header_value("Host");
  23034. }
  23035. std::string msg;
  23036. while (ws.read(msg)) {
  23037. ws.send(msg);
  23038. }
  23039. });
  23040. svr.set_address_family(AF_UNIX);
  23041. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  23042. auto se = detail::scope_exit([&] {
  23043. svr.stop();
  23044. t.join();
  23045. std::remove(sock_path.c_str());
  23046. });
  23047. svr.wait_until_ready();
  23048. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  23049. client.set_address_family(AF_UNIX);
  23050. ASSERT_TRUE(client.connect());
  23051. ASSERT_TRUE(client.send("hello"));
  23052. std::string msg;
  23053. ASSERT_TRUE(client.read(msg));
  23054. client.close();
  23055. {
  23056. std::lock_guard<std::mutex> lock(mtx);
  23057. // There is no host:port for a Unix socket, so the same "localhost"
  23058. // placeholder the HTTP client uses is expected.
  23059. EXPECT_EQ("localhost", received_host);
  23060. }
  23061. }
  23062. // Two threads must never parse WebSocket frames from the same stream.
  23063. // close() used to read the peer's Close reply with its own frame read, so it
  23064. // raced a reader thread that was in the middle of a payload: the payload loop
  23065. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  23066. // so bytes taken by close() were replaced with bytes from further along the
  23067. // stream. The message kept its length and silently changed content.
  23068. //
  23069. // The raw peer below sends a frame header plus part of the payload, waits for
  23070. // the handler to call close(), and only then sends the rest. Whichever thread
  23071. // would win the race for those bytes, the message must arrive intact, because
  23072. // close() must not touch the stream while read() owns it.
  23073. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  23074. #ifndef _WIN32
  23075. signal(SIGPIPE, SIG_IGN);
  23076. #endif
  23077. const size_t payload_len = 120; // fits the 7-bit length field
  23078. const size_t prefix_len = 8;
  23079. const int attempts = 8;
  23080. std::string expected(payload_len, '\0');
  23081. for (size_t i = 0; i < payload_len; i++) {
  23082. expected[i] = static_cast<char>('a' + i % 26);
  23083. }
  23084. std::atomic<bool> peer_stalled{false};
  23085. std::atomic<bool> handler_done{false};
  23086. std::mutex received_mutex;
  23087. std::vector<std::string> received;
  23088. // Bound every wait, so a regression fails the test instead of hanging the
  23089. // suite.
  23090. auto wait_for = [](const std::atomic<bool> &flag) {
  23091. for (int i = 0; i < 500 && !flag; i++) {
  23092. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23093. }
  23094. };
  23095. Server svr;
  23096. svr.set_websocket_ping_interval(0);
  23097. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23098. std::thread reader([&]() {
  23099. std::string msg;
  23100. while (ws.read(msg)) {
  23101. std::lock_guard<std::mutex> guard(received_mutex);
  23102. received.push_back(msg);
  23103. }
  23104. });
  23105. // Wait until the peer stalls mid-payload, so the reader thread is parked
  23106. // inside read_websocket_frame() when close() runs.
  23107. wait_for(peer_stalled);
  23108. ws.close();
  23109. reader.join();
  23110. handler_done = true;
  23111. });
  23112. auto port = svr.bind_to_any_port("127.0.0.1");
  23113. std::thread t([&]() { svr.listen_after_bind(); });
  23114. auto se = detail::scope_exit([&] {
  23115. svr.stop();
  23116. t.join();
  23117. });
  23118. svr.wait_until_ready();
  23119. auto send_bytes = [](socket_t s, const std::string &data) {
  23120. #ifdef _WIN32
  23121. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  23122. #else
  23123. auto n = ::send(s, data.data(), data.size(), 0);
  23124. #endif
  23125. return n == static_cast<decltype(n)>(data.size());
  23126. };
  23127. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  23128. // Every length used here fits the 7-bit length field.
  23129. auto masked_header = [](uint8_t first_byte, size_t len) {
  23130. std::string h;
  23131. h += static_cast<char>(first_byte);
  23132. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  23133. h.append(4, '\0'); // mask key
  23134. return h;
  23135. };
  23136. for (int attempt = 0; attempt < attempts; attempt++) {
  23137. peer_stalled = false;
  23138. handler_done = false;
  23139. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23140. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  23141. auto se_sock = detail::scope_exit([&] {
  23142. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  23143. });
  23144. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23145. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  23146. sockaddr_in addr{};
  23147. addr.sin_family = AF_INET;
  23148. addr.sin_port = htons(static_cast<uint16_t>(port));
  23149. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23150. ASSERT_EQ(
  23151. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  23152. << "attempt " << attempt;
  23153. ASSERT_TRUE(send_bytes(sock,
  23154. "GET /ws HTTP/1.1\r\n"
  23155. "Host: 127.0.0.1\r\n"
  23156. "Upgrade: websocket\r\n"
  23157. "Connection: Upgrade\r\n"
  23158. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23159. "Sec-WebSocket-Version: 13\r\n"
  23160. "\r\n"))
  23161. << "attempt " << attempt;
  23162. std::string response;
  23163. while (response.find("\r\n\r\n") == std::string::npos) {
  23164. char buf[512];
  23165. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  23166. if (n <= 0) { break; }
  23167. response.append(buf, static_cast<size_t>(n));
  23168. }
  23169. ASSERT_NE(std::string::npos, response.find(" 101 "))
  23170. << "attempt " << attempt;
  23171. // Send the header of a Binary message but only the first prefix_len bytes
  23172. // of its payload, leaving the reader thread stalled inside the payload.
  23173. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  23174. expected.substr(0, prefix_len)))
  23175. << "attempt " << attempt;
  23176. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23177. peer_stalled = true;
  23178. // Let close() send its Close frame and park in its own read before the
  23179. // rest of the payload arrives, so both threads are waiting for it.
  23180. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23181. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  23182. close_frame += static_cast<char>(0x03); // status 1000
  23183. close_frame += static_cast<char>(0xE8);
  23184. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  23185. << "attempt " << attempt;
  23186. // Closing the peer releases the reader thread even on the buggy path,
  23187. // where it waits for bytes another thread already consumed.
  23188. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23189. detail::close_socket(sock);
  23190. sock = INVALID_SOCKET;
  23191. wait_for(handler_done);
  23192. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  23193. }
  23194. std::lock_guard<std::mutex> guard(received_mutex);
  23195. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  23196. << "a message in flight when close() ran was dropped";
  23197. for (size_t i = 0; i < received.size(); i++) {
  23198. EXPECT_EQ(expected, received[i]) << "message " << i;
  23199. }
  23200. }
  23201. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  23202. // returning the socket, or INVALID_SOCKET.
  23203. static socket_t connect_raw_websocket(int port, const std::string &path) {
  23204. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23205. if (sock == INVALID_SOCKET) { return sock; }
  23206. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23207. sockaddr_in addr{};
  23208. addr.sin_family = AF_INET;
  23209. addr.sin_port = htons(static_cast<uint16_t>(port));
  23210. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23211. std::string req = "GET " + path +
  23212. " HTTP/1.1\r\n"
  23213. "Host: 127.0.0.1\r\n"
  23214. "Upgrade: websocket\r\n"
  23215. "Connection: Upgrade\r\n"
  23216. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23217. "Sec-WebSocket-Version: 13\r\n"
  23218. "\r\n";
  23219. std::string res;
  23220. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  23221. ::send(sock, req.data(), static_cast<int>(req.size()), 0) ==
  23222. static_cast<int>(req.size())) {
  23223. char c;
  23224. while (res.find("\r\n\r\n") == std::string::npos &&
  23225. ::recv(sock, &c, 1, 0) == 1) {
  23226. res += c;
  23227. }
  23228. }
  23229. if (res.find(" 101 ") == std::string::npos) {
  23230. detail::close_socket(sock);
  23231. return INVALID_SOCKET;
  23232. }
  23233. return sock;
  23234. }
  23235. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  23236. // The payload must fit the 7-bit length field.
  23237. static std::string masked_frame(uint8_t first_byte,
  23238. const std::string &payload) {
  23239. std::string f;
  23240. f += static_cast<char>(first_byte);
  23241. f += static_cast<char>(0x80 | payload.size());
  23242. f.append(4, '\0');
  23243. return f + payload;
  23244. }
  23245. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  23246. std::atomic<bool> done{false};
  23247. std::string received;
  23248. Server svr;
  23249. svr.set_websocket_ping_interval(0);
  23250. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23251. std::string msg;
  23252. if (ws.read(msg) == ws::Binary) { received = msg; }
  23253. done = true;
  23254. });
  23255. auto port = svr.bind_to_any_port("127.0.0.1");
  23256. std::thread t([&]() { svr.listen_after_bind(); });
  23257. auto se = detail::scope_exit([&] {
  23258. svr.stop();
  23259. t.join();
  23260. });
  23261. svr.wait_until_ready();
  23262. auto sock = connect_raw_websocket(port, "/ws");
  23263. ASSERT_NE(INVALID_SOCKET, sock);
  23264. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23265. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  23266. masked_frame(0x89, "p") + // FIN + Ping
  23267. masked_frame(0x80, "lo"); // FIN + Continuation
  23268. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23269. for (int i = 0; i < 500 && !done; i++) {
  23270. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23271. }
  23272. ASSERT_TRUE(done);
  23273. EXPECT_EQ("Hello", received);
  23274. // The Ping between the fragments is answered with a Pong.
  23275. char pong[3];
  23276. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  23277. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  23278. }
  23279. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  23280. Server svr;
  23281. svr.set_websocket_ping_interval(-1);
  23282. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23283. std::string msg;
  23284. while (ws.read(msg)) {}
  23285. });
  23286. auto port = svr.bind_to_any_port("127.0.0.1");
  23287. std::thread t([&]() { svr.listen_after_bind(); });
  23288. auto se = detail::scope_exit([&] {
  23289. svr.stop();
  23290. t.join();
  23291. });
  23292. svr.wait_until_ready();
  23293. auto sock = connect_raw_websocket(port, "/ws");
  23294. ASSERT_NE(INVALID_SOCKET, sock);
  23295. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23296. // Nothing comes while the client stays quiet.
  23297. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  23298. char c;
  23299. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  23300. }
  23301. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  23302. Server svr;
  23303. svr.set_websocket_ping_interval(0);
  23304. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23305. std::string msg;
  23306. while (ws.read(msg)) {}
  23307. });
  23308. auto port = svr.bind_to_any_port("127.0.0.1");
  23309. std::thread t([&]() { svr.listen_after_bind(); });
  23310. auto se = detail::scope_exit([&] {
  23311. svr.stop();
  23312. t.join();
  23313. });
  23314. svr.wait_until_ready();
  23315. // Each Close payload and the reply it should get: an echo when valid, 1002
  23316. // otherwise.
  23317. std::vector<std::pair<std::string, std::string>> cases = {
  23318. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  23319. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  23320. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  23321. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  23322. };
  23323. // Also between the fragments of a message.
  23324. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  23325. for (const auto &c : cases) {
  23326. auto sock = connect_raw_websocket(port, "/ws");
  23327. ASSERT_NE(INVALID_SOCKET, sock);
  23328. auto frames = prefix + masked_frame(0x88, c.first);
  23329. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23330. std::string reply;
  23331. char buf[256];
  23332. while (reply.size() < 2 + c.second.size()) {
  23333. auto n = ::recv(sock, buf, sizeof(buf), 0);
  23334. if (n <= 0) { break; }
  23335. reply.append(buf, static_cast<size_t>(n));
  23336. }
  23337. detail::close_socket(sock);
  23338. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  23339. c.second,
  23340. reply);
  23341. }
  23342. }
  23343. }
  23344. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23345. class WebSocketSSLIntegrationTest : public ::testing::Test {
  23346. protected:
  23347. void SetUp() override {
  23348. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  23349. SERVER_PRIVATE_KEY_FILE);
  23350. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23351. std::string msg;
  23352. ws::ReadResult ret;
  23353. while ((ret = ws.read(msg))) {
  23354. if (ret == ws::Binary) {
  23355. ws.send(msg.data(), msg.size());
  23356. } else {
  23357. ws.send(msg);
  23358. }
  23359. }
  23360. });
  23361. port_ = server_->bind_to_any_port(HOST);
  23362. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23363. server_->wait_until_ready();
  23364. }
  23365. void TearDown() override {
  23366. server_->stop();
  23367. if (server_thread_.joinable()) { server_thread_.join(); }
  23368. }
  23369. std::unique_ptr<SSLServer> server_;
  23370. std::thread server_thread_;
  23371. int port_ = 0;
  23372. };
  23373. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  23374. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23375. {
  23376. ws::WebSocketClient client(url);
  23377. client.enable_server_certificate_verification(false);
  23378. auto calls = 0;
  23379. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  23380. calls++;
  23381. return false;
  23382. });
  23383. EXPECT_FALSE(client.connect());
  23384. EXPECT_GT(calls, 0);
  23385. }
  23386. {
  23387. ws::WebSocketClient client(url);
  23388. client.enable_server_certificate_verification(false);
  23389. client.set_session_verifier([](tls::session_t) {
  23390. return SSLVerifierResponse::CertificateRejected;
  23391. });
  23392. EXPECT_FALSE(client.connect());
  23393. }
  23394. {
  23395. ws::WebSocketClient client(url);
  23396. client.enable_server_certificate_verification(false);
  23397. client.set_session_verifier([](tls::session_t) {
  23398. return SSLVerifierResponse::CertificateAccepted;
  23399. });
  23400. EXPECT_TRUE(client.connect());
  23401. }
  23402. }
  23403. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  23404. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23405. "/ws-echo");
  23406. client.enable_server_certificate_verification(false);
  23407. ASSERT_TRUE(client.connect());
  23408. ASSERT_TRUE(client.is_open());
  23409. ASSERT_TRUE(client.send("Hello WSS"));
  23410. std::string msg;
  23411. EXPECT_EQ(ws::Text, client.read(msg));
  23412. EXPECT_EQ("Hello WSS", msg);
  23413. client.close();
  23414. }
  23415. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  23416. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  23417. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  23418. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  23419. // client (without calling close() first) is the only path that runs
  23420. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  23421. // bug exactly.
  23422. //
  23423. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  23424. // when linked against an instrumented libssl; run under Valgrind to catch it
  23425. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  23426. // suite (the freed session otherwise stalls on the close handshake) — this test
  23427. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  23428. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  23429. {
  23430. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23431. "/ws-echo");
  23432. client.enable_server_certificate_verification(false);
  23433. client.set_read_timeout(2, 0);
  23434. client.set_write_timeout(2, 0);
  23435. ASSERT_TRUE(client.connect());
  23436. ASSERT_TRUE(client.is_open());
  23437. ASSERT_TRUE(client.send("still open"));
  23438. // Intentionally do NOT call client.close(): leaving scope runs
  23439. // shutdown_and_close() with the WebSocket still open, which must send the
  23440. // close frame while the TLS session is still alive.
  23441. }
  23442. }
  23443. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  23444. // shutdown_and_close() at the start of connect(), reproducing the same
  23445. // use-after-free within the test body rather than at scope exit. The second
  23446. // connect must succeed and echo, proving the close handshake ran over a live
  23447. // session. See the note above about memory-tool requirements.
  23448. TEST_F(WebSocketSSLIntegrationTest,
  23449. ReconnectWhileOpenSendsCloseOverLiveSession) {
  23450. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23451. "/ws-echo");
  23452. client.enable_server_certificate_verification(false);
  23453. client.set_read_timeout(2, 0);
  23454. client.set_write_timeout(2, 0);
  23455. ASSERT_TRUE(client.connect());
  23456. ASSERT_TRUE(client.is_open());
  23457. ASSERT_TRUE(client.send("still open"));
  23458. // Reconnect without closing first: connect() calls shutdown_and_close() on
  23459. // the still-open connection, which must not touch a freed TLS session.
  23460. ASSERT_TRUE(client.connect());
  23461. ASSERT_TRUE(client.is_open());
  23462. ASSERT_TRUE(client.send("after reconnect"));
  23463. std::string msg;
  23464. EXPECT_EQ(ws::Text, client.read(msg));
  23465. EXPECT_EQ("after reconnect", msg);
  23466. client.close();
  23467. }
  23468. #endif
  23469. #ifdef CPPHTTPLIB_SSL_ENABLED
  23470. class WebSocketSSLCATest : public ::testing::Test {
  23471. protected:
  23472. void SetUp() override {
  23473. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  23474. SERVER_PRIVATE_KEY_FILE);
  23475. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23476. std::string msg;
  23477. while (ws.read(msg)) {
  23478. ws.send(msg);
  23479. }
  23480. });
  23481. port_ = server_->bind_to_any_port("127.0.0.1");
  23482. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23483. server_->wait_until_ready();
  23484. }
  23485. void TearDown() override {
  23486. server_->stop();
  23487. if (server_thread_.joinable()) { server_thread_.join(); }
  23488. }
  23489. std::string url() const {
  23490. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  23491. }
  23492. std::unique_ptr<SSLServer> server_;
  23493. std::thread server_thread_;
  23494. int port_ = 0;
  23495. };
  23496. // A custom CA loaded as PEM verifies the server with full certificate
  23497. // verification enabled
  23498. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  23499. ws::WebSocketClient client(url());
  23500. std::string cert;
  23501. read_file(SERVER_CERT2_FILE, cert);
  23502. client.load_ca_cert_store(cert.c_str(), cert.size());
  23503. ASSERT_TRUE(client.connect());
  23504. ASSERT_TRUE(client.send("hello"));
  23505. std::string msg;
  23506. EXPECT_EQ(ws::Text, client.read(msg));
  23507. EXPECT_EQ("hello", msg);
  23508. client.close();
  23509. }
  23510. // A custom CA that does not cover the server must fail verification (the
  23511. // custom CA is exclusive; system certs are not loaded alongside it)
  23512. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  23513. ws::WebSocketClient client(url());
  23514. std::string cert;
  23515. read_file(CLIENT_CA_CERT_FILE, cert);
  23516. client.load_ca_cert_store(cert.c_str(), cert.size());
  23517. auto res = client.connect();
  23518. ASSERT_FALSE(res);
  23519. EXPECT_EQ(Error::SSLServerVerification, res.error());
  23520. EXPECT_EQ(-1, res.status());
  23521. EXPECT_NE(0u, res.ssl_backend_error());
  23522. }
  23523. // The same CA as a file path rather than PEM in memory
  23524. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  23525. ws::WebSocketClient client(url());
  23526. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23527. ASSERT_TRUE(client.connect());
  23528. ASSERT_TRUE(client.send("hello"));
  23529. std::string msg;
  23530. EXPECT_EQ(ws::Text, client.read(msg));
  23531. EXPECT_EQ("hello", msg);
  23532. client.close();
  23533. }
  23534. // ...and a CA file that does not cover the server still fails, so it is the
  23535. // path above that decides the outcome
  23536. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  23537. ws::WebSocketClient client(url());
  23538. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23539. ASSERT_FALSE(client.connect());
  23540. }
  23541. // Regression test: reconnecting with a native custom CA store used to reuse
  23542. // a store handle the previous TLS context had already freed (use-after-free
  23543. // under the OpenSSL backend). The context now lives as long as the client.
  23544. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  23545. ws::WebSocketClient client(url());
  23546. std::string cert;
  23547. read_file(SERVER_CERT2_FILE, cert);
  23548. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  23549. ASSERT_TRUE(client.connect());
  23550. client.close();
  23551. ASSERT_TRUE(client.connect());
  23552. ASSERT_TRUE(client.send("again"));
  23553. std::string msg;
  23554. EXPECT_EQ(ws::Text, client.read(msg));
  23555. EXPECT_EQ("again", msg);
  23556. client.close();
  23557. }
  23558. // Regression test: a certificate with a trusted chain but no identity match
  23559. // for the server IP must be rejected. The Mbed TLS backend used to skip
  23560. // verification entirely for IP hosts, so this connection succeeded there.
  23561. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  23562. // chain verification while the identity check must still fail.
  23563. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  23564. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23565. ASSERT_TRUE(svr.is_valid());
  23566. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23567. std::string msg;
  23568. while (ws.read(msg)) {
  23569. ws.send(msg);
  23570. }
  23571. });
  23572. auto port = svr.bind_to_any_port("127.0.0.1");
  23573. auto t = std::thread([&]() { svr.listen_after_bind(); });
  23574. auto se = detail::scope_exit([&] {
  23575. svr.stop();
  23576. t.join();
  23577. });
  23578. svr.wait_until_ready();
  23579. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  23580. "/echo");
  23581. std::string cert;
  23582. read_file(SERVER_CERT_FILE, cert);
  23583. client.load_ca_cert_store(cert.c_str(), cert.size());
  23584. ASSERT_FALSE(client.connect());
  23585. }
  23586. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  23587. // SNI, so nothing binds the host name to the TLS session. These bind the
  23588. // server to "localhost" instead, the only shape that exercises the SNI and
  23589. // hostname-verification path with certificate verification left enabled.
  23590. class WebSocketSSLDnsHostTest : public ::testing::Test {
  23591. protected:
  23592. void Start(const char *cert_file) {
  23593. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  23594. SERVER_PRIVATE_KEY_FILE);
  23595. ASSERT_TRUE(server_->is_valid());
  23596. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23597. std::string msg;
  23598. while (ws.read(msg)) {
  23599. ws.send(msg);
  23600. }
  23601. });
  23602. port_ = server_->bind_to_any_port("localhost");
  23603. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23604. server_->wait_until_ready();
  23605. }
  23606. void TearDown() override {
  23607. if (server_) { server_->stop(); }
  23608. if (server_thread_.joinable()) { server_thread_.join(); }
  23609. }
  23610. std::string url() const {
  23611. return "wss://localhost:" + std::to_string(port_) + "/echo";
  23612. }
  23613. std::unique_ptr<SSLServer> server_;
  23614. std::thread server_thread_;
  23615. int port_ = 0;
  23616. };
  23617. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  23618. // out and the connection is usable
  23619. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  23620. Start(SERVER_CERT2_FILE);
  23621. ws::WebSocketClient client(url());
  23622. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23623. ASSERT_TRUE(client.connect());
  23624. ASSERT_TRUE(client.send("hello"));
  23625. std::string msg;
  23626. EXPECT_EQ(ws::Text, client.read(msg));
  23627. EXPECT_EQ("hello", msg);
  23628. client.close();
  23629. }
  23630. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  23631. // while the identity check must still reject "localhost"
  23632. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  23633. Start(SERVER_CERT_FILE);
  23634. ws::WebSocketClient client(url());
  23635. client.set_ca_cert_path(SERVER_CERT_FILE);
  23636. auto res = client.connect();
  23637. ASSERT_FALSE(res);
  23638. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  23639. EXPECT_EQ(-1, res.status());
  23640. }
  23641. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  23642. // disabled: the chain is still checked, only the identity check is skipped
  23643. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  23644. Start(SERVER_CERT_FILE);
  23645. ws::WebSocketClient client(url());
  23646. client.set_ca_cert_path(SERVER_CERT_FILE);
  23647. client.enable_server_hostname_verification(false);
  23648. ASSERT_TRUE(client.connect());
  23649. ASSERT_TRUE(client.send("hello"));
  23650. std::string msg;
  23651. EXPECT_EQ(ws::Text, client.read(msg));
  23652. EXPECT_EQ("hello", msg);
  23653. client.close();
  23654. }
  23655. // A CA that did not sign the server certificate fails the chain, even though
  23656. // the name would match
  23657. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  23658. Start(SERVER_CERT2_FILE);
  23659. ws::WebSocketClient client(url());
  23660. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23661. ASSERT_FALSE(client.connect());
  23662. }
  23663. // With verification disabled, neither the chain nor the name is checked
  23664. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  23665. Start(SERVER_CERT_FILE);
  23666. ws::WebSocketClient client(url());
  23667. client.enable_server_certificate_verification(false);
  23668. ASSERT_TRUE(client.connect());
  23669. ASSERT_TRUE(client.send("hello"));
  23670. std::string msg;
  23671. EXPECT_EQ(ws::Text, client.read(msg));
  23672. EXPECT_EQ("hello", msg);
  23673. client.close();
  23674. }
  23675. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  23676. protected:
  23677. void SetUp() override {
  23678. server_ = httplib::detail::make_unique<SSLServer>(
  23679. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23680. ASSERT_TRUE(server_->is_valid());
  23681. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23682. std::string msg;
  23683. while (ws.read(msg)) {
  23684. ws.send(msg);
  23685. }
  23686. });
  23687. port_ = server_->bind_to_any_port("localhost");
  23688. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23689. server_->wait_until_ready();
  23690. }
  23691. void TearDown() override {
  23692. server_->stop();
  23693. if (server_thread_.joinable()) { server_thread_.join(); }
  23694. }
  23695. std::string url() const {
  23696. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23697. }
  23698. void ConnectWithClientCert(const std::string &client_cert_file,
  23699. const std::string &client_private_key_file,
  23700. const char *private_key_password) {
  23701. std::string cert_pem, key_pem;
  23702. read_file(client_cert_file, cert_pem);
  23703. read_file(client_private_key_file, key_pem);
  23704. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  23705. key_pem.c_str(), key_pem.size(),
  23706. private_key_password};
  23707. ws::WebSocketClient client(url(), pem);
  23708. ASSERT_TRUE(client.is_valid());
  23709. client.enable_server_certificate_verification(false);
  23710. ASSERT_TRUE(client.connect());
  23711. ASSERT_TRUE(client.send("hello"));
  23712. std::string msg;
  23713. EXPECT_EQ(ws::Text, client.read(msg));
  23714. EXPECT_EQ("hello", msg);
  23715. client.close();
  23716. }
  23717. std::unique_ptr<SSLServer> server_;
  23718. std::thread server_thread_;
  23719. int port_ = 0;
  23720. };
  23721. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  23722. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  23723. }
  23724. // Control for the tests above: the fixture's server really does require a
  23725. // client certificate, so it is the PEM the constructor installed that decides
  23726. // the outcome.
  23727. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  23728. ws::WebSocketClient client(url());
  23729. ASSERT_TRUE(client.is_valid());
  23730. client.enable_server_certificate_verification(false);
  23731. EXPECT_FALSE(client.connect());
  23732. }
  23733. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  23734. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  23735. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  23736. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  23737. }
  23738. #endif
  23739. #if !defined(_WIN32)
  23740. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  23741. auto secret_dir = std::string("./symlink_test_secret");
  23742. auto served_dir = std::string("./symlink_test_served");
  23743. auto secret_file = secret_dir + "/secret.txt";
  23744. auto symlink_path = served_dir + "/escape";
  23745. // Setup: create directories and files
  23746. mkdir(secret_dir.c_str(), 0755);
  23747. mkdir(served_dir.c_str(), 0755);
  23748. {
  23749. std::ofstream ofs(secret_file);
  23750. ofs << "SECRET_DATA";
  23751. }
  23752. // Create symlink using absolute path so it resolves correctly
  23753. #ifdef PATH_MAX
  23754. char abs_secret[PATH_MAX];
  23755. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  23756. #else
  23757. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  23758. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  23759. ASSERT_NE(nullptr, abs_secret);
  23760. #endif
  23761. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  23762. auto se = detail::scope_exit([&] {
  23763. unlink(symlink_path.c_str());
  23764. unlink(secret_file.c_str());
  23765. rmdir(served_dir.c_str());
  23766. rmdir(secret_dir.c_str());
  23767. });
  23768. Server svr;
  23769. svr.set_mount_point("/", served_dir);
  23770. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  23771. auto se2 = detail::scope_exit([&] {
  23772. svr.stop();
  23773. listen_thread.join();
  23774. });
  23775. svr.wait_until_ready();
  23776. Client cli("localhost", PORT);
  23777. // Symlink pointing outside base dir should be blocked
  23778. auto res = cli.Get("/escape/secret.txt");
  23779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23780. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  23781. }
  23782. #endif
  23783. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  23784. // "GET /smuggled" request), reads the first response, and only then sends the
  23785. // embedded request as the body. Returns how many times /smuggled ran.
  23786. //
  23787. // The body is sent AFTER receiving the first response (as in the original
  23788. // PoC) so that the stream_line_reader cannot buffer it together with the
  23789. // headers of the first request.
  23790. static int count_smuggled_requests(const std::string &outer_head,
  23791. std::string &first_response) {
  23792. Server svr;
  23793. svr.set_mount_point("/", "./www");
  23794. std::atomic<int> smuggled_count(0);
  23795. svr.Get("/smuggled", [&](const Request &, Response &res) {
  23796. smuggled_count++;
  23797. res.set_content("oops", "text/plain");
  23798. });
  23799. svr.Post("/post", [&](const Request &req, Response &res) {
  23800. res.set_content(req.body, "text/plain");
  23801. });
  23802. auto port = svr.bind_to_any_port("localhost");
  23803. thread t = thread([&] { svr.listen_after_bind(); });
  23804. auto se = detail::scope_exit([&] {
  23805. svr.stop();
  23806. t.join();
  23807. });
  23808. svr.wait_until_ready();
  23809. auto error = Error::Success;
  23810. auto sock = detail::create_client_socket(
  23811. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  23812. /*connection_timeout_sec=*/2, 0,
  23813. /*read_timeout_sec=*/2, 0,
  23814. /*write_timeout_sec=*/2, 0, std::string(), error);
  23815. EXPECT_NE(INVALID_SOCKET, sock);
  23816. if (sock == INVALID_SOCKET) { return -1; }
  23817. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23818. // The "smuggled" request will be sent as the body of the outer request
  23819. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  23820. "Host: localhost\r\n"
  23821. "Connection: close\r\n"
  23822. "\r\n";
  23823. auto head = outer_head;
  23824. auto len = std::to_string(smuggled.size());
  23825. for (auto pos = head.find("{len}"); pos != std::string::npos;
  23826. pos = head.find("{len}", pos + len.size())) {
  23827. head.replace(pos, 5, len);
  23828. }
  23829. // Step 1: Send only the outer request headers (no body yet)
  23830. auto sent = send(sock, head.data(), head.size(), 0);
  23831. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  23832. // Step 2: Read the first response
  23833. char buf[4096];
  23834. for (;;) {
  23835. auto n = recv(sock, buf, sizeof(buf), 0);
  23836. if (n <= 0) break;
  23837. first_response.append(buf, static_cast<size_t>(n));
  23838. // Stop once we have a complete response (headers + body)
  23839. auto hdr_end = first_response.find("\r\n\r\n");
  23840. if (hdr_end != std::string::npos) {
  23841. // Check for Content-Length to know when the body is complete
  23842. auto cl_pos = first_response.find("Content-Length:");
  23843. if (cl_pos != std::string::npos) {
  23844. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  23845. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  23846. auto cl = std::stoul(
  23847. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  23848. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  23849. } else {
  23850. break; // No Content-Length, assume headers-only response
  23851. }
  23852. }
  23853. }
  23854. // Step 3: Now send the body, which looks like a new HTTP request. On a
  23855. // vulnerable server the keep-alive loop reads this as a second request. The
  23856. // server may already have closed the connection, so the result is ignored.
  23857. send(sock, smuggled.data(), smuggled.size(), 0);
  23858. // Half-close so that a server which drained the body sees EOF and closes,
  23859. // instead of the read below waiting for the read timeout.
  23860. #ifdef _WIN32
  23861. ::shutdown(sock, SD_SEND);
  23862. #else
  23863. ::shutdown(sock, SHUT_WR);
  23864. #endif
  23865. // Step 4: Read until the server closes the connection
  23866. for (;;) {
  23867. auto n = recv(sock, buf, sizeof(buf), 0);
  23868. if (n <= 0) break;
  23869. }
  23870. return smuggled_count.load();
  23871. }
  23872. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  23873. // A GET request with Content-Length to a static file handler must have its
  23874. // body drained before the keep-alive connection is reused. Otherwise the
  23875. // unread body bytes are interpreted as the next HTTP request.
  23876. std::string first_response;
  23877. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23878. "Host: localhost\r\n"
  23879. "Content-Length: {len}\r\n"
  23880. "\r\n",
  23881. first_response));
  23882. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  23883. }
  23884. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  23885. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  23886. // be answered with 400 and the connection closed. Treating it as "no body"
  23887. // leaves the body to be parsed as the next request.
  23888. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  23889. const char *targets[] = {
  23890. "GET /file", // handler that never reads the body
  23891. "GET /not-found", // no handler matches (404)
  23892. "POST /post", // handler that reads the body
  23893. };
  23894. for (auto target : targets) {
  23895. for (auto value : values) {
  23896. std::string first_response;
  23897. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  23898. " HTTP/1.1\r\n"
  23899. "Host: localhost\r\n"
  23900. "Content-Length: " +
  23901. value + "\r\n\r\n",
  23902. first_response))
  23903. << target << " with Content-Length: " << value;
  23904. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  23905. << target << " with Content-Length: " << value;
  23906. }
  23907. }
  23908. }
  23909. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  23910. // A 400 for an unparseable request line leaves the rest of the message
  23911. // unread, so the connection must be closed rather than reused.
  23912. std::string first_response;
  23913. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  23914. "Host: localhost\r\n"
  23915. "Content-Length: {len}\r\n"
  23916. "\r\n",
  23917. first_response));
  23918. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23919. }
  23920. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  23921. // Same as above for a header block that fails to parse.
  23922. std::string first_response;
  23923. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23924. "Host: localhost\r\n"
  23925. "Bad Header\r\n"
  23926. "Content-Length: {len}\r\n"
  23927. "\r\n",
  23928. first_response));
  23929. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23930. }
  23931. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  23932. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  23933. // server must not read another request on that connection, even when the
  23934. // request had no body to drain.
  23935. std::string first_response;
  23936. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  23937. "Host: localhost\r\n"
  23938. "\r\n",
  23939. first_response));
  23940. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  23941. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  23942. }
  23943. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  23944. // A content reader that stops early leaves the stream inside the body.
  23945. // Draining the whole Content-Length from there, or reading the body again,
  23946. // reads into the next request, and whatever follows is parsed as a request
  23947. // of its own.
  23948. Server svr;
  23949. std::atomic<int> smuggled_count(0);
  23950. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  23951. svr.Post("/upload", [](const Request &req, Response &res,
  23952. const ContentReader &content_reader) {
  23953. // Stop at the last chunk, so the whole body has been read however it
  23954. // arrives.
  23955. auto length = req.get_header_value_u64("Content-Length");
  23956. size_t total = 0;
  23957. auto consumed = content_reader([&](const char *, size_t n) {
  23958. total += n;
  23959. return total < length;
  23960. });
  23961. EXPECT_FALSE(consumed);
  23962. if (req.has_param("retry")) {
  23963. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  23964. }
  23965. // Replace the 400 the aborted read set, which would close the connection.
  23966. res.set_redirect("/done");
  23967. });
  23968. auto port = svr.bind_to_any_port(HOST);
  23969. thread t = thread([&] { svr.listen_after_bind(); });
  23970. auto se = detail::scope_exit([&] {
  23971. svr.stop();
  23972. t.join();
  23973. });
  23974. svr.wait_until_ready();
  23975. // A front end sees the second request as a POST whose body is the GET. The
  23976. // first body is as long as the POST's headers, so draining it again reads
  23977. // exactly those and leaves the GET to be parsed next.
  23978. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  23979. "Host: localhost\r\n"
  23980. "\r\n";
  23981. std::string second_head = "POST /post HTTP/1.1\r\n"
  23982. "Host: localhost\r\n"
  23983. "Content-Length: " +
  23984. std::to_string(inner.size()) +
  23985. "\r\n"
  23986. "\r\n";
  23987. for (auto target : {"/upload", "/upload?retry"}) {
  23988. smuggled_count = 0;
  23989. std::string request = "POST " + std::string(target) +
  23990. " HTTP/1.1\r\n"
  23991. "Host: localhost\r\n"
  23992. "Content-Length: " +
  23993. std::to_string(second_head.size()) +
  23994. "\r\n"
  23995. "\r\n" +
  23996. std::string(second_head.size(), 'A') + second_head +
  23997. inner;
  23998. std::string response;
  23999. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  24000. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  24001. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  24002. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  24003. EXPECT_EQ(0, smuggled_count.load()) << target;
  24004. }
  24005. }
  24006. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  24007. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  24008. // must be rejected with 400 Bad Request.
  24009. Server svr;
  24010. svr.Post("/test", [&](const Request &, Response &res) {
  24011. res.set_content("ok", "text/plain");
  24012. });
  24013. thread t = thread([&] { svr.listen(HOST, PORT); });
  24014. auto se = detail::scope_exit([&] {
  24015. svr.stop();
  24016. t.join();
  24017. ASSERT_FALSE(svr.is_running());
  24018. });
  24019. svr.wait_until_ready();
  24020. // Exact "chunked"
  24021. {
  24022. auto req = "POST /test HTTP/1.1\r\n"
  24023. "Host: localhost\r\n"
  24024. "Content-Length: 5\r\n"
  24025. "Transfer-Encoding: chunked\r\n"
  24026. "Connection: close\r\n"
  24027. "\r\n"
  24028. "hello";
  24029. std::string response;
  24030. ASSERT_TRUE(send_request(1, req, &response));
  24031. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24032. response.substr(0, response.find("\r\n")));
  24033. }
  24034. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  24035. {
  24036. auto req = "POST /test HTTP/1.1\r\n"
  24037. "Host: localhost\r\n"
  24038. "Content-Length: 5\r\n"
  24039. "Transfer-Encoding: gzip, chunked\r\n"
  24040. "Connection: close\r\n"
  24041. "\r\n"
  24042. "hello";
  24043. std::string response;
  24044. ASSERT_TRUE(send_request(1, req, &response));
  24045. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24046. response.substr(0, response.find("\r\n")));
  24047. }
  24048. }
  24049. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  24050. Server svr;
  24051. svr.Post("/test", [&](const Request &, Response &res) {
  24052. res.set_content("ok", "text/plain");
  24053. });
  24054. thread t = thread([&] { svr.listen(HOST, PORT); });
  24055. auto se = detail::scope_exit([&] {
  24056. svr.stop();
  24057. t.join();
  24058. ASSERT_FALSE(svr.is_running());
  24059. });
  24060. svr.wait_until_ready();
  24061. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  24062. // length cannot be determined, so the server must answer 400 and close
  24063. // rather than treat the request as bodyless and leave the body in the
  24064. // socket for the next request to pick up.
  24065. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  24066. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  24067. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  24068. std::string response;
  24069. ASSERT_TRUE(send_request(1, req, &response));
  24070. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24071. response.substr(0, response.find("\r\n")))
  24072. << transfer_encoding;
  24073. }
  24074. // RFC 9110 5.3: the codings may also be split across several
  24075. // Transfer-Encoding lines, which combine in the order they were received.
  24076. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  24077. // just like the single-line "chunked, gzip" above.
  24078. {
  24079. auto req = "POST /test HTTP/1.1\r\n"
  24080. "Host: localhost\r\n"
  24081. "Transfer-Encoding: chunked\r\n"
  24082. "Transfer-Encoding: gzip\r\n"
  24083. "\r\n"
  24084. "0\r\n\r\n";
  24085. std::string response;
  24086. ASSERT_TRUE(send_request(1, req, &response));
  24087. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24088. response.substr(0, response.find("\r\n")));
  24089. }
  24090. // A sequence ending in chunked stays valid.
  24091. auto req = "POST /test HTTP/1.1\r\n"
  24092. "Host: localhost\r\n"
  24093. "Transfer-Encoding: gzip, chunked\r\n"
  24094. "Connection: close\r\n"
  24095. "\r\n"
  24096. "0\r\n\r\n";
  24097. std::string response;
  24098. ASSERT_TRUE(send_request(1, req, &response));
  24099. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  24100. // ...including when it is spread over several lines.
  24101. auto split_req = "POST /test HTTP/1.1\r\n"
  24102. "Host: localhost\r\n"
  24103. "Transfer-Encoding: gzip\r\n"
  24104. "Transfer-Encoding: chunked\r\n"
  24105. "Connection: close\r\n"
  24106. "\r\n"
  24107. "0\r\n\r\n";
  24108. std::string split_response;
  24109. ASSERT_TRUE(send_request(1, split_req, &split_response));
  24110. EXPECT_EQ("HTTP/1.1 200 OK",
  24111. split_response.substr(0, split_response.find("\r\n")));
  24112. }
  24113. // Regression for issue #2450: a DELETE without Content-Length on a
  24114. // keep-alive connection must not let the post-response drain consume the
  24115. // next request's bytes.
  24116. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  24117. Server svr;
  24118. std::atomic<int> delete_count(0);
  24119. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  24120. delete_count++;
  24121. res.status = StatusCode::NoContent_204;
  24122. });
  24123. auto port = svr.bind_to_any_port(HOST);
  24124. thread t = thread([&] { svr.listen_after_bind(); });
  24125. auto se = detail::scope_exit([&] {
  24126. svr.stop();
  24127. t.join();
  24128. });
  24129. svr.wait_until_ready();
  24130. auto error = Error::Success;
  24131. auto sock = detail::create_client_socket(
  24132. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24133. /*connection_timeout_sec=*/2, 0,
  24134. /*read_timeout_sec=*/2, 0,
  24135. /*write_timeout_sec=*/2, 0, std::string(), error);
  24136. ASSERT_NE(INVALID_SOCKET, sock);
  24137. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24138. auto send_request_and_read_response = [&](const std::string &req,
  24139. std::string &out) -> bool {
  24140. auto sent = send(sock, req.data(), req.size(), 0);
  24141. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  24142. char buf[4096];
  24143. for (;;) {
  24144. auto n = recv(sock, buf, sizeof(buf), 0);
  24145. if (n <= 0) { return !out.empty(); }
  24146. out.append(buf, static_cast<size_t>(n));
  24147. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  24148. }
  24149. };
  24150. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  24151. "Host: localhost\r\n"
  24152. "\r\n";
  24153. std::string resp1;
  24154. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  24155. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  24156. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  24157. "Host: localhost\r\n"
  24158. "Connection: close\r\n"
  24159. "\r\n";
  24160. std::string resp2;
  24161. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  24162. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  24163. EXPECT_EQ(2, delete_count.load());
  24164. }
  24165. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  24166. Server svr;
  24167. svr.Post("/ingest", [&](const Request &, Response &res,
  24168. const ContentReader &content_reader) {
  24169. auto consumed = content_reader([](const char *, size_t) { return false; });
  24170. EXPECT_FALSE(consumed);
  24171. res.status = StatusCode::Conflict_409;
  24172. res.set_header("Connection", "close");
  24173. });
  24174. auto port = svr.bind_to_any_port(HOST);
  24175. thread t = thread([&] { svr.listen_after_bind(); });
  24176. auto se = detail::scope_exit([&] {
  24177. svr.stop();
  24178. t.join();
  24179. });
  24180. svr.wait_until_ready();
  24181. auto error = Error::Success;
  24182. auto sock = detail::create_client_socket(
  24183. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24184. /*connection_timeout_sec=*/2, 0,
  24185. /*read_timeout_sec=*/1, 0,
  24186. /*write_timeout_sec=*/2, 0, std::string(), error);
  24187. ASSERT_NE(INVALID_SOCKET, sock);
  24188. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24189. std::string request = "POST /ingest HTTP/1.1\r\n"
  24190. "Host: localhost\r\n"
  24191. "Transfer-Encoding: chunked\r\n"
  24192. "\r\n"
  24193. "4\r\n"
  24194. "data\r\n";
  24195. auto sent = send(sock, request.data(), request.size(), 0);
  24196. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  24197. std::string response;
  24198. ssize_t received = 0;
  24199. do {
  24200. char buf[4096];
  24201. received = recv(sock, buf, sizeof(buf), 0);
  24202. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  24203. } while (received > 0);
  24204. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  24205. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  24206. EXPECT_EQ(0, received);
  24207. }
  24208. namespace no_proxy_test {
  24209. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  24210. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  24211. // calling listen().
  24212. class ScopedServer {
  24213. public:
  24214. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  24215. ~ScopedServer() {
  24216. svr_.stop();
  24217. if (th_.joinable()) { th_.join(); }
  24218. }
  24219. Server &svr() { return svr_; }
  24220. int port() const { return port_; }
  24221. void listen() {
  24222. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24223. svr_.wait_until_ready();
  24224. }
  24225. private:
  24226. Server svr_;
  24227. std::thread th_;
  24228. int port_ = 0;
  24229. };
  24230. class ProxyAndTargetServers {
  24231. public:
  24232. ProxyAndTargetServers() {
  24233. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  24234. proxy_hits_++;
  24235. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24236. res.set_content("via-proxy", "text/plain");
  24237. });
  24238. target_.Get(".*", [this](const Request &req, Response &res) {
  24239. target_hits_++;
  24240. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24241. res.set_content("direct", "text/plain");
  24242. });
  24243. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  24244. target_port_ = target_.bind_to_any_port("127.0.0.1");
  24245. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  24246. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  24247. proxy_mock_.wait_until_ready();
  24248. target_.wait_until_ready();
  24249. }
  24250. ~ProxyAndTargetServers() {
  24251. proxy_mock_.stop();
  24252. target_.stop();
  24253. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  24254. if (target_thread_.joinable()) { target_thread_.join(); }
  24255. }
  24256. Server &proxy_mock() { return proxy_mock_; }
  24257. Server &target() { return target_; }
  24258. int proxy_port() const { return proxy_port_; }
  24259. int target_port() const { return target_port_; }
  24260. int proxy_hits() const { return proxy_hits_.load(); }
  24261. int target_hits() const { return target_hits_.load(); }
  24262. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  24263. void reset_counters() {
  24264. proxy_hits_ = 0;
  24265. target_hits_ = 0;
  24266. last_had_proxy_authz_ = false;
  24267. }
  24268. private:
  24269. Server proxy_mock_;
  24270. Server target_;
  24271. std::thread proxy_thread_;
  24272. std::thread target_thread_;
  24273. int proxy_port_ = 0;
  24274. int target_port_ = 0;
  24275. std::atomic<int> proxy_hits_{0};
  24276. std::atomic<int> target_hits_{0};
  24277. std::atomic<bool> last_had_proxy_authz_{false};
  24278. };
  24279. inline std::unique_ptr<Client> make_client(const std::string &host,
  24280. ProxyAndTargetServers &s) {
  24281. auto cli = detail::make_unique<Client>(host, s.target_port());
  24282. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  24283. cli->set_proxy("127.0.0.1", s.proxy_port());
  24284. return cli;
  24285. }
  24286. } // namespace no_proxy_test
  24287. using no_proxy_test::make_client;
  24288. using no_proxy_test::ProxyAndTargetServers;
  24289. TEST(NoProxyTest, ExactHostnameBypasses) {
  24290. ProxyAndTargetServers s;
  24291. auto cli = make_client("example.com", s);
  24292. cli->set_no_proxy({"example.com"});
  24293. auto res = cli->Get("/");
  24294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24295. EXPECT_EQ(0, s.proxy_hits());
  24296. EXPECT_EQ(1, s.target_hits());
  24297. }
  24298. TEST(NoProxyTest, SubdomainBypasses) {
  24299. ProxyAndTargetServers s;
  24300. auto cli = make_client("foo.example.com", s);
  24301. cli->set_no_proxy({"example.com"});
  24302. auto res = cli->Get("/");
  24303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24304. EXPECT_EQ(0, s.proxy_hits());
  24305. EXPECT_EQ(1, s.target_hits());
  24306. }
  24307. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  24308. // Regression guard: "evilexample.com" must not be considered a subdomain
  24309. // of "example.com". Without the dot-boundary rule, a naive endsWith
  24310. // check would let traffic bypass the proxy and leak credentials direct
  24311. // to the attacker host.
  24312. ProxyAndTargetServers s;
  24313. auto cli = make_client("evilexample.com", s);
  24314. cli->set_no_proxy({"example.com"});
  24315. auto res = cli->Get("/");
  24316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24317. EXPECT_GE(s.proxy_hits(), 1);
  24318. EXPECT_EQ(0, s.target_hits());
  24319. }
  24320. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  24321. ProxyAndTargetServers s;
  24322. auto cli = make_client("example.com.evil.com", s);
  24323. cli->set_no_proxy({"example.com"});
  24324. auto res = cli->Get("/");
  24325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24326. EXPECT_GE(s.proxy_hits(), 1);
  24327. EXPECT_EQ(0, s.target_hits());
  24328. }
  24329. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  24330. ProxyAndTargetServers s;
  24331. auto cli = make_client("example.com", s);
  24332. cli->set_no_proxy({".example.com"});
  24333. auto res = cli->Get("/");
  24334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24335. EXPECT_EQ(0, s.proxy_hits());
  24336. EXPECT_EQ(1, s.target_hits());
  24337. }
  24338. TEST(NoProxyTest, CaseInsensitiveHostname) {
  24339. ProxyAndTargetServers s;
  24340. auto cli = make_client("Example.COM", s);
  24341. cli->set_no_proxy({"EXAMPLE.com"});
  24342. auto res = cli->Get("/");
  24343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24344. EXPECT_EQ(0, s.proxy_hits());
  24345. EXPECT_EQ(1, s.target_hits());
  24346. }
  24347. TEST(NoProxyTest, TrailingDotIsNormalized) {
  24348. ProxyAndTargetServers s;
  24349. auto cli = make_client("example.com.", s);
  24350. cli->set_no_proxy({"example.com"});
  24351. auto res = cli->Get("/");
  24352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24353. EXPECT_EQ(0, s.proxy_hits());
  24354. EXPECT_EQ(1, s.target_hits());
  24355. }
  24356. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  24357. // Trailing dots must be normalized on BOTH sides — host and entry.
  24358. // An implementation that only strips the host-side trailing dot would
  24359. // fail to match host "example.com" against entry "example.com." because
  24360. // a literal substring search would compare 11 chars against 12.
  24361. ProxyAndTargetServers s;
  24362. auto cli = make_client("example.com", s);
  24363. cli->set_no_proxy({"example.com."});
  24364. auto res = cli->Get("/");
  24365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24366. EXPECT_EQ(0, s.proxy_hits());
  24367. EXPECT_EQ(1, s.target_hits());
  24368. }
  24369. TEST(NoProxyTest, WildcardBypassesEverything) {
  24370. ProxyAndTargetServers s;
  24371. auto cli = make_client("anything.invalid.test", s);
  24372. cli->set_no_proxy({"*"});
  24373. auto res = cli->Get("/");
  24374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24375. EXPECT_EQ(0, s.proxy_hits());
  24376. EXPECT_EQ(1, s.target_hits());
  24377. }
  24378. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  24379. ProxyAndTargetServers s;
  24380. Client cli("127.0.0.1", s.target_port());
  24381. cli.set_proxy("127.0.0.1", s.proxy_port());
  24382. cli.set_no_proxy({"127.0.0.1"});
  24383. auto res = cli.Get("/");
  24384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24385. EXPECT_EQ(0, s.proxy_hits());
  24386. EXPECT_EQ(1, s.target_hits());
  24387. }
  24388. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  24389. ProxyAndTargetServers s;
  24390. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  24391. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  24392. cli.set_proxy("127.0.0.1", s.proxy_port());
  24393. cli.set_no_proxy({"::1"});
  24394. auto res = cli.Get("/");
  24395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24396. EXPECT_EQ(0, s.proxy_hits());
  24397. EXPECT_EQ(1, s.target_hits());
  24398. }
  24399. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  24400. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  24401. // must still be recognized as IPv6 for CIDR matching. Implementations
  24402. // that detect IPv6 only when the host begins with '[' would parse the
  24403. // host as a hostname and miss the match.
  24404. ProxyAndTargetServers s;
  24405. Client cli("fe80::1", s.target_port());
  24406. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24407. cli.set_proxy("127.0.0.1", s.proxy_port());
  24408. cli.set_no_proxy({"fe80::/10"});
  24409. auto res = cli.Get("/");
  24410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24411. EXPECT_EQ(0, s.proxy_hits());
  24412. EXPECT_EQ(1, s.target_hits());
  24413. }
  24414. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  24415. ProxyAndTargetServers s;
  24416. Client cli("::1", s.target_port());
  24417. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  24418. cli.set_proxy("127.0.0.1", s.proxy_port());
  24419. cli.set_no_proxy({"[::1]"});
  24420. auto res = cli.Get("/");
  24421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24422. EXPECT_EQ(0, s.proxy_hits());
  24423. EXPECT_EQ(1, s.target_hits());
  24424. }
  24425. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  24426. ProxyAndTargetServers s;
  24427. Client cli("fe80::1", s.target_port());
  24428. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24429. cli.set_proxy("127.0.0.1", s.proxy_port());
  24430. cli.set_no_proxy({"[fe80::]/10"});
  24431. auto res = cli.Get("/");
  24432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24433. EXPECT_EQ(0, s.proxy_hits());
  24434. EXPECT_EQ(1, s.target_hits());
  24435. }
  24436. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  24437. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  24438. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  24439. // tricks via address-family conversion.
  24440. ProxyAndTargetServers s;
  24441. Client cli("::ffff:127.0.0.1", s.target_port());
  24442. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  24443. cli.set_proxy("127.0.0.1", s.proxy_port());
  24444. cli.set_no_proxy({"127.0.0.1"});
  24445. auto res = cli.Get("/");
  24446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24447. EXPECT_GE(s.proxy_hits(), 1);
  24448. EXPECT_EQ(0, s.target_hits());
  24449. }
  24450. TEST(NoProxyTest, IPv4CidrMatch) {
  24451. ProxyAndTargetServers s;
  24452. Client cli("127.0.0.1", s.target_port());
  24453. cli.set_proxy("127.0.0.1", s.proxy_port());
  24454. cli.set_no_proxy({"127.0.0.0/8"});
  24455. auto res = cli.Get("/");
  24456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24457. EXPECT_EQ(0, s.proxy_hits());
  24458. EXPECT_EQ(1, s.target_hits());
  24459. }
  24460. TEST(NoProxyTest, IPv4CidrNonMatch) {
  24461. ProxyAndTargetServers s;
  24462. Client cli("127.0.0.1", s.target_port());
  24463. cli.set_proxy("127.0.0.1", s.proxy_port());
  24464. cli.set_no_proxy({"10.0.0.0/8"});
  24465. auto res = cli.Get("/");
  24466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24467. EXPECT_GE(s.proxy_hits(), 1);
  24468. EXPECT_EQ(0, s.target_hits());
  24469. }
  24470. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  24471. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  24472. // IPv4 target matches.
  24473. ProxyAndTargetServers s;
  24474. Client cli("127.0.0.1", s.target_port());
  24475. cli.set_proxy("127.0.0.1", s.proxy_port());
  24476. cli.set_no_proxy({"0.0.0.0/0"});
  24477. auto res = cli.Get("/");
  24478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24479. EXPECT_EQ(0, s.proxy_hits());
  24480. EXPECT_EQ(1, s.target_hits());
  24481. }
  24482. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  24483. ProxyAndTargetServers s;
  24484. Client cli("127.0.0.1", s.target_port());
  24485. cli.set_proxy("127.0.0.1", s.proxy_port());
  24486. cli.set_no_proxy({"127.0.0.1"});
  24487. auto res = cli.Get("/");
  24488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24489. EXPECT_EQ(0, s.proxy_hits());
  24490. EXPECT_EQ(1, s.target_hits());
  24491. }
  24492. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  24493. ProxyAndTargetServers s;
  24494. Client cli("127.0.0.1", s.target_port());
  24495. cli.set_proxy("127.0.0.1", s.proxy_port());
  24496. cli.set_no_proxy({"127.0.0.0/33"});
  24497. auto res = cli.Get("/");
  24498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24499. EXPECT_GE(s.proxy_hits(), 1);
  24500. EXPECT_EQ(0, s.target_hits());
  24501. }
  24502. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  24503. // Empty prefix after the slash must be rejected, not silently treated as /32.
  24504. ProxyAndTargetServers s;
  24505. Client cli("127.0.0.1", s.target_port());
  24506. cli.set_proxy("127.0.0.1", s.proxy_port());
  24507. cli.set_no_proxy({"127.0.0.1/"});
  24508. auto res = cli.Get("/");
  24509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24510. EXPECT_GE(s.proxy_hits(), 1);
  24511. EXPECT_EQ(0, s.target_hits());
  24512. }
  24513. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  24514. ProxyAndTargetServers s;
  24515. auto cli = make_client("internal.corp", s);
  24516. cli->set_proxy_basic_auth("u", "p");
  24517. cli->set_no_proxy({"internal.corp"});
  24518. auto res = cli->Get("/");
  24519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24520. EXPECT_EQ(1, s.target_hits());
  24521. EXPECT_EQ(0, s.proxy_hits());
  24522. EXPECT_FALSE(s.last_had_proxy_authz())
  24523. << "Proxy-Authorization must not be sent direct to the target";
  24524. }
  24525. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  24526. ProxyAndTargetServers s;
  24527. auto cli = make_client("public.example", s);
  24528. cli->set_proxy_basic_auth("u", "p");
  24529. cli->set_no_proxy({"internal.corp"}); // does not match
  24530. auto res = cli->Get("/");
  24531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24532. EXPECT_GE(s.proxy_hits(), 1);
  24533. EXPECT_TRUE(s.last_had_proxy_authz());
  24534. }
  24535. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  24536. std::atomic<int> hits{0};
  24537. std::atomic<int> hits_with_authz{0};
  24538. no_proxy_test::ScopedServer proxy_mock;
  24539. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24540. hits++;
  24541. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  24542. if (req.target.find("/redir") != std::string::npos) {
  24543. res.set_redirect("http://other.example/landed");
  24544. } else {
  24545. res.set_content("via-proxy", "text/plain");
  24546. }
  24547. });
  24548. proxy_mock.listen();
  24549. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  24550. hits = 0;
  24551. hits_with_authz = 0;
  24552. Client cli("public.example", 80);
  24553. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24554. cli.set_proxy_basic_auth(c.first, c.second);
  24555. cli.set_follow_location(true);
  24556. // The redirect to another host goes through the proxy as well
  24557. auto res = cli.Get("/redir");
  24558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24559. EXPECT_EQ(2, hits.load());
  24560. EXPECT_EQ(2, hits_with_authz.load());
  24561. }
  24562. }
  24563. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  24564. ProxyAndTargetServers s;
  24565. auto cli = make_client("anything.test", s);
  24566. auto res = cli->Get("/");
  24567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24568. EXPECT_GE(s.proxy_hits(), 1);
  24569. EXPECT_EQ(0, s.target_hits());
  24570. }
  24571. TEST(NoProxyTest, PortSpecificEntryRejected) {
  24572. ProxyAndTargetServers s;
  24573. auto cli = make_client("example.com", s);
  24574. cli->set_no_proxy({"example.com:8080"});
  24575. auto res = cli->Get("/");
  24576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24577. EXPECT_GE(s.proxy_hits(), 1);
  24578. EXPECT_EQ(0, s.target_hits());
  24579. }
  24580. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  24581. ProxyAndTargetServers s;
  24582. auto cli = make_client("anything.test", s);
  24583. cli->set_no_proxy({"", " ", "\t"});
  24584. auto res = cli->Get("/");
  24585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24586. EXPECT_GE(s.proxy_hits(), 1);
  24587. EXPECT_EQ(0, s.target_hits());
  24588. }
  24589. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  24590. // An entry with leading/trailing whitespace must still match — env-style
  24591. // values are commonly pasted with stray spaces and an implementation
  24592. // that feeds the raw token directly to inet_pton would fail to match
  24593. // valid CIDRs because of the spaces.
  24594. ProxyAndTargetServers s;
  24595. Client cli("127.0.0.1", s.target_port());
  24596. cli.set_proxy("127.0.0.1", s.proxy_port());
  24597. cli.set_no_proxy({" 127.0.0.0/8 "});
  24598. auto res = cli.Get("/");
  24599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24600. EXPECT_EQ(0, s.proxy_hits());
  24601. EXPECT_EQ(1, s.target_hits());
  24602. }
  24603. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  24604. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  24605. // go direct and must NOT carry Proxy-Authorization.
  24606. std::atomic<int> proxy_hits{0};
  24607. std::atomic<int> target_hits{0};
  24608. std::atomic<bool> target_saw_authz{false};
  24609. no_proxy_test::ScopedServer proxy_mock, target;
  24610. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24611. proxy_hits++;
  24612. res.status = 302;
  24613. res.set_header("Location", "http://127.0.0.1:" +
  24614. std::to_string(target.port()) + "/landed");
  24615. });
  24616. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24617. target_hits++;
  24618. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  24619. res.set_content("direct", "text/plain");
  24620. });
  24621. proxy_mock.listen();
  24622. target.listen();
  24623. Client cli("public.example", target.port());
  24624. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24625. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24626. cli.set_proxy_basic_auth("u", "p");
  24627. cli.set_no_proxy({"127.0.0.1"});
  24628. cli.set_follow_location(true);
  24629. auto res = cli.Get("/redir");
  24630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24631. EXPECT_GE(proxy_hits.load(), 1);
  24632. EXPECT_GE(target_hits.load(), 1);
  24633. EXPECT_FALSE(target_saw_authz.load());
  24634. }
  24635. #ifdef CPPHTTPLIB_SSL_ENABLED
  24636. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  24637. // Direct origin replying 407 must not trigger the digest retry; otherwise
  24638. // proxy creds would be sent to the (possibly hostile) origin.
  24639. std::atomic<int> target_hits{0};
  24640. std::atomic<bool> target_saw_proxy_authz{false};
  24641. no_proxy_test::ScopedServer target;
  24642. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24643. target_hits++;
  24644. if (req.has_header("Proxy-Authorization")) {
  24645. target_saw_proxy_authz = true;
  24646. }
  24647. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24648. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  24649. "nonce=\"abc\", algorithm=MD5");
  24650. });
  24651. target.listen();
  24652. // The proxy address is set to the target's port: the bypass MUST kick in;
  24653. // if it doesn't, the test still routes "via proxy" to the same server and
  24654. // the Proxy-Authorization assertion below catches the leak.
  24655. Client cli("evil.example", target.port());
  24656. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  24657. cli.set_proxy("127.0.0.1", target.port());
  24658. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24659. cli.set_no_proxy({"evil.example"});
  24660. auto res = cli.Get("/x");
  24661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24662. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24663. EXPECT_EQ(1, target_hits.load());
  24664. EXPECT_FALSE(target_saw_proxy_authz.load());
  24665. }
  24666. #endif
  24667. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  24668. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  24669. std::atomic<int> proxy_hits{0};
  24670. std::atomic<int> bypass_hits{0};
  24671. std::atomic<bool> proxy_saw_c_url{false};
  24672. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  24673. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24674. proxy_hits++;
  24675. if (req.path.find("/start") != std::string::npos) {
  24676. res.status = 302;
  24677. res.set_header("Location", "http://127.0.0.1:" +
  24678. std::to_string(bypass_server.port()) +
  24679. "/middle");
  24680. return;
  24681. }
  24682. if (req.path.find("/end") != std::string::npos) {
  24683. proxy_saw_c_url = true;
  24684. res.set_content("c-via-proxy", "text/plain");
  24685. return;
  24686. }
  24687. res.set_content("unexpected", "text/plain");
  24688. });
  24689. // public.example's "advertised" port is arbitrary (the request never lands
  24690. // there — it goes through the proxy), but use a dynamic value to stay
  24691. // friendly with sharded parallel runs.
  24692. int public_port = bypass_server.port();
  24693. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  24694. bypass_hits++;
  24695. res.status = 302;
  24696. res.set_header("Location", "http://public.example:" +
  24697. std::to_string(public_port) + "/end");
  24698. });
  24699. proxy_mock.listen();
  24700. bypass_server.listen();
  24701. Client cli("public.example", public_port);
  24702. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24703. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24704. cli.set_no_proxy({"127.0.0.1"});
  24705. cli.set_follow_location(true);
  24706. auto res = cli.Get("/start");
  24707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24708. EXPECT_EQ(StatusCode::OK_200, res->status);
  24709. EXPECT_EQ("c-via-proxy", res->body);
  24710. EXPECT_GE(proxy_hits.load(), 2);
  24711. EXPECT_GE(bypass_hits.load(), 1);
  24712. EXPECT_TRUE(proxy_saw_c_url.load());
  24713. }
  24714. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  24715. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  24716. // request reconnects to the correct endpoint.
  24717. std::atomic<int> proxy_hits{0};
  24718. std::atomic<int> target_hits{0};
  24719. no_proxy_test::ScopedServer proxy_mock, target;
  24720. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24721. proxy_hits++;
  24722. res.set_content("via-proxy", "text/plain");
  24723. });
  24724. target.svr().Get(".*", [&](const Request &, Response &res) {
  24725. target_hits++;
  24726. res.set_content("direct", "text/plain");
  24727. });
  24728. proxy_mock.listen();
  24729. target.listen();
  24730. Client cli("public.example", target.port());
  24731. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24732. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24733. cli.set_keep_alive(true);
  24734. auto res1 = cli.Get("/a");
  24735. ASSERT_TRUE(res1);
  24736. EXPECT_EQ("via-proxy", res1->body);
  24737. EXPECT_EQ(1, proxy_hits.load());
  24738. EXPECT_EQ(0, target_hits.load());
  24739. cli.set_no_proxy({"public.example"});
  24740. auto res2 = cli.Get("/b");
  24741. ASSERT_TRUE(res2);
  24742. EXPECT_EQ("direct", res2->body);
  24743. EXPECT_EQ(1, proxy_hits.load());
  24744. EXPECT_EQ(1, target_hits.load());
  24745. }
  24746. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  24747. namespace proxy_tunnel_test {
  24748. // SSLServer counterpart to no_proxy_test::ScopedServer.
  24749. class ScopedSSLServer {
  24750. public:
  24751. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  24752. port_ = svr_.bind_to_any_port("127.0.0.1");
  24753. }
  24754. ~ScopedSSLServer() {
  24755. svr_.stop();
  24756. if (th_.joinable()) { th_.join(); }
  24757. }
  24758. SSLServer &svr() { return svr_; }
  24759. int port() const { return port_; }
  24760. void listen() {
  24761. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24762. svr_.wait_until_ready();
  24763. }
  24764. private:
  24765. SSLServer svr_;
  24766. std::thread th_;
  24767. int port_ = 0;
  24768. };
  24769. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  24770. class ScopedConnectProxy {
  24771. public:
  24772. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  24773. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  24774. if (listen_fd_ < 0) { return; }
  24775. int yes = 1;
  24776. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  24777. sockaddr_in a{};
  24778. a.sin_family = AF_INET;
  24779. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24780. a.sin_port = 0;
  24781. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  24782. return;
  24783. }
  24784. socklen_t alen = sizeof(a);
  24785. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  24786. 0) {
  24787. return;
  24788. }
  24789. port_ = ntohs(a.sin_port);
  24790. if (::listen(listen_fd_, 1) != 0) { return; }
  24791. th_ = std::thread([this] { run(); });
  24792. }
  24793. ~ScopedConnectProxy() {
  24794. stop_ = true;
  24795. if (listen_fd_ >= 0) {
  24796. ::shutdown(listen_fd_, SHUT_RDWR);
  24797. ::close(listen_fd_);
  24798. }
  24799. if (th_.joinable()) { th_.join(); }
  24800. }
  24801. int port() const { return port_; }
  24802. int connect_hits() const { return connect_hits_.load(); }
  24803. // Head of the last CONNECT request, as the proxy saw it on the wire.
  24804. std::string connect_request() const {
  24805. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24806. return connect_request_;
  24807. }
  24808. private:
  24809. void run() {
  24810. while (!stop_.load()) {
  24811. fd_set rfds;
  24812. FD_ZERO(&rfds);
  24813. FD_SET(listen_fd_, &rfds);
  24814. timeval tv{0, 100 * 1000};
  24815. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  24816. if (sel <= 0) { continue; }
  24817. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  24818. if (client_fd < 0) { continue; }
  24819. std::string req;
  24820. char buf[2048];
  24821. while (req.find("\r\n\r\n") == std::string::npos) {
  24822. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  24823. if (n <= 0) { break; }
  24824. req.append(buf, static_cast<size_t>(n));
  24825. }
  24826. if (req.compare(0, 7, "CONNECT") != 0) {
  24827. ::close(client_fd);
  24828. continue;
  24829. }
  24830. connect_hits_++;
  24831. {
  24832. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24833. connect_request_ = req;
  24834. }
  24835. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  24836. ::send(client_fd, ok, std::strlen(ok), 0);
  24837. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  24838. sockaddr_in o{};
  24839. o.sin_family = AF_INET;
  24840. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24841. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  24842. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  24843. 0) {
  24844. ::close(client_fd);
  24845. ::close(origin_fd);
  24846. continue;
  24847. }
  24848. auto forward = [](int from, int to) {
  24849. char b[8192];
  24850. for (;;) {
  24851. ssize_t n = ::recv(from, b, sizeof(b), 0);
  24852. if (n <= 0) { break; }
  24853. ssize_t off = 0;
  24854. while (off < n) {
  24855. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  24856. if (s <= 0) {
  24857. off = n;
  24858. break;
  24859. }
  24860. off += s;
  24861. }
  24862. }
  24863. ::shutdown(to, SHUT_WR);
  24864. };
  24865. std::thread t1([&] { forward(client_fd, origin_fd); });
  24866. std::thread t2([&] { forward(origin_fd, client_fd); });
  24867. t1.join();
  24868. t2.join();
  24869. ::close(client_fd);
  24870. ::close(origin_fd);
  24871. }
  24872. }
  24873. int forward_port_ = -1;
  24874. int listen_fd_ = -1;
  24875. int port_ = 0;
  24876. std::thread th_;
  24877. std::atomic<bool> stop_{false};
  24878. std::atomic<int> connect_hits_{0};
  24879. mutable std::mutex connect_request_mutex_;
  24880. std::string connect_request_;
  24881. };
  24882. // Sends one request through the CONNECT proxy to the TLS origin with a
  24883. // credential configured for each hop, and checks that each credential reaches
  24884. // only the hop it was configured for: the proxy's on the CONNECT request, the
  24885. // origin's (every header in origin_headers) on the tunnelled request.
  24886. void CredentialsStayWithTheirHop(
  24887. const std::function<void(SSLClient &)> &set_credentials,
  24888. const std::string &scheme,
  24889. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  24890. std::atomic<int> origin_hits{0};
  24891. std::atomic<bool> origin_saw_proxy_authz{false};
  24892. std::atomic<bool> origin_saw_headers{false};
  24893. ScopedSSLServer origin;
  24894. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24895. origin_hits++;
  24896. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  24897. origin_saw_headers =
  24898. std::all_of(origin_headers.begin(), origin_headers.end(),
  24899. [&](const std::string &h) { return req.has_header(h); });
  24900. res.set_content("ok", "text/plain");
  24901. });
  24902. origin.listen();
  24903. ScopedConnectProxy proxy(origin.port());
  24904. ASSERT_NE(0, proxy.port());
  24905. // Pinned to 127.0.0.1 for the same reason as the test below.
  24906. SSLClient cli("127.0.0.1", origin.port());
  24907. cli.enable_server_certificate_verification(false);
  24908. cli.set_proxy("127.0.0.1", proxy.port());
  24909. set_credentials(cli);
  24910. auto res = cli.Get("/x");
  24911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24912. EXPECT_EQ(StatusCode::OK_200, res->status);
  24913. EXPECT_EQ(1, origin_hits.load());
  24914. EXPECT_EQ(1, proxy.connect_hits());
  24915. EXPECT_TRUE(origin_saw_headers.load());
  24916. EXPECT_FALSE(origin_saw_proxy_authz.load())
  24917. << "Proxy-Authorization must not be sent inside the tunnel";
  24918. auto connect_req = proxy.connect_request();
  24919. EXPECT_NE(std::string::npos,
  24920. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  24921. for (const auto &h : origin_headers) {
  24922. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  24923. << h << " must not be sent to the proxy on CONNECT";
  24924. }
  24925. }
  24926. } // namespace proxy_tunnel_test
  24927. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  24928. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24929. [](SSLClient &cli) {
  24930. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24931. cli.set_basic_auth("origin-user", "origin-pass");
  24932. },
  24933. "Basic");
  24934. }
  24935. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  24936. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24937. [](SSLClient &cli) {
  24938. cli.set_proxy_bearer_token_auth("proxy-token");
  24939. cli.set_bearer_token_auth("origin-token");
  24940. },
  24941. "Bearer");
  24942. }
  24943. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  24944. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24945. [](SSLClient &cli) {
  24946. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24947. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  24948. {"Cookie", "sid=origin-session"},
  24949. {"X-Api-Key", "origin-key"}});
  24950. },
  24951. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  24952. }
  24953. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  24954. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  24955. // retry; otherwise proxy creds would be sent to the origin.
  24956. std::atomic<int> origin_hits{0};
  24957. std::atomic<bool> origin_saw_proxy_authz{false};
  24958. proxy_tunnel_test::ScopedSSLServer origin;
  24959. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24960. origin_hits++;
  24961. if (req.has_header("Proxy-Authorization")) {
  24962. origin_saw_proxy_authz = true;
  24963. }
  24964. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24965. res.set_header("Proxy-Authenticate",
  24966. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  24967. "algorithm=MD5");
  24968. });
  24969. origin.listen();
  24970. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  24971. ASSERT_NE(0, proxy.port());
  24972. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  24973. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  24974. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  24975. // and answer with its own status, making this test flaky.
  24976. SSLClient cli("127.0.0.1", origin.port());
  24977. cli.enable_server_certificate_verification(false);
  24978. cli.set_proxy("127.0.0.1", proxy.port());
  24979. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24980. auto res = cli.Get("/x");
  24981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24982. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24983. EXPECT_EQ(1, origin_hits.load());
  24984. EXPECT_FALSE(origin_saw_proxy_authz.load());
  24985. EXPECT_EQ(1, proxy.connect_hits());
  24986. }
  24987. #endif